From b4a2c9849791761c00c9b2a7fa2eb141d25b7af2 Mon Sep 17 00:00:00 2001 From: alam00000 Date: Fri, 20 Mar 2026 21:48:48 +0530 Subject: [PATCH] Add documentation for all PDF tools --- docs/.vitepress/cache/deps/@theme_index.js | 194 +- docs/.vitepress/cache/deps/_metadata.json | 32 +- .../{chunk-2CLQ7TTZ.js => chunk-BRNHR3LR.js} | 6753 ++++++++++------- ...-2CLQ7TTZ.js.map => chunk-BRNHR3LR.js.map} | 0 .../{chunk-LE5NDSFD.js => chunk-H6MPEGKE.js} | 4950 +++++++----- .../cache/deps/chunk-H6MPEGKE.js.map | 7 + .../cache/deps/chunk-LE5NDSFD.js.map | 7 - .../cache/deps/vitepress___@vueuse_core.js | 8 +- ...ess___@vueuse_integrations_useFocusTrap.js | 1017 ++- ...__@vueuse_integrations_useFocusTrap.js.map | 6 +- docs/.vitepress/cache/deps/vue.js | 6 +- docs/.vitepress/config.mts | 150 +- docs/tools/add-attachments.md | 49 + docs/tools/add-blank-page.md | 40 + docs/tools/add-page-labels.md | 53 + docs/tools/add-stamps.md | 45 + docs/tools/add-watermark.md | 70 + docs/tools/adjust-colors.md | 55 + docs/tools/alternate-merge.md | 42 + docs/tools/background-color.md | 45 + docs/tools/bates-numbering.md | 62 + docs/tools/bmp-to-pdf.md | 44 + docs/tools/bookmark.md | 56 + docs/tools/cbz-to-pdf.md | 47 + docs/tools/change-permissions.md | 61 + docs/tools/combine-single-page.md | 55 + docs/tools/compare-pdfs.md | 60 + docs/tools/compress-pdf.md | 69 + docs/tools/crop-pdf.md | 44 + docs/tools/csv-to-pdf.md | 51 + docs/tools/decrypt-pdf.md | 46 + docs/tools/delete-pages.md | 42 + docs/tools/deskew-pdf.md | 46 + docs/tools/digital-sign-pdf.md | 65 + docs/tools/divide-pages.md | 42 + docs/tools/edit-attachments.md | 43 + docs/tools/edit-metadata.md | 58 + docs/tools/edit-pdf.md | 47 + docs/tools/email-to-pdf.md | 50 + docs/tools/encrypt-pdf.md | 64 + docs/tools/epub-to-pdf.md | 44 + docs/tools/excel-to-pdf.md | 55 + docs/tools/extract-attachments.md | 42 + docs/tools/extract-images.md | 45 + docs/tools/extract-pages.md | 41 + docs/tools/extract-tables.md | 46 + docs/tools/fb2-to-pdf.md | 43 + docs/tools/fix-page-size.md | 44 + docs/tools/flatten-pdf.md | 51 + docs/tools/font-to-outline.md | 52 + docs/tools/form-creator.md | 76 + docs/tools/form-filler.md | 47 + docs/tools/header-footer.md | 53 + docs/tools/heic-to-pdf.md | 46 + docs/tools/image-to-pdf.md | 65 + docs/tools/index.md | 260 +- docs/tools/invert-colors.md | 42 + docs/tools/jpg-to-pdf.md | 48 + docs/tools/json-to-pdf.md | 53 + docs/tools/linearize-pdf.md | 49 + docs/tools/markdown-to-pdf.md | 59 + docs/tools/merge-pdf.md | 54 + docs/tools/mobi-to-pdf.md | 43 + docs/tools/n-up-pdf.md | 54 + docs/tools/ocr-pdf.md | 54 + docs/tools/odg-to-pdf.md | 43 + docs/tools/odp-to-pdf.md | 44 + docs/tools/ods-to-pdf.md | 44 + docs/tools/odt-to-pdf.md | 51 + docs/tools/organize-pdf.md | 45 + docs/tools/page-dimensions.md | 53 + docs/tools/page-numbers.md | 48 + docs/tools/pdf-booklet.md | 43 + docs/tools/pdf-layers.md | 46 + docs/tools/pdf-multi-tool.md | 52 + docs/tools/pdf-to-bmp.md | 40 + docs/tools/pdf-to-csv.md | 44 + docs/tools/pdf-to-docx.md | 42 + docs/tools/pdf-to-excel.md | 44 + docs/tools/pdf-to-greyscale.md | 42 + docs/tools/pdf-to-jpg.md | 46 + docs/tools/pdf-to-json.md | 45 + docs/tools/pdf-to-markdown.md | 43 + docs/tools/pdf-to-pdfa.md | 50 + docs/tools/pdf-to-png.md | 42 + docs/tools/pdf-to-svg.md | 43 + docs/tools/pdf-to-text.md | 43 + docs/tools/pdf-to-tiff.md | 43 + docs/tools/pdf-to-webp.md | 43 + docs/tools/pdf-to-zip.md | 41 + docs/tools/pdf-workflow.md | 95 + docs/tools/png-to-pdf.md | 49 + docs/tools/posterize-pdf.md | 53 + docs/tools/powerpoint-to-pdf.md | 55 + docs/tools/prepare-pdf-for-ai.md | 47 + docs/tools/psd-to-pdf.md | 44 + docs/tools/pub-to-pdf.md | 43 + docs/tools/rasterize-pdf.md | 53 + docs/tools/remove-annotations.md | 42 + docs/tools/remove-blank-pages.md | 49 + docs/tools/remove-metadata.md | 50 + docs/tools/remove-restrictions.md | 45 + docs/tools/repair-pdf.md | 56 + docs/tools/reverse-pages.md | 40 + docs/tools/rotate-custom.md | 43 + docs/tools/rotate-pdf.md | 43 + docs/tools/rtf-to-pdf.md | 51 + docs/tools/sanitize-pdf.md | 53 + docs/tools/scanner-effect.md | 57 + docs/tools/sign-pdf.md | 48 + docs/tools/split-pdf.md | 57 + docs/tools/svg-to-pdf.md | 50 + docs/tools/table-of-contents.md | 49 + docs/tools/text-color.md | 45 + docs/tools/tiff-to-pdf.md | 45 + docs/tools/txt-to-pdf.md | 54 + docs/tools/validate-signature-pdf.md | 74 + docs/tools/view-metadata.md | 51 + docs/tools/vsd-to-pdf.md | 45 + docs/tools/webp-to-pdf.md | 49 + docs/tools/word-to-pdf.md | 56 + docs/tools/wpd-to-pdf.md | 42 + docs/tools/wps-to-pdf.md | 42 + docs/tools/xml-to-pdf.md | 44 + docs/tools/xps-to-pdf.md | 43 + 125 files changed, 13507 insertions(+), 5422 deletions(-) rename docs/.vitepress/cache/deps/{chunk-2CLQ7TTZ.js => chunk-BRNHR3LR.js} (58%) rename docs/.vitepress/cache/deps/{chunk-2CLQ7TTZ.js.map => chunk-BRNHR3LR.js.map} (100%) rename docs/.vitepress/cache/deps/{chunk-LE5NDSFD.js => chunk-H6MPEGKE.js} (74%) create mode 100644 docs/.vitepress/cache/deps/chunk-H6MPEGKE.js.map delete mode 100644 docs/.vitepress/cache/deps/chunk-LE5NDSFD.js.map create mode 100644 docs/tools/add-attachments.md create mode 100644 docs/tools/add-blank-page.md create mode 100644 docs/tools/add-page-labels.md create mode 100644 docs/tools/add-stamps.md create mode 100644 docs/tools/add-watermark.md create mode 100644 docs/tools/adjust-colors.md create mode 100644 docs/tools/alternate-merge.md create mode 100644 docs/tools/background-color.md create mode 100644 docs/tools/bates-numbering.md create mode 100644 docs/tools/bmp-to-pdf.md create mode 100644 docs/tools/bookmark.md create mode 100644 docs/tools/cbz-to-pdf.md create mode 100644 docs/tools/change-permissions.md create mode 100644 docs/tools/combine-single-page.md create mode 100644 docs/tools/compare-pdfs.md create mode 100644 docs/tools/compress-pdf.md create mode 100644 docs/tools/crop-pdf.md create mode 100644 docs/tools/csv-to-pdf.md create mode 100644 docs/tools/decrypt-pdf.md create mode 100644 docs/tools/delete-pages.md create mode 100644 docs/tools/deskew-pdf.md create mode 100644 docs/tools/digital-sign-pdf.md create mode 100644 docs/tools/divide-pages.md create mode 100644 docs/tools/edit-attachments.md create mode 100644 docs/tools/edit-metadata.md create mode 100644 docs/tools/edit-pdf.md create mode 100644 docs/tools/email-to-pdf.md create mode 100644 docs/tools/encrypt-pdf.md create mode 100644 docs/tools/epub-to-pdf.md create mode 100644 docs/tools/excel-to-pdf.md create mode 100644 docs/tools/extract-attachments.md create mode 100644 docs/tools/extract-images.md create mode 100644 docs/tools/extract-pages.md create mode 100644 docs/tools/extract-tables.md create mode 100644 docs/tools/fb2-to-pdf.md create mode 100644 docs/tools/fix-page-size.md create mode 100644 docs/tools/flatten-pdf.md create mode 100644 docs/tools/font-to-outline.md create mode 100644 docs/tools/form-creator.md create mode 100644 docs/tools/form-filler.md create mode 100644 docs/tools/header-footer.md create mode 100644 docs/tools/heic-to-pdf.md create mode 100644 docs/tools/image-to-pdf.md create mode 100644 docs/tools/invert-colors.md create mode 100644 docs/tools/jpg-to-pdf.md create mode 100644 docs/tools/json-to-pdf.md create mode 100644 docs/tools/linearize-pdf.md create mode 100644 docs/tools/markdown-to-pdf.md create mode 100644 docs/tools/merge-pdf.md create mode 100644 docs/tools/mobi-to-pdf.md create mode 100644 docs/tools/n-up-pdf.md create mode 100644 docs/tools/ocr-pdf.md create mode 100644 docs/tools/odg-to-pdf.md create mode 100644 docs/tools/odp-to-pdf.md create mode 100644 docs/tools/ods-to-pdf.md create mode 100644 docs/tools/odt-to-pdf.md create mode 100644 docs/tools/organize-pdf.md create mode 100644 docs/tools/page-dimensions.md create mode 100644 docs/tools/page-numbers.md create mode 100644 docs/tools/pdf-booklet.md create mode 100644 docs/tools/pdf-layers.md create mode 100644 docs/tools/pdf-multi-tool.md create mode 100644 docs/tools/pdf-to-bmp.md create mode 100644 docs/tools/pdf-to-csv.md create mode 100644 docs/tools/pdf-to-docx.md create mode 100644 docs/tools/pdf-to-excel.md create mode 100644 docs/tools/pdf-to-greyscale.md create mode 100644 docs/tools/pdf-to-jpg.md create mode 100644 docs/tools/pdf-to-json.md create mode 100644 docs/tools/pdf-to-markdown.md create mode 100644 docs/tools/pdf-to-pdfa.md create mode 100644 docs/tools/pdf-to-png.md create mode 100644 docs/tools/pdf-to-svg.md create mode 100644 docs/tools/pdf-to-text.md create mode 100644 docs/tools/pdf-to-tiff.md create mode 100644 docs/tools/pdf-to-webp.md create mode 100644 docs/tools/pdf-to-zip.md create mode 100644 docs/tools/pdf-workflow.md create mode 100644 docs/tools/png-to-pdf.md create mode 100644 docs/tools/posterize-pdf.md create mode 100644 docs/tools/powerpoint-to-pdf.md create mode 100644 docs/tools/prepare-pdf-for-ai.md create mode 100644 docs/tools/psd-to-pdf.md create mode 100644 docs/tools/pub-to-pdf.md create mode 100644 docs/tools/rasterize-pdf.md create mode 100644 docs/tools/remove-annotations.md create mode 100644 docs/tools/remove-blank-pages.md create mode 100644 docs/tools/remove-metadata.md create mode 100644 docs/tools/remove-restrictions.md create mode 100644 docs/tools/repair-pdf.md create mode 100644 docs/tools/reverse-pages.md create mode 100644 docs/tools/rotate-custom.md create mode 100644 docs/tools/rotate-pdf.md create mode 100644 docs/tools/rtf-to-pdf.md create mode 100644 docs/tools/sanitize-pdf.md create mode 100644 docs/tools/scanner-effect.md create mode 100644 docs/tools/sign-pdf.md create mode 100644 docs/tools/split-pdf.md create mode 100644 docs/tools/svg-to-pdf.md create mode 100644 docs/tools/table-of-contents.md create mode 100644 docs/tools/text-color.md create mode 100644 docs/tools/tiff-to-pdf.md create mode 100644 docs/tools/txt-to-pdf.md create mode 100644 docs/tools/validate-signature-pdf.md create mode 100644 docs/tools/view-metadata.md create mode 100644 docs/tools/vsd-to-pdf.md create mode 100644 docs/tools/webp-to-pdf.md create mode 100644 docs/tools/word-to-pdf.md create mode 100644 docs/tools/wpd-to-pdf.md create mode 100644 docs/tools/wps-to-pdf.md create mode 100644 docs/tools/xml-to-pdf.md create mode 100644 docs/tools/xps-to-pdf.md diff --git a/docs/.vitepress/cache/deps/@theme_index.js b/docs/.vitepress/cache/deps/@theme_index.js index 991f721..bf4cfd8 100644 --- a/docs/.vitepress/cache/deps/@theme_index.js +++ b/docs/.vitepress/cache/deps/@theme_index.js @@ -1,79 +1,74 @@ -import { - useMediaQuery -} from "./chunk-2CLQ7TTZ.js"; -import { - computed, - ref, - shallowRef, - watch -} from "./chunk-LE5NDSFD.js"; +import { useMediaQuery } from './chunk-BRNHR3LR.js'; +import { computed, ref, shallowRef, watch } from './chunk-H6MPEGKE.js'; // node_modules/vitepress/dist/client/theme-default/index.js -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/fonts.css"; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/fonts.css'; // node_modules/vitepress/dist/client/theme-default/without-fonts.js -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/vars.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/base.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/icons.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/utils.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/custom-block.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code-group.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-doc.css"; -import "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-sponsor.css"; -import VPBadge from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue"; -import Layout from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/Layout.vue"; -import { default as default2 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue"; -import { default as default3 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPButton.vue"; -import { default as default4 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPDocAsideSponsors.vue"; -import { default as default5 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPFeatures.vue"; -import { default as default6 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeContent.vue"; -import { default as default7 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeFeatures.vue"; -import { default as default8 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeHero.vue"; -import { default as default9 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeSponsors.vue"; -import { default as default10 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPImage.vue"; -import { default as default11 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPLink.vue"; -import { default as default12 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPNavBarSearch.vue"; -import { default as default13 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPSocialLink.vue"; -import { default as default14 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPSocialLinks.vue"; -import { default as default15 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPSponsors.vue"; -import { default as default16 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamMembers.vue"; -import { default as default17 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamPage.vue"; -import { default as default18 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageSection.vue"; -import { default as default19 } from "/Users/abdullahtapadar/Desktop/workspaceforbento/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageTitle.vue"; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/vars.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/base.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/icons.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/utils.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/custom-block.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-code-group.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-doc.css'; +import '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/styles/components/vp-sponsor.css'; +import VPBadge from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue'; +import Layout from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/Layout.vue'; +import { default as default2 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPBadge.vue'; +import { default as default3 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPButton.vue'; +import { default as default4 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPDocAsideSponsors.vue'; +import { default as default5 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPFeatures.vue'; +import { default as default6 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeContent.vue'; +import { default as default7 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeFeatures.vue'; +import { default as default8 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeHero.vue'; +import { default as default9 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPHomeSponsors.vue'; +import { default as default10 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPImage.vue'; +import { default as default11 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPLink.vue'; +import { default as default12 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPNavBarSearch.vue'; +import { default as default13 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPSocialLink.vue'; +import { default as default14 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPSocialLinks.vue'; +import { default as default15 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPSponsors.vue'; +import { default as default16 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamMembers.vue'; +import { default as default17 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamPage.vue'; +import { default as default18 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageSection.vue'; +import { default as default19 } from '/Users/abdullahtapadar/Desktop/bento-pdf/node_modules/vitepress/dist/client/theme-default/components/VPTeamPageTitle.vue'; // node_modules/vitepress/dist/client/theme-default/composables/local-nav.js -import { onContentUpdated } from "vitepress"; +import { onContentUpdated } from 'vitepress'; // node_modules/vitepress/dist/client/theme-default/composables/outline.js -import { getScrollOffset } from "vitepress"; +import { getScrollOffset } from 'vitepress'; // node_modules/vitepress/dist/client/theme-default/support/utils.js -import { withBase } from "vitepress"; +import { withBase } from 'vitepress'; // node_modules/vitepress/dist/client/theme-default/composables/data.js -import { useData as useData$ } from "vitepress"; +import { useData as useData$ } from 'vitepress'; var useData = useData$; // node_modules/vitepress/dist/client/theme-default/support/utils.js function ensureStartingSlash(path) { - return path.startsWith("/") ? path : `/${path}`; + return path.startsWith('/') ? path : `/${path}`; } // node_modules/vitepress/dist/client/theme-default/support/sidebar.js function getSidebar(_sidebar, path) { - if (Array.isArray(_sidebar)) - return addBase(_sidebar); - if (_sidebar == null) - return []; + if (Array.isArray(_sidebar)) return addBase(_sidebar); + if (_sidebar == null) return []; path = ensureStartingSlash(path); - const dir = Object.keys(_sidebar).sort((a, b) => { - return b.split("/").length - a.split("/").length; - }).find((dir2) => { - return path.startsWith(ensureStartingSlash(dir2)); - }); + const dir = Object.keys(_sidebar) + .sort((a, b) => { + return b.split('/').length - a.split('/').length; + }) + .find((dir2) => { + return path.startsWith(ensureStartingSlash(dir2)); + }); const sidebar = dir ? _sidebar[dir] : []; - return Array.isArray(sidebar) ? addBase(sidebar) : addBase(sidebar.items, sidebar.base); + return Array.isArray(sidebar) + ? addBase(sidebar) + : addBase(sidebar.items, sidebar.base); } function getSidebarGroups(sidebar) { const groups = []; @@ -95,10 +90,8 @@ function addBase(items, _base) { return [...items].map((_item) => { const item = { ..._item }; const base = item.base || _base; - if (base && item.link) - item.link = base + item.link; - if (item.items) - item.items = addBase(item.items, base); + if (base && item.link) item.link = base + item.link; + if (item.items) item.items = addBase(item.items, base); return item; }); } @@ -106,7 +99,7 @@ function addBase(items, _base) { // node_modules/vitepress/dist/client/theme-default/composables/sidebar.js function useSidebar() { const { frontmatter, page, theme: theme2 } = useData(); - const is960 = useMediaQuery("(min-width: 960px)"); + const is960 = useMediaQuery('(min-width: 960px)'); const isOpen = ref(false); const _sidebar = computed(() => { const sidebarConfig = theme2.value.sidebar; @@ -119,18 +112,22 @@ function useSidebar() { sidebar.value = _sidebar.value; }); const hasSidebar = computed(() => { - return frontmatter.value.sidebar !== false && sidebar.value.length > 0 && frontmatter.value.layout !== "home"; + return ( + frontmatter.value.sidebar !== false && + sidebar.value.length > 0 && + frontmatter.value.layout !== 'home' + ); }); const leftAside = computed(() => { if (hasAside) - return frontmatter.value.aside == null ? theme2.value.aside === "left" : frontmatter.value.aside === "left"; + return frontmatter.value.aside == null + ? theme2.value.aside === 'left' + : frontmatter.value.aside === 'left'; return false; }); const hasAside = computed(() => { - if (frontmatter.value.layout === "home") - return false; - if (frontmatter.value.aside != null) - return !!frontmatter.value.aside; + if (frontmatter.value.layout === 'home') return false; + if (frontmatter.value.aside != null) return !!frontmatter.value.aside; return theme2.value.aside !== false; }); const isSidebarEnabled = computed(() => hasSidebar.value && is960.value); @@ -156,7 +153,7 @@ function useSidebar() { isSidebarEnabled, open, close, - toggle + toggle, }; } @@ -165,24 +162,25 @@ var ignoreRE = /\b(?:VPBadge|header-anchor|footnote-ref|ignore-header)\b/; var resolvedHeaders = []; function getHeaders(range) { const headers = [ - ...document.querySelectorAll(".VPDoc :where(h1,h2,h3,h4,h5,h6)") - ].filter((el) => el.id && el.hasChildNodes()).map((el) => { - const level = Number(el.tagName[1]); - return { - element: el, - title: serializeHeader(el), - link: "#" + el.id, - level - }; - }); + ...document.querySelectorAll('.VPDoc :where(h1,h2,h3,h4,h5,h6)'), + ] + .filter((el) => el.id && el.hasChildNodes()) + .map((el) => { + const level = Number(el.tagName[1]); + return { + element: el, + title: serializeHeader(el), + link: '#' + el.id, + level, + }; + }); return resolveHeaders(headers, range); } function serializeHeader(h) { - let ret = ""; + let ret = ''; for (const node of h.childNodes) { if (node.nodeType === 1) { - if (ignoreRE.test(node.className)) - continue; + if (ignoreRE.test(node.className)) continue; ret += node.textContent; } else if (node.nodeType === 3) { ret += node.textContent; @@ -194,8 +192,16 @@ function resolveHeaders(headers, range) { if (range === false) { return []; } - const levelsRange = (typeof range === "object" && !Array.isArray(range) ? range.level : range) || 2; - const [high, low] = typeof levelsRange === "number" ? [levelsRange, levelsRange] : levelsRange === "deep" ? [2, 6] : levelsRange; + const levelsRange = + (typeof range === 'object' && !Array.isArray(range) + ? range.level + : range) || 2; + const [high, low] = + typeof levelsRange === 'number' + ? [levelsRange, levelsRange] + : levelsRange === 'deep' + ? [2, 6] + : levelsRange; return buildTree(headers, high, low); } function buildTree(data, min, max) { @@ -209,17 +215,17 @@ function buildTree(data, min, max) { stack.pop(); parent = stack[stack.length - 1]; } - if (node.element.classList.contains("ignore-header") || parent && "shouldIgnore" in parent) { + if ( + node.element.classList.contains('ignore-header') || + (parent && 'shouldIgnore' in parent) + ) { stack.push({ level: node.level, shouldIgnore: true }); return; } - if (node.level > max || node.level < min) - return; + if (node.level > max || node.level < min) return; resolvedHeaders.push({ element: node.element, link: node.link }); - if (parent) - parent.children.push(node); - else - result.push(node); + if (parent) parent.children.push(node); + else result.push(node); stack.push(node); }); return result; @@ -233,11 +239,13 @@ function useLocalNav() { return headers.value.length > 0; }); onContentUpdated(() => { - headers.value = getHeaders(frontmatter.value.outline ?? theme2.value.outline); + headers.value = getHeaders( + frontmatter.value.outline ?? theme2.value.outline + ); }); return { headers, - hasLocalNav + hasLocalNav, }; } @@ -245,8 +253,8 @@ function useLocalNav() { var theme = { Layout, enhanceApp: ({ app }) => { - app.component("Badge", VPBadge); - } + app.component('Badge', VPBadge); + }, }; var without_fonts_default = theme; export { @@ -270,6 +278,6 @@ export { default19 as VPTeamPageTitle, without_fonts_default as default, useLocalNav, - useSidebar + useSidebar, }; //# sourceMappingURL=@theme_index.js.map diff --git a/docs/.vitepress/cache/deps/_metadata.json b/docs/.vitepress/cache/deps/_metadata.json index ead6f83..37112a4 100644 --- a/docs/.vitepress/cache/deps/_metadata.json +++ b/docs/.vitepress/cache/deps/_metadata.json @@ -1,58 +1,58 @@ { - "hash": "b8473a4c", - "configHash": "de601e5a", - "lockfileHash": "97b635bf", - "browserHash": "6dc79743", + "hash": "cbe76ac1", + "configHash": "fcacb6fc", + "lockfileHash": "25b6b516", + "browserHash": "e3bcae4a", "optimized": { "vue": { "src": "../../../../node_modules/vue/dist/vue.runtime.esm-bundler.js", "file": "vue.js", - "fileHash": "82d9bd70", + "fileHash": "d430f9d5", "needsInterop": false }, "vitepress > @vue/devtools-api": { "src": "../../../../node_modules/@vue/devtools-api/dist/index.js", "file": "vitepress___@vue_devtools-api.js", - "fileHash": "776db5f7", + "fileHash": "cdc3240f", "needsInterop": false }, "vitepress > @vueuse/core": { "src": "../../../../node_modules/@vueuse/core/index.mjs", "file": "vitepress___@vueuse_core.js", - "fileHash": "5b890910", + "fileHash": "9c54fae4", "needsInterop": false }, "vitepress > @vueuse/integrations/useFocusTrap": { "src": "../../../../node_modules/@vueuse/integrations/useFocusTrap.mjs", "file": "vitepress___@vueuse_integrations_useFocusTrap.js", - "fileHash": "0798c805", + "fileHash": "dcb2d016", "needsInterop": false }, "vitepress > mark.js/src/vanilla.js": { "src": "../../../../node_modules/mark.js/src/vanilla.js", "file": "vitepress___mark__js_src_vanilla__js.js", - "fileHash": "ce575f5c", + "fileHash": "89ac005f", "needsInterop": false }, "vitepress > minisearch": { "src": "../../../../node_modules/minisearch/dist/es/index.js", "file": "vitepress___minisearch.js", - "fileHash": "97a74ec0", + "fileHash": "dcc8fa95", "needsInterop": false }, "@theme/index": { "src": "../../../../node_modules/vitepress/dist/client/theme-default/index.js", "file": "@theme_index.js", - "fileHash": "725ded83", + "fileHash": "12a406fc", "needsInterop": false } }, "chunks": { - "chunk-2CLQ7TTZ": { - "file": "chunk-2CLQ7TTZ.js" + "chunk-BRNHR3LR": { + "file": "chunk-BRNHR3LR.js" }, - "chunk-LE5NDSFD": { - "file": "chunk-LE5NDSFD.js" + "chunk-H6MPEGKE": { + "file": "chunk-H6MPEGKE.js" } } -} \ No newline at end of file +} diff --git a/docs/.vitepress/cache/deps/chunk-2CLQ7TTZ.js b/docs/.vitepress/cache/deps/chunk-BRNHR3LR.js similarity index 58% rename from docs/.vitepress/cache/deps/chunk-2CLQ7TTZ.js rename to docs/.vitepress/cache/deps/chunk-BRNHR3LR.js index 8cd09fb..e40766f 100644 --- a/docs/.vitepress/cache/deps/chunk-2CLQ7TTZ.js +++ b/docs/.vitepress/cache/deps/chunk-BRNHR3LR.js @@ -34,19 +34,23 @@ import { toValue, unref, watch, - watchEffect -} from "./chunk-LE5NDSFD.js"; + watchEffect, +} from './chunk-H6MPEGKE.js'; // node_modules/@vueuse/shared/index.mjs function computedEager(fn, options) { var _a; const result = shallowRef(); - watchEffect(() => { - result.value = fn(); - }, { - ...options, - flush: (_a = options == null ? void 0 : options.flush) != null ? _a : "sync" - }); + watchEffect( + () => { + result.value = fn(); + }, + { + ...options, + flush: + (_a = options == null ? void 0 : options.flush) != null ? _a : 'sync', + } + ); return readonly(result); } function computedWithControl(source, fn) { @@ -58,9 +62,9 @@ function computedWithControl(source, fn) { dirty.value = true; trigger(); }; - watch(source, update, { flush: "sync" }); - const get2 = typeof fn === "function" ? fn : fn.get; - const set2 = typeof fn === "function" ? void 0 : fn.set; + watch(source, update, { flush: 'sync' }); + const get2 = typeof fn === 'function' ? fn : fn.get; + const set2 = typeof fn === 'function' ? void 0 : fn.set; const result = customRef((_track, _trigger) => { track = _track; trigger = _trigger; @@ -75,11 +79,10 @@ function computedWithControl(source, fn) { }, set(v2) { set2 == null ? void 0 : set2(v2); - } + }, }; }); - if (Object.isExtensible(result)) - result.trigger = update; + if (Object.isExtensible(result)) result.trigger = update; return result; } function tryOnScopeDispose(fn) { @@ -102,7 +105,7 @@ function createEventHook() { const offFn = () => off(fn); tryOnScopeDispose(offFn); return { - off: offFn + off: offFn, }; }; const trigger = (...args) => { @@ -112,7 +115,7 @@ function createEventHook() { on, off, trigger, - clear + clear, }; } function createGlobalState(stateFactory) { @@ -133,16 +136,19 @@ var injectLocal = (...args) => { const key = args[0]; const instance = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy; if (instance == null && !hasInjectionContext()) - throw new Error("injectLocal must be called in setup"); - if (instance && localProvidedStateMap.has(instance) && key in localProvidedStateMap.get(instance)) + throw new Error('injectLocal must be called in setup'); + if ( + instance && + localProvidedStateMap.has(instance) && + key in localProvidedStateMap.get(instance) + ) return localProvidedStateMap.get(instance)[key]; return inject(...args); }; var provideLocal = (key, value) => { var _a; const instance = (_a = getCurrentInstance()) == null ? void 0 : _a.proxy; - if (instance == null) - throw new Error("provideLocal must be called in setup"); + if (instance == null) throw new Error('provideLocal must be called in setup'); if (!localProvidedStateMap.has(instance)) localProvidedStateMap.set(instance, /* @__PURE__ */ Object.create(null)); const localProvidedState = localProvidedStateMap.get(instance); @@ -150,7 +156,9 @@ var provideLocal = (key, value) => { provide(key, value); }; function createInjectionState(composable, options) { - const key = (options == null ? void 0 : options.injectionKey) || Symbol(composable.name || "InjectionState"); + const key = + (options == null ? void 0 : options.injectionKey) || + Symbol(composable.name || 'InjectionState'); const defaultValue = options == null ? void 0 : options.defaultValue; const useProvidingState = (...args) => { const state = composable(...args); @@ -191,8 +199,7 @@ function createSharedComposable(composable) { } function extendRef(ref2, extend, { enumerable = false, unwrap = true } = {}) { for (const [key, value] of Object.entries(extend)) { - if (key === "value") - continue; + if (key === 'value') continue; if (isRef(value) && unwrap) { Object.defineProperty(ref2, key, { get() { @@ -201,7 +208,7 @@ function extendRef(ref2, extend, { enumerable = false, unwrap = true } = {}) { set(v) { value.value = v; }, - enumerable + enumerable, }); } else { Object.defineProperty(ref2, key, { value, enumerable }); @@ -210,15 +217,14 @@ function extendRef(ref2, extend, { enumerable = false, unwrap = true } = {}) { return ref2; } function get(obj, key) { - if (key == null) - return unref(obj); + if (key == null) return unref(obj); return unref(obj)[key]; } function isDefined(v) { return unref(v) != null; } function makeDestructurable(obj, arr) { - if (typeof Symbol !== "undefined") { + if (typeof Symbol !== 'undefined') { const clone = { ...obj }; Object.defineProperty(clone, Symbol.iterator, { enumerable: false, @@ -227,10 +233,10 @@ function makeDestructurable(obj, arr) { return { next: () => ({ value: arr[index++], - done: index > arr.length - }) + done: index > arr.length, + }), }; - } + }, }); return clone; } else { @@ -238,9 +244,17 @@ function makeDestructurable(obj, arr) { } } function reactify(fn, options) { - const unrefFn = (options == null ? void 0 : options.computedGetter) === false ? unref : toValue; - return function(...args) { - return computed(() => fn.apply(this, args.map((i) => unrefFn(i)))); + const unrefFn = + (options == null ? void 0 : options.computedGetter) === false + ? unref + : toValue; + return function (...args) { + return computed(() => + fn.apply( + this, + args.map((i) => unrefFn(i)) + ) + ); }; } function reactifyObject(obj, optionsOrKeys = {}) { @@ -252,49 +266,51 @@ function reactifyObject(obj, optionsOrKeys = {}) { options = optionsOrKeys; const { includeOwnProperties = true } = optionsOrKeys; keys2.push(...Object.keys(obj)); - if (includeOwnProperties) - keys2.push(...Object.getOwnPropertyNames(obj)); + if (includeOwnProperties) keys2.push(...Object.getOwnPropertyNames(obj)); } return Object.fromEntries( keys2.map((key) => { const value = obj[key]; return [ key, - typeof value === "function" ? reactify(value.bind(obj), options) : value + typeof value === 'function' + ? reactify(value.bind(obj), options) + : value, ]; }) ); } function toReactive(objectRef) { - if (!isRef(objectRef)) - return reactive(objectRef); - const proxy = new Proxy({}, { - get(_, p, receiver) { - return unref(Reflect.get(objectRef.value, p, receiver)); - }, - set(_, p, value) { - if (isRef(objectRef.value[p]) && !isRef(value)) - objectRef.value[p].value = value; - else - objectRef.value[p] = value; - return true; - }, - deleteProperty(_, p) { - return Reflect.deleteProperty(objectRef.value, p); - }, - has(_, p) { - return Reflect.has(objectRef.value, p); - }, - ownKeys() { - return Object.keys(objectRef.value); - }, - getOwnPropertyDescriptor() { - return { - enumerable: true, - configurable: true - }; + if (!isRef(objectRef)) return reactive(objectRef); + const proxy = new Proxy( + {}, + { + get(_, p, receiver) { + return unref(Reflect.get(objectRef.value, p, receiver)); + }, + set(_, p, value) { + if (isRef(objectRef.value[p]) && !isRef(value)) + objectRef.value[p].value = value; + else objectRef.value[p] = value; + return true; + }, + deleteProperty(_, p) { + return Reflect.deleteProperty(objectRef.value, p); + }, + has(_, p) { + return Reflect.has(objectRef.value, p); + }, + ownKeys() { + return Object.keys(objectRef.value); + }, + getOwnPropertyDescriptor() { + return { + enumerable: true, + configurable: true, + }; + }, } - }); + ); return reactive(proxy); } function reactiveComputed(fn) { @@ -303,23 +319,33 @@ function reactiveComputed(fn) { function reactiveOmit(obj, ...keys2) { const flatKeys = keys2.flat(); const predicate = flatKeys[0]; - return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs(obj)).filter(([k, v]) => !predicate(toValue(v), k))) : Object.fromEntries(Object.entries(toRefs(obj)).filter((e) => !flatKeys.includes(e[0])))); + return reactiveComputed(() => + typeof predicate === 'function' + ? Object.fromEntries( + Object.entries(toRefs(obj)).filter( + ([k, v]) => !predicate(toValue(v), k) + ) + ) + : Object.fromEntries( + Object.entries(toRefs(obj)).filter((e) => !flatKeys.includes(e[0])) + ) + ); } -var isClient = typeof window !== "undefined" && typeof document !== "undefined"; -var isWorker = typeof WorkerGlobalScope !== "undefined" && globalThis instanceof WorkerGlobalScope; -var isDef = (val) => typeof val !== "undefined"; +var isClient = typeof window !== 'undefined' && typeof document !== 'undefined'; +var isWorker = + typeof WorkerGlobalScope !== 'undefined' && + globalThis instanceof WorkerGlobalScope; +var isDef = (val) => typeof val !== 'undefined'; var notNullish = (val) => val != null; var assert = (condition, ...infos) => { - if (!condition) - console.warn(...infos); + if (!condition) console.warn(...infos); }; var toString = Object.prototype.toString; -var isObject = (val) => toString.call(val) === "[object Object]"; +var isObject = (val) => toString.call(val) === '[object Object]'; var now = () => Date.now(); var timestamp = () => +Date.now(); var clamp = (n, min, max) => Math.min(max, Math.max(min, n)); -var noop = () => { -}; +var noop = () => {}; var rand = (min, max) => { min = Math.ceil(min); max = Math.floor(max); @@ -329,12 +355,28 @@ var hasOwn = (val, key) => Object.prototype.hasOwnProperty.call(val, key); var isIOS = getIsIOS(); function getIsIOS() { var _a, _b; - return isClient && ((_a = window == null ? void 0 : window.navigator) == null ? void 0 : _a.userAgent) && (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || ((_b = window == null ? void 0 : window.navigator) == null ? void 0 : _b.maxTouchPoints) > 2 && /iPad|Macintosh/.test(window == null ? void 0 : window.navigator.userAgent)); + return ( + isClient && + ((_a = window == null ? void 0 : window.navigator) == null + ? void 0 + : _a.userAgent) && + (/iP(?:ad|hone|od)/.test(window.navigator.userAgent) || + (((_b = window == null ? void 0 : window.navigator) == null + ? void 0 + : _b.maxTouchPoints) > 2 && + /iPad|Macintosh/.test( + window == null ? void 0 : window.navigator.userAgent + ))) + ); } function createFilterWrapper(filter, fn) { function wrapper(...args) { return new Promise((resolve, reject) => { - Promise.resolve(filter(() => fn.apply(this, args), { fn, thisArg: this, args })).then(resolve).catch(reject); + Promise.resolve( + filter(() => fn.apply(this, args), { fn, thisArg: this, args }) + ) + .then(resolve) + .catch(reject); }); } return wrapper; @@ -355,9 +397,8 @@ function debounceFilter(ms, options = {}) { const filter = (invoke2) => { const duration = toValue(ms); const maxDuration = toValue(options.maxWait); - if (timer) - _clearTimeout(timer); - if (duration <= 0 || maxDuration !== void 0 && maxDuration <= 0) { + if (timer) _clearTimeout(timer); + if (duration <= 0 || (maxDuration !== void 0 && maxDuration <= 0)) { if (maxTimer) { _clearTimeout(maxTimer); maxTimer = null; @@ -369,15 +410,13 @@ function debounceFilter(ms, options = {}) { lastInvoker = invoke2; if (maxDuration && !maxTimer) { maxTimer = setTimeout(() => { - if (timer) - _clearTimeout(timer); + if (timer) _clearTimeout(timer); maxTimer = null; resolve(lastInvoker()); }, maxDuration); } timer = setTimeout(() => { - if (maxTimer) - _clearTimeout(maxTimer); + if (maxTimer) _clearTimeout(maxTimer); maxTimer = null; resolve(invoke2()); }, duration); @@ -395,10 +434,14 @@ function throttleFilter(...args) { let trailing; let leading; let rejectOnCancel; - if (!isRef(args[0]) && typeof args[0] === "object") - ({ delay: ms, trailing = true, leading = true, rejectOnCancel = false } = args[0]); - else - [ms, trailing = true, leading = true, rejectOnCancel = false] = args; + if (!isRef(args[0]) && typeof args[0] === 'object') + ({ + delay: ms, + trailing = true, + leading = true, + rejectOnCancel = false, + } = args[0]); + else [ms, trailing = true, leading = true, rejectOnCancel = false] = args; const clear = () => { if (timer) { clearTimeout(timer); @@ -411,7 +454,7 @@ function throttleFilter(...args) { const duration = toValue(ms); const elapsed = Date.now() - lastExec; const invoke2 = () => { - return lastValue = _invoke(); + return (lastValue = _invoke()); }; clear(); if (duration <= 0) { @@ -424,26 +467,27 @@ function throttleFilter(...args) { } else if (trailing) { lastValue = new Promise((resolve, reject) => { lastRejector = rejectOnCancel ? reject : resolve; - timer = setTimeout(() => { - lastExec = Date.now(); - isLeading = true; - resolve(invoke2()); - clear(); - }, Math.max(0, duration - elapsed)); + timer = setTimeout( + () => { + lastExec = Date.now(); + isLeading = true; + resolve(invoke2()); + clear(); + }, + Math.max(0, duration - elapsed) + ); }); } if (!leading && !timer) - timer = setTimeout(() => isLeading = true, duration); + timer = setTimeout(() => (isLeading = true), duration); isLeading = false; return lastValue; }; return filter; } function pausableFilter(extendFilter = bypassFilter, options = {}) { - const { - initialState = "active" - } = options; - const isActive = toRef2(initialState === "active"); + const { initialState = 'active' } = options; + const isActive = toRef2(initialState === 'active'); function pause() { isActive.value = false; } @@ -451,8 +495,7 @@ function pausableFilter(extendFilter = bypassFilter, options = {}) { isActive.value = true; } const eventFilter = (...args) => { - if (isActive.value) - extendFilter(...args); + if (isActive.value) extendFilter(...args); }; return { isActive: readonly(isActive), pause, resume, eventFilter }; } @@ -464,17 +507,17 @@ function cacheStringFunction(fn) { }; } var hyphenateRE = /\B([A-Z])/g; -var hyphenate = cacheStringFunction((str) => str.replace(hyphenateRE, "-$1").toLowerCase()); +var hyphenate = cacheStringFunction((str) => + str.replace(hyphenateRE, '-$1').toLowerCase() +); var camelizeRE = /-(\w)/g; var camelize = cacheStringFunction((str) => { - return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : ""); + return str.replace(camelizeRE, (_, c) => (c ? c.toUpperCase() : '')); }); -function promiseTimeout(ms, throwOnTimeout = false, reason = "Timeout") { +function promiseTimeout(ms, throwOnTimeout = false, reason = 'Timeout') { return new Promise((resolve, reject) => { - if (throwOnTimeout) - setTimeout(() => reject(reason), ms); - else - setTimeout(resolve, ms); + if (throwOnTimeout) setTimeout(() => reject(reason), ms); + else setTimeout(resolve, ms); }); } function identity(arg) { @@ -483,15 +526,13 @@ function identity(arg) { function createSingletonPromise(fn) { let _promise; function wrapper() { - if (!_promise) - _promise = fn(); + if (!_promise) _promise = fn(); return _promise; } wrapper.reset = async () => { const _prev = _promise; _promise = void 0; - if (_prev) - await _prev; + if (_prev) await _prev; }; return wrapper; } @@ -503,31 +544,33 @@ function containsProp(obj, ...props) { } function increaseWithUnit(target, delta) { var _a; - if (typeof target === "number") - return target + delta; - const value = ((_a = target.match(/^-?\d+\.?\d*/)) == null ? void 0 : _a[0]) || ""; + if (typeof target === 'number') return target + delta; + const value = + ((_a = target.match(/^-?\d+\.?\d*/)) == null ? void 0 : _a[0]) || ''; const unit = target.slice(value.length); const result = Number.parseFloat(value) + delta; - if (Number.isNaN(result)) - return target; + if (Number.isNaN(result)) return target; return result + unit; } function pxValue(px) { - return px.endsWith("rem") ? Number.parseFloat(px) * 16 : Number.parseFloat(px); + return px.endsWith('rem') + ? Number.parseFloat(px) * 16 + : Number.parseFloat(px); } function objectPick(obj, keys2, omitUndefined = false) { return keys2.reduce((n, k) => { if (k in obj) { - if (!omitUndefined || obj[k] !== void 0) - n[k] = obj[k]; + if (!omitUndefined || obj[k] !== void 0) n[k] = obj[k]; } return n; }, {}); } function objectOmit(obj, keys2, omitUndefined = false) { - return Object.fromEntries(Object.entries(obj).filter(([key, value]) => { - return (!omitUndefined || value !== void 0) && !keys2.includes(key); - })); + return Object.fromEntries( + Object.entries(obj).filter(([key, value]) => { + return (!omitUndefined || value !== void 0) && !keys2.includes(key); + }) + ); } function objectEntries(obj) { return Object.entries(obj); @@ -539,25 +582,35 @@ function toArray(value) { return Array.isArray(value) ? value : [value]; } function toRef2(...args) { - if (args.length !== 1) - return toRef(...args); + if (args.length !== 1) return toRef(...args); const r = args[0]; - return typeof r === "function" ? readonly(customRef(() => ({ get: r, set: noop }))) : ref(r); + return typeof r === 'function' + ? readonly(customRef(() => ({ get: r, set: noop }))) + : ref(r); } var resolveRef = toRef2; function reactivePick(obj, ...keys2) { const flatKeys = keys2.flat(); const predicate = flatKeys[0]; - return reactiveComputed(() => typeof predicate === "function" ? Object.fromEntries(Object.entries(toRefs(obj)).filter(([k, v]) => predicate(toValue(v), k))) : Object.fromEntries(flatKeys.map((k) => [k, toRef2(obj, k)]))); + return reactiveComputed(() => + typeof predicate === 'function' + ? Object.fromEntries( + Object.entries(toRefs(obj)).filter(([k, v]) => + predicate(toValue(v), k) + ) + ) + : Object.fromEntries(flatKeys.map((k) => [k, toRef2(obj, k)])) + ); } function refAutoReset(defaultValue, afterMs = 1e4) { return customRef((track, trigger) => { let value = toValue(defaultValue); let timer; - const resetAfter = () => setTimeout(() => { - value = toValue(defaultValue); - trigger(); - }, toValue(afterMs)); + const resetAfter = () => + setTimeout(() => { + value = toValue(defaultValue); + trigger(); + }, toValue(afterMs)); tryOnScopeDispose(() => { clearTimeout(timer); }); @@ -571,21 +624,22 @@ function refAutoReset(defaultValue, afterMs = 1e4) { trigger(); clearTimeout(timer); timer = resetAfter(); - } + }, }; }); } function useDebounceFn(fn, ms = 200, options = {}) { - return createFilterWrapper( - debounceFilter(ms, options), - fn - ); + return createFilterWrapper(debounceFilter(ms, options), fn); } function refDebounced(value, ms = 200, options = {}) { const debounced = ref(value.value); - const updater = useDebounceFn(() => { - debounced.value = value.value; - }, ms, options); + const updater = useDebounceFn( + () => { + debounced.value = value.value; + }, + ms, + options + ); watch(value, () => updater()); return debounced; } @@ -597,22 +651,32 @@ function refDefault(source, defaultValue) { }, set(value) { source.value = value; - } + }, }); } -function useThrottleFn(fn, ms = 200, trailing = false, leading = true, rejectOnCancel = false) { +function useThrottleFn( + fn, + ms = 200, + trailing = false, + leading = true, + rejectOnCancel = false +) { return createFilterWrapper( throttleFilter(ms, trailing, leading, rejectOnCancel), fn ); } function refThrottled(value, delay = 200, trailing = true, leading = true) { - if (delay <= 0) - return value; + if (delay <= 0) return value; const throttled = ref(value.value); - const updater = useThrottleFn(() => { - throttled.value = value.value; - }, delay, trailing, leading); + const updater = useThrottleFn( + () => { + throttled.value = value.value; + }, + delay, + trailing, + leading + ); watch(value, () => updater()); return throttled; } @@ -629,25 +693,26 @@ function refWithControl(initial, options = {}) { }, set(v) { set2(v); - } + }, }; }); function get2(tracking = true) { - if (tracking) - track(); + if (tracking) track(); return source; } function set2(value, triggering = true) { var _a, _b; - if (value === source) - return; + if (value === source) return; const old = source; - if (((_a = options.onBeforeChange) == null ? void 0 : _a.call(options, value, old)) === false) + if ( + ((_a = options.onBeforeChange) == null + ? void 0 + : _a.call(options, value, old)) === false + ) return; source = value; (_b = options.onChanged) == null ? void 0 : _b.call(options, value, old); - if (triggering) - trigger(); + if (triggering) trigger(); } const untrackedGet = () => get2(false); const silentSet = (v) => set2(v, false); @@ -661,7 +726,7 @@ function refWithControl(initial, options = {}) { untrackedGet, silentSet, peek, - lay + lay, }, { enumerable: true } ); @@ -678,68 +743,60 @@ function set(...args) { } } function watchWithFilter(source, cb, options = {}) { - const { - eventFilter = bypassFilter, - ...watchOptions - } = options; - return watch( - source, - createFilterWrapper( - eventFilter, - cb - ), - watchOptions - ); + const { eventFilter = bypassFilter, ...watchOptions } = options; + return watch(source, createFilterWrapper(eventFilter, cb), watchOptions); } function watchPausable(source, cb, options = {}) { const { eventFilter: filter, - initialState = "active", + initialState = 'active', ...watchOptions } = options; - const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { initialState }); - const stop = watchWithFilter( - source, - cb, - { - ...watchOptions, - eventFilter - } - ); + const { eventFilter, pause, resume, isActive } = pausableFilter(filter, { + initialState, + }); + const stop = watchWithFilter(source, cb, { + ...watchOptions, + eventFilter, + }); return { stop, pause, resume, isActive }; } function syncRef(left, right, ...[options]) { const { - flush = "sync", + flush = 'sync', deep = false, immediate = true, - direction = "both", - transform = {} + direction = 'both', + transform = {}, } = options || {}; const watchers = []; - const transformLTR = "ltr" in transform && transform.ltr || ((v) => v); - const transformRTL = "rtl" in transform && transform.rtl || ((v) => v); - if (direction === "both" || direction === "ltr") { - watchers.push(watchPausable( - left, - (newValue) => { - watchers.forEach((w) => w.pause()); - right.value = transformLTR(newValue); - watchers.forEach((w) => w.resume()); - }, - { flush, deep, immediate } - )); + const transformLTR = ('ltr' in transform && transform.ltr) || ((v) => v); + const transformRTL = ('rtl' in transform && transform.rtl) || ((v) => v); + if (direction === 'both' || direction === 'ltr') { + watchers.push( + watchPausable( + left, + (newValue) => { + watchers.forEach((w) => w.pause()); + right.value = transformLTR(newValue); + watchers.forEach((w) => w.resume()); + }, + { flush, deep, immediate } + ) + ); } - if (direction === "both" || direction === "rtl") { - watchers.push(watchPausable( - right, - (newValue) => { - watchers.forEach((w) => w.pause()); - left.value = transformRTL(newValue); - watchers.forEach((w) => w.resume()); - }, - { flush, deep, immediate } - )); + if (direction === 'both' || direction === 'rtl') { + watchers.push( + watchPausable( + right, + (newValue) => { + watchers.forEach((w) => w.pause()); + left.value = transformRTL(newValue); + watchers.forEach((w) => w.resume()); + }, + { flush, deep, immediate } + ) + ); } const stop = () => { watchers.forEach((w) => w.stop()); @@ -747,22 +804,19 @@ function syncRef(left, right, ...[options]) { return stop; } function syncRefs(source, targets, options = {}) { - const { - flush = "sync", - deep = false, - immediate = true - } = options; + const { flush = 'sync', deep = false, immediate = true } = options; const targetsArray = toArray(targets); return watch( source, - (newValue) => targetsArray.forEach((target) => target.value = newValue), + (newValue) => targetsArray.forEach((target) => (target.value = newValue)), { flush, deep, immediate } ); } function toRefs2(objectRef, options = {}) { - if (!isRef(objectRef)) - return toRefs(objectRef); - const result = Array.isArray(objectRef.value) ? Array.from({ length: objectRef.value.length }) : {}; + if (!isRef(objectRef)) return toRefs(objectRef); + const result = Array.isArray(objectRef.value) + ? Array.from({ length: objectRef.value.length }) + : {}; for (const key in objectRef.value) { result[key] = customRef(() => ({ get() { @@ -770,7 +824,8 @@ function toRefs2(objectRef, options = {}) { }, set(v) { var _a; - const replaceRef = (_a = toValue(options.replaceRef)) != null ? _a : true; + const replaceRef = + (_a = toValue(options.replaceRef)) != null ? _a : true; if (replaceRef) { if (Array.isArray(objectRef.value)) { const copy = [...objectRef.value]; @@ -778,13 +833,16 @@ function toRefs2(objectRef, options = {}) { objectRef.value = copy; } else { const newObject = { ...objectRef.value, [key]: v }; - Object.setPrototypeOf(newObject, Object.getPrototypeOf(objectRef.value)); + Object.setPrototypeOf( + newObject, + Object.getPrototypeOf(objectRef.value) + ); objectRef.value = newObject; } } else { objectRef.value[key] = v; } - } + }, })); } return result; @@ -793,93 +851,92 @@ var toValue2 = toValue; var resolveUnref = toValue; function tryOnBeforeMount(fn, sync = true, target) { const instance = getLifeCycleTarget(target); - if (instance) - onBeforeMount(fn, target); - else if (sync) - fn(); - else - nextTick(fn); + if (instance) onBeforeMount(fn, target); + else if (sync) fn(); + else nextTick(fn); } function tryOnBeforeUnmount(fn, target) { const instance = getLifeCycleTarget(target); - if (instance) - onBeforeUnmount(fn, target); + if (instance) onBeforeUnmount(fn, target); } function tryOnMounted(fn, sync = true, target) { const instance = getLifeCycleTarget(); - if (instance) - onMounted(fn, target); - else if (sync) - fn(); - else - nextTick(fn); + if (instance) onMounted(fn, target); + else if (sync) fn(); + else nextTick(fn); } function tryOnUnmounted(fn, target) { const instance = getLifeCycleTarget(target); - if (instance) - onUnmounted(fn, target); + if (instance) onUnmounted(fn, target); } function createUntil(r, isNot = false) { - function toMatch(condition, { flush = "sync", deep = false, timeout, throwOnTimeout } = {}) { + function toMatch( + condition, + { flush = 'sync', deep = false, timeout, throwOnTimeout } = {} + ) { let stop = null; const watcher = new Promise((resolve) => { stop = watch( r, (v) => { if (condition(v) !== isNot) { - if (stop) - stop(); - else - nextTick(() => stop == null ? void 0 : stop()); + if (stop) stop(); + else nextTick(() => (stop == null ? void 0 : stop())); resolve(v); } }, { flush, deep, - immediate: true + immediate: true, } ); }); const promises = [watcher]; if (timeout != null) { promises.push( - promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => stop == null ? void 0 : stop()) + promiseTimeout(timeout, throwOnTimeout) + .then(() => toValue(r)) + .finally(() => (stop == null ? void 0 : stop())) ); } return Promise.race(promises); } function toBe(value, options) { - if (!isRef(value)) - return toMatch((v) => v === value, options); - const { flush = "sync", deep = false, timeout, throwOnTimeout } = options != null ? options : {}; + if (!isRef(value)) return toMatch((v) => v === value, options); + const { + flush = 'sync', + deep = false, + timeout, + throwOnTimeout, + } = options != null ? options : {}; let stop = null; const watcher = new Promise((resolve) => { stop = watch( [r, value], ([v1, v2]) => { if (isNot !== (v1 === v2)) { - if (stop) - stop(); - else - nextTick(() => stop == null ? void 0 : stop()); + if (stop) stop(); + else nextTick(() => (stop == null ? void 0 : stop())); resolve(v1); } }, { flush, deep, - immediate: true + immediate: true, } ); }); const promises = [watcher]; if (timeout != null) { promises.push( - promiseTimeout(timeout, throwOnTimeout).then(() => toValue(r)).finally(() => { - stop == null ? void 0 : stop(); - return toValue(r); - }) + promiseTimeout(timeout, throwOnTimeout) + .then(() => toValue(r)) + .finally(() => { + stop == null ? void 0 : stop(); + return toValue(r); + }) ); } return Promise.race(promises); @@ -920,7 +977,7 @@ function createUntil(r, isNot = false) { changedTimes, get not() { return createUntil(r, !isNot); - } + }, }; return instance; } else { @@ -935,7 +992,7 @@ function createUntil(r, isNot = false) { changedTimes, get not() { return createUntil(r, !isNot); - } + }, }; return instance; } @@ -951,50 +1008,81 @@ function useArrayDifference(...args) { const list = args[0]; const values = args[1]; let compareFn = (_a = args[2]) != null ? _a : defaultComparator; - const { - symmetric = false - } = (_b = args[3]) != null ? _b : {}; - if (typeof compareFn === "string") { + const { symmetric = false } = (_b = args[3]) != null ? _b : {}; + if (typeof compareFn === 'string') { const key = compareFn; compareFn = (value, othVal) => value[key] === othVal[key]; } - const diff1 = computed(() => toValue(list).filter((x) => toValue(values).findIndex((y) => compareFn(x, y)) === -1)); + const diff1 = computed(() => + toValue(list).filter( + (x) => toValue(values).findIndex((y) => compareFn(x, y)) === -1 + ) + ); if (symmetric) { - const diff2 = computed(() => toValue(values).filter((x) => toValue(list).findIndex((y) => compareFn(x, y)) === -1)); - return computed(() => symmetric ? [...toValue(diff1), ...toValue(diff2)] : toValue(diff1)); + const diff2 = computed(() => + toValue(values).filter( + (x) => toValue(list).findIndex((y) => compareFn(x, y)) === -1 + ) + ); + return computed(() => + symmetric ? [...toValue(diff1), ...toValue(diff2)] : toValue(diff1) + ); } else { return diff1; } } function useArrayEvery(list, fn) { - return computed(() => toValue(list).every((element, index, array) => fn(toValue(element), index, array))); + return computed(() => + toValue(list).every((element, index, array) => + fn(toValue(element), index, array) + ) + ); } function useArrayFilter(list, fn) { - return computed(() => toValue(list).map((i) => toValue(i)).filter(fn)); + return computed(() => + toValue(list) + .map((i) => toValue(i)) + .filter(fn) + ); } function useArrayFind(list, fn) { - return computed(() => toValue( - toValue(list).find((element, index, array) => fn(toValue(element), index, array)) - )); + return computed(() => + toValue( + toValue(list).find((element, index, array) => + fn(toValue(element), index, array) + ) + ) + ); } function useArrayFindIndex(list, fn) { - return computed(() => toValue(list).findIndex((element, index, array) => fn(toValue(element), index, array))); + return computed(() => + toValue(list).findIndex((element, index, array) => + fn(toValue(element), index, array) + ) + ); } function findLast(arr, cb) { let index = arr.length; while (index-- > 0) { - if (cb(arr[index], index, arr)) - return arr[index]; + if (cb(arr[index], index, arr)) return arr[index]; } return void 0; } function useArrayFindLast(list, fn) { - return computed(() => toValue( - !Array.prototype.findLast ? findLast(toValue(list), (element, index, array) => fn(toValue(element), index, array)) : toValue(list).findLast((element, index, array) => fn(toValue(element), index, array)) - )); + return computed(() => + toValue( + !Array.prototype.findLast + ? findLast(toValue(list), (element, index, array) => + fn(toValue(element), index, array) + ) + : toValue(list).findLast((element, index, array) => + fn(toValue(element), index, array) + ) + ) + ); } function isArrayIncludesOptions(obj) { - return isObject(obj) && containsProp(obj, "formIndex", "comparator"); + return isObject(obj) && containsProp(obj, 'formIndex', 'comparator'); } function useArrayIncludes(...args) { var _a; @@ -1006,77 +1094,101 @@ function useArrayIncludes(...args) { formIndex = (_a = comparator.fromIndex) != null ? _a : 0; comparator = comparator.comparator; } - if (typeof comparator === "string") { + if (typeof comparator === 'string') { const key = comparator; comparator = (element, value2) => element[key] === toValue(value2); } - comparator = comparator != null ? comparator : (element, value2) => element === toValue(value2); - return computed(() => toValue(list).slice(formIndex).some((element, index, array) => comparator( - toValue(element), - toValue(value), - index, - toValue(array) - ))); + comparator = + comparator != null + ? comparator + : (element, value2) => element === toValue(value2); + return computed(() => + toValue(list) + .slice(formIndex) + .some((element, index, array) => + comparator(toValue(element), toValue(value), index, toValue(array)) + ) + ); } function useArrayJoin(list, separator) { - return computed(() => toValue(list).map((i) => toValue(i)).join(toValue(separator))); + return computed(() => + toValue(list) + .map((i) => toValue(i)) + .join(toValue(separator)) + ); } function useArrayMap(list, fn) { - return computed(() => toValue(list).map((i) => toValue(i)).map(fn)); + return computed(() => + toValue(list) + .map((i) => toValue(i)) + .map(fn) + ); } function useArrayReduce(list, reducer, ...args) { - const reduceCallback = (sum, value, index) => reducer(toValue(sum), toValue(value), index); + const reduceCallback = (sum, value, index) => + reducer(toValue(sum), toValue(value), index); return computed(() => { const resolved = toValue(list); - return args.length ? resolved.reduce(reduceCallback, typeof args[0] === "function" ? toValue(args[0]()) : toValue(args[0])) : resolved.reduce(reduceCallback); + return args.length + ? resolved.reduce( + reduceCallback, + typeof args[0] === 'function' ? toValue(args[0]()) : toValue(args[0]) + ) + : resolved.reduce(reduceCallback); }); } function useArraySome(list, fn) { - return computed(() => toValue(list).some((element, index, array) => fn(toValue(element), index, array))); + return computed(() => + toValue(list).some((element, index, array) => + fn(toValue(element), index, array) + ) + ); } function uniq(array) { return Array.from(new Set(array)); } function uniqueElementsBy(array, fn) { return array.reduce((acc, v) => { - if (!acc.some((x) => fn(v, x, array))) - acc.push(v); + if (!acc.some((x) => fn(v, x, array))) acc.push(v); return acc; }, []); } function useArrayUnique(list, compareFn) { return computed(() => { const resolvedList = toValue(list).map((element) => toValue(element)); - return compareFn ? uniqueElementsBy(resolvedList, compareFn) : uniq(resolvedList); + return compareFn + ? uniqueElementsBy(resolvedList, compareFn) + : uniq(resolvedList); }); } function useCounter(initialValue = 0, options = {}) { let _initialValue = unref(initialValue); const count = shallowRef(initialValue); - const { - max = Number.POSITIVE_INFINITY, - min = Number.NEGATIVE_INFINITY - } = options; - const inc = (delta = 1) => count.value = Math.max(Math.min(max, count.value + delta), min); - const dec = (delta = 1) => count.value = Math.min(Math.max(min, count.value - delta), max); + const { max = Number.POSITIVE_INFINITY, min = Number.NEGATIVE_INFINITY } = + options; + const inc = (delta = 1) => + (count.value = Math.max(Math.min(max, count.value + delta), min)); + const dec = (delta = 1) => + (count.value = Math.min(Math.max(min, count.value - delta), max)); const get2 = () => count.value; - const set2 = (val) => count.value = Math.max(min, Math.min(max, val)); + const set2 = (val) => (count.value = Math.max(min, Math.min(max, val))); const reset = (val = _initialValue) => { _initialValue = val; return set2(val); }; return { count, inc, dec, get: get2, set: set2, reset }; } -var REGEX_PARSE = /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i; -var REGEX_FORMAT = /[YMDHhms]o|\[([^\]]+)\]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|z{1,4}|SSS/g; +var REGEX_PARSE = + /^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[T\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/i; +var REGEX_FORMAT = + /[YMDHhms]o|\[([^\]]+)\]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a{1,2}|A{1,2}|m{1,2}|s{1,2}|Z{1,2}|z{1,4}|SSS/g; function defaultMeridiem(hours, minutes, isLowercase, hasPeriod) { - let m = hours < 12 ? "AM" : "PM"; - if (hasPeriod) - m = m.split("").reduce((acc, curr) => acc += `${curr}.`, ""); + let m = hours < 12 ? 'AM' : 'PM'; + if (hasPeriod) m = m.split('').reduce((acc, curr) => (acc += `${curr}.`), ''); return isLowercase ? m.toLowerCase() : m; } function formatOrdinal(num) { - const suffixes = ["th", "st", "nd", "rd"]; + const suffixes = ['th', 'st', 'nd', 'rd']; const v = num % 100; return num + (suffixes[(v - 20) % 10] || suffixes[v] || suffixes[0]); } @@ -1093,7 +1205,7 @@ function formatDate(date, formatStr, options = {}) { const meridiem = (_a = options.customMeridiem) != null ? _a : defaultMeridiem; const stripTimeZone = (dateString) => { var _a2; - return (_a2 = dateString.split(" ")[1]) != null ? _a2 : ""; + return (_a2 = dateString.split(' ')[1]) != null ? _a2 : ''; }; const matches = { Yo: () => formatOrdinal(years), @@ -1101,68 +1213,96 @@ function formatDate(date, formatStr, options = {}) { YYYY: () => years, M: () => month + 1, Mo: () => formatOrdinal(month + 1), - MM: () => `${month + 1}`.padStart(2, "0"), - MMM: () => date.toLocaleDateString(toValue(options.locales), { month: "short" }), - MMMM: () => date.toLocaleDateString(toValue(options.locales), { month: "long" }), + MM: () => `${month + 1}`.padStart(2, '0'), + MMM: () => + date.toLocaleDateString(toValue(options.locales), { month: 'short' }), + MMMM: () => + date.toLocaleDateString(toValue(options.locales), { month: 'long' }), D: () => String(days), Do: () => formatOrdinal(days), - DD: () => `${days}`.padStart(2, "0"), + DD: () => `${days}`.padStart(2, '0'), H: () => String(hours), Ho: () => formatOrdinal(hours), - HH: () => `${hours}`.padStart(2, "0"), - h: () => `${hours % 12 || 12}`.padStart(1, "0"), + HH: () => `${hours}`.padStart(2, '0'), + h: () => `${hours % 12 || 12}`.padStart(1, '0'), ho: () => formatOrdinal(hours % 12 || 12), - hh: () => `${hours % 12 || 12}`.padStart(2, "0"), + hh: () => `${hours % 12 || 12}`.padStart(2, '0'), m: () => String(minutes), mo: () => formatOrdinal(minutes), - mm: () => `${minutes}`.padStart(2, "0"), + mm: () => `${minutes}`.padStart(2, '0'), s: () => String(seconds), so: () => formatOrdinal(seconds), - ss: () => `${seconds}`.padStart(2, "0"), - SSS: () => `${milliseconds}`.padStart(3, "0"), + ss: () => `${seconds}`.padStart(2, '0'), + SSS: () => `${milliseconds}`.padStart(3, '0'), d: () => day, - dd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "narrow" }), - ddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "short" }), - dddd: () => date.toLocaleDateString(toValue(options.locales), { weekday: "long" }), + dd: () => + date.toLocaleDateString(toValue(options.locales), { weekday: 'narrow' }), + ddd: () => + date.toLocaleDateString(toValue(options.locales), { weekday: 'short' }), + dddd: () => + date.toLocaleDateString(toValue(options.locales), { weekday: 'long' }), A: () => meridiem(hours, minutes), AA: () => meridiem(hours, minutes, false, true), a: () => meridiem(hours, minutes, true), aa: () => meridiem(hours, minutes, true, true), - z: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })), - zz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })), - zzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "shortOffset" })), - zzzz: () => stripTimeZone(date.toLocaleDateString(toValue(options.locales), { timeZoneName: "longOffset" })) + z: () => + stripTimeZone( + date.toLocaleDateString(toValue(options.locales), { + timeZoneName: 'shortOffset', + }) + ), + zz: () => + stripTimeZone( + date.toLocaleDateString(toValue(options.locales), { + timeZoneName: 'shortOffset', + }) + ), + zzz: () => + stripTimeZone( + date.toLocaleDateString(toValue(options.locales), { + timeZoneName: 'shortOffset', + }) + ), + zzzz: () => + stripTimeZone( + date.toLocaleDateString(toValue(options.locales), { + timeZoneName: 'longOffset', + }) + ), }; return formatStr.replace(REGEX_FORMAT, (match, $1) => { var _a2, _b; - return (_b = $1 != null ? $1 : (_a2 = matches[match]) == null ? void 0 : _a2.call(matches)) != null ? _b : match; + return (_b = + $1 != null + ? $1 + : (_a2 = matches[match]) == null + ? void 0 + : _a2.call(matches)) != null + ? _b + : match; }); } function normalizeDate(date) { - if (date === null) - return new Date(Number.NaN); - if (date === void 0) - return /* @__PURE__ */ new Date(); - if (date instanceof Date) - return new Date(date); - if (typeof date === "string" && !/Z$/i.test(date)) { + if (date === null) return new Date(Number.NaN); + if (date === void 0) return /* @__PURE__ */ new Date(); + if (date instanceof Date) return new Date(date); + if (typeof date === 'string' && !/Z$/i.test(date)) { const d = date.match(REGEX_PARSE); if (d) { const m = d[2] - 1 || 0; - const ms = (d[7] || "0").substring(0, 3); + const ms = (d[7] || '0').substring(0, 3); return new Date(d[1], m, d[3] || 1, d[4] || 0, d[5] || 0, d[6] || 0, ms); } } return new Date(date); } -function useDateFormat(date, formatStr = "HH:mm:ss", options = {}) { - return computed(() => formatDate(normalizeDate(toValue(date)), toValue(formatStr), options)); +function useDateFormat(date, formatStr = 'HH:mm:ss', options = {}) { + return computed(() => + formatDate(normalizeDate(toValue(date)), toValue(formatStr), options) + ); } function useIntervalFn(cb, interval = 1e3, options = {}) { - const { - immediate = true, - immediateCallback = false - } = options; + const { immediate = true, immediateCallback = false } = options; let timer = null; const isActive = shallowRef(false); function clean() { @@ -1177,21 +1317,16 @@ function useIntervalFn(cb, interval = 1e3, options = {}) { } function resume() { const intervalValue = toValue(interval); - if (intervalValue <= 0) - return; + if (intervalValue <= 0) return; isActive.value = true; - if (immediateCallback) - cb(); + if (immediateCallback) cb(); clean(); - if (isActive.value) - timer = setInterval(cb, intervalValue); + if (isActive.value) timer = setInterval(cb, intervalValue); } - if (immediate && isClient) - resume(); - if (isRef(interval) || typeof interval === "function") { + if (immediate && isClient) resume(); + if (isRef(interval) || typeof interval === 'function') { const stopWatch = watch(interval, () => { - if (isActive.value && isClient) - resume(); + if (isActive.value && isClient) resume(); }); tryOnScopeDispose(stopWatch); } @@ -1199,25 +1334,27 @@ function useIntervalFn(cb, interval = 1e3, options = {}) { return { isActive, pause, - resume + resume, }; } function useInterval(interval = 1e3, options = {}) { const { controls: exposeControls = false, immediate = true, - callback + callback, } = options; const counter = shallowRef(0); - const update = () => counter.value += 1; + const update = () => (counter.value += 1); const reset = () => { counter.value = 0; }; const controls = useIntervalFn( - callback ? () => { - update(); - callback(counter.value); - } : update, + callback + ? () => { + update(); + callback(counter.value); + } + : update, interval, { immediate } ); @@ -1225,7 +1362,7 @@ function useInterval(interval = 1e3, options = {}) { return { counter, reset, - ...controls + ...controls, }; } else { return counter; @@ -1234,18 +1371,11 @@ function useInterval(interval = 1e3, options = {}) { function useLastChanged(source, options = {}) { var _a; const ms = shallowRef((_a = options.initialValue) != null ? _a : null); - watch( - source, - () => ms.value = timestamp(), - options - ); + watch(source, () => (ms.value = timestamp()), options); return ms; } function useTimeoutFn(cb, interval, options = {}) { - const { - immediate = true, - immediateCallback = false - } = options; + const { immediate = true, immediateCallback = false } = options; const isPending = shallowRef(false); let timer = null; function clear() { @@ -1259,8 +1389,7 @@ function useTimeoutFn(cb, interval, options = {}) { clear(); } function start(...args) { - if (immediateCallback) - cb(); + if (immediateCallback) cb(); clear(); isPending.value = true; timer = setTimeout(() => { @@ -1271,21 +1400,17 @@ function useTimeoutFn(cb, interval, options = {}) { } if (immediate) { isPending.value = true; - if (isClient) - start(); + if (isClient) start(); } tryOnScopeDispose(stop); return { isPending: readonly(isPending), start, - stop + stop, }; } function useTimeout(interval = 1e3, options = {}) { - const { - controls: exposeControls = false, - callback - } = options; + const { controls: exposeControls = false, callback } = options; const controls = useTimeoutFn( callback != null ? callback : noop, interval, @@ -1295,26 +1420,20 @@ function useTimeout(interval = 1e3, options = {}) { if (exposeControls) { return { ready, - ...controls + ...controls, }; } else { return ready; } } function useToNumber(value, options = {}) { - const { - method = "parseFloat", - radix, - nanToZero - } = options; + const { method = 'parseFloat', radix, nanToZero } = options; return computed(() => { let resolved = toValue(value); - if (typeof method === "function") - resolved = method(resolved); - else if (typeof resolved === "string") + if (typeof method === 'function') resolved = method(resolved); + else if (typeof resolved === 'string') resolved = Number[method](resolved, radix); - if (nanToZero && Number.isNaN(resolved)) - resolved = 0; + if (nanToZero && Number.isNaN(resolved)) resolved = 0; return resolved; }); } @@ -1322,10 +1441,7 @@ function useToString(value) { return computed(() => `${toValue(value)}`); } function useToggle(initialValue = false, options = {}) { - const { - truthyValue = true, - falsyValue = false - } = options; + const { truthyValue = true, falsyValue = false } = options; const valueIsRef = isRef(initialValue); const _value = shallowRef(initialValue); function toggle(value) { @@ -1338,45 +1454,50 @@ function useToggle(initialValue = false, options = {}) { return _value.value; } } - if (valueIsRef) - return toggle; - else - return [_value, toggle]; + if (valueIsRef) return toggle; + else return [_value, toggle]; } function watchArray(source, cb, options) { - let oldList = (options == null ? void 0 : options.immediate) ? [] : [...typeof source === "function" ? source() : Array.isArray(source) ? source : toValue(source)]; - return watch(source, (newList, _, onCleanup) => { - const oldListRemains = Array.from({ length: oldList.length }); - const added = []; - for (const obj of newList) { - let found = false; - for (let i = 0; i < oldList.length; i++) { - if (!oldListRemains[i] && obj === oldList[i]) { - oldListRemains[i] = true; - found = true; - break; + let oldList = (options == null ? void 0 : options.immediate) + ? [] + : [ + ...(typeof source === 'function' + ? source() + : Array.isArray(source) + ? source + : toValue(source)), + ]; + return watch( + source, + (newList, _, onCleanup) => { + const oldListRemains = Array.from({ length: oldList.length }); + const added = []; + for (const obj of newList) { + let found = false; + for (let i = 0; i < oldList.length; i++) { + if (!oldListRemains[i] && obj === oldList[i]) { + oldListRemains[i] = true; + found = true; + break; + } } + if (!found) added.push(obj); } - if (!found) - added.push(obj); - } - const removed = oldList.filter((_2, i) => !oldListRemains[i]); - cb(newList, oldList, added, removed, onCleanup); - oldList = [...newList]; - }, options); + const removed = oldList.filter((_2, i) => !oldListRemains[i]); + cb(newList, oldList, added, removed, onCleanup); + oldList = [...newList]; + }, + options + ); } function watchAtMost(source, cb, options) { - const { - count, - ...watchOptions - } = options; + const { count, ...watchOptions } = options; const current = shallowRef(0); const stop = watchWithFilter( source, (...args) => { current.value += 1; - if (current.value >= toValue(count)) - nextTick(() => stop()); + if (current.value >= toValue(count)) nextTick(() => stop()); cb(...args); }, watchOptions @@ -1384,46 +1505,27 @@ function watchAtMost(source, cb, options) { return { count: current, stop }; } function watchDebounced(source, cb, options = {}) { - const { - debounce = 0, - maxWait = void 0, - ...watchOptions - } = options; - return watchWithFilter( - source, - cb, - { - ...watchOptions, - eventFilter: debounceFilter(debounce, { maxWait }) - } - ); + const { debounce = 0, maxWait = void 0, ...watchOptions } = options; + return watchWithFilter(source, cb, { + ...watchOptions, + eventFilter: debounceFilter(debounce, { maxWait }), + }); } function watchDeep(source, cb, options) { - return watch( - source, - cb, - { - ...options, - deep: true - } - ); + return watch(source, cb, { + ...options, + deep: true, + }); } function watchIgnorable(source, cb, options = {}) { - const { - eventFilter = bypassFilter, - ...watchOptions - } = options; - const filteredCb = createFilterWrapper( - eventFilter, - cb - ); + const { eventFilter = bypassFilter, ...watchOptions } = options; + const filteredCb = createFilterWrapper(eventFilter, cb); let ignoreUpdates; let ignorePrevAsyncUpdates; let stop; - if (watchOptions.flush === "sync") { + if (watchOptions.flush === 'sync') { const ignore = shallowRef(false); - ignorePrevAsyncUpdates = () => { - }; + ignorePrevAsyncUpdates = () => {}; ignoreUpdates = (updater) => { ignore.value = true; updater(); @@ -1432,8 +1534,7 @@ function watchIgnorable(source, cb, options = {}) { stop = watch( source, (...args) => { - if (!ignore.value) - filteredCb(...args); + if (!ignore.value) filteredCb(...args); }, watchOptions ); @@ -1450,7 +1551,7 @@ function watchIgnorable(source, cb, options = {}) { () => { syncCounter.value++; }, - { ...watchOptions, flush: "sync" } + { ...watchOptions, flush: 'sync' } ) ); ignoreUpdates = (updater) => { @@ -1462,11 +1563,12 @@ function watchIgnorable(source, cb, options = {}) { watch( source, (...args) => { - const ignore = ignoreCounter.value > 0 && ignoreCounter.value === syncCounter.value; + const ignore = + ignoreCounter.value > 0 && + ignoreCounter.value === syncCounter.value; ignoreCounter.value = 0; syncCounter.value = 0; - if (ignore) - return; + if (ignore) return; filteredCb(...args); }, watchOptions @@ -1479,20 +1581,20 @@ function watchIgnorable(source, cb, options = {}) { return { stop, ignoreUpdates, ignorePrevAsyncUpdates }; } function watchImmediate(source, cb, options) { - return watch( - source, - cb, - { - ...options, - immediate: true - } - ); + return watch(source, cb, { + ...options, + immediate: true, + }); } function watchOnce(source, cb, options) { - const stop = watch(source, (...args) => { - nextTick(() => stop()); - return cb(...args); - }, options); + const stop = watch( + source, + (...args) => { + nextTick(() => stop()); + return cb(...args); + }, + options + ); return stop; } function watchThrottled(source, cb, options = {}) { @@ -1502,20 +1604,15 @@ function watchThrottled(source, cb, options = {}) { leading = true, ...watchOptions } = options; - return watchWithFilter( - source, - cb, - { - ...watchOptions, - eventFilter: throttleFilter(throttle, trailing, leading) - } - ); + return watchWithFilter(source, cb, { + ...watchOptions, + eventFilter: throttleFilter(throttle, trailing, leading), + }); } function watchTriggerable(source, cb, options = {}) { let cleanupFn; function onEffect() { - if (!cleanupFn) - return; + if (!cleanupFn) return; const fn = cleanupFn; cleanupFn = void 0; fn(); @@ -1538,14 +1635,12 @@ function watchTriggerable(source, cb, options = {}) { }; return { ...res, - trigger + trigger, }; } function getWatchSources(sources) { - if (isReactive(sources)) - return sources; - if (Array.isArray(sources)) - return sources.map((item) => toValue(item)); + if (isReactive(sources)) return sources; + if (Array.isArray(sources)) return sources.map((item) => toValue(item)); return toValue(sources); } function getOldValue(source) { @@ -1556,14 +1651,13 @@ function whenever(source, cb, options) { source, (v, ov, onInvalidate) => { if (v) { - if (options == null ? void 0 : options.once) - nextTick(() => stop()); + if (options == null ? void 0 : options.once) nextTick(() => stop()); cb(v, ov, onInvalidate); } }, { ...options, - once: false + once: false, } ); return stop; @@ -1574,7 +1668,7 @@ function computedAsync(evaluationCallback, initialState, optionsOrRef) { let options; if (isRef(optionsOrRef)) { options = { - evaluating: optionsOrRef + evaluating: optionsOrRef, }; } else { options = optionsOrRef || {}; @@ -1583,14 +1677,13 @@ function computedAsync(evaluationCallback, initialState, optionsOrRef) { lazy = false, evaluating = void 0, shallow = true, - onError = noop + onError = noop, } = options; const started = shallowRef(!lazy); const current = shallow ? shallowRef(initialState) : ref(initialState); let counter = 0; watchEffect(async (onInvalidate) => { - if (!started.value) - return; + if (!started.value) return; counter++; const counterAtBeginning = counter; let hasFinished = false; @@ -1602,14 +1695,11 @@ function computedAsync(evaluationCallback, initialState, optionsOrRef) { try { const result = await evaluationCallback((cancelCallback) => { onInvalidate(() => { - if (evaluating) - evaluating.value = false; - if (!hasFinished) - cancelCallback(); + if (evaluating) evaluating.value = false; + if (!hasFinished) cancelCallback(); }); }); - if (counterAtBeginning === counter) - current.value = result; + if (counterAtBeginning === counter) current.value = result; } catch (e) { onError(e); } finally { @@ -1629,30 +1719,27 @@ function computedAsync(evaluationCallback, initialState, optionsOrRef) { } function computedInject(key, options, defaultSource, treatDefaultAsFactory) { let source = inject(key); - if (defaultSource) - source = inject(key, defaultSource); + if (defaultSource) source = inject(key, defaultSource); if (treatDefaultAsFactory) source = inject(key, defaultSource, treatDefaultAsFactory); - if (typeof options === "function") { + if (typeof options === 'function') { return computed((ctx) => options(source, ctx)); } else { return computed({ get: (ctx) => options.get(source, ctx), - set: options.set + set: options.set, }); } } function createReusableTemplate(options = {}) { - const { - inheritAttrs = true - } = options; + const { inheritAttrs = true } = options; const render = shallowRef(); const define = defineComponent({ setup(_, { slots }) { return () => { render.value = slots.default; }; - } + }, }); const reuse = defineComponent({ inheritAttrs, @@ -1661,24 +1748,29 @@ function createReusableTemplate(options = {}) { return () => { var _a; if (!render.value && true) - throw new Error("[VueUse] Failed to find the definition of reusable template"); - const vnode = (_a = render.value) == null ? void 0 : _a.call(render, { - ...options.props == null ? keysToCamelKebabCase(attrs) : props, - $slots: slots - }); - return inheritAttrs && (vnode == null ? void 0 : vnode.length) === 1 ? vnode[0] : vnode; + throw new Error( + '[VueUse] Failed to find the definition of reusable template' + ); + const vnode = + (_a = render.value) == null + ? void 0 + : _a.call(render, { + ...(options.props == null + ? keysToCamelKebabCase(attrs) + : props), + $slots: slots, + }); + return inheritAttrs && (vnode == null ? void 0 : vnode.length) === 1 + ? vnode[0] + : vnode; }; - } + }, }); - return makeDestructurable( - { define, reuse }, - [define, reuse] - ); + return makeDestructurable({ define, reuse }, [define, reuse]); } function keysToCamelKebabCase(obj) { const newObj = {}; - for (const key in obj) - newObj[camelize(key)] = obj[key]; + for (const key in obj) newObj[camelize(key)] = obj[key]; return newObj; } function createTemplatePromise(options = {}) { @@ -1689,12 +1781,10 @@ function createTemplatePromise(options = {}) { key: index++, args, promise: void 0, - resolve: () => { - }, - reject: () => { - }, + resolve: () => {}, + reject: () => {}, isResolving: false, - options + options, }); instances.value.push(props); props.promise = new Promise((_resolve, _reject) => { @@ -1706,8 +1796,7 @@ function createTemplatePromise(options = {}) { }).finally(() => { props.promise = void 0; const index2 = instances.value.indexOf(props); - if (index2 !== -1) - instances.value.splice(index2, 1); + if (index2 !== -1) instances.value.splice(index2, 1); }); return props.promise; } @@ -1717,10 +1806,15 @@ function createTemplatePromise(options = {}) { return create(...args); } const component = defineComponent((_, { slots }) => { - const renderList = () => instances.value.map((props) => { - var _a; - return h(Fragment, { key: props.key }, (_a = slots.default) == null ? void 0 : _a.call(slots, props)); - }); + const renderList = () => + instances.value.map((props) => { + var _a; + return h( + Fragment, + { key: props.key }, + (_a = slots.default) == null ? void 0 : _a.call(slots, props) + ); + }); if (options.transition) return () => h(TransitionGroup, options.transition, renderList); return renderList; @@ -1729,8 +1823,11 @@ function createTemplatePromise(options = {}) { return component; } function createUnrefFn(fn) { - return function(...args) { - return fn.apply(this, args.map((i) => toValue(i))); + return function (...args) { + return fn.apply( + this, + args.map((i) => toValue(i)) + ); }; } var defaultWindow = isClient ? window : void 0; @@ -1754,33 +1851,46 @@ function useEventListener(...args) { }; const firstParamTargets = computed(() => { const test = toArray(toValue(args[0])).filter((e) => e != null); - return test.every((e) => typeof e !== "string") ? test : void 0; + return test.every((e) => typeof e !== 'string') ? test : void 0; }); const stopWatch = watchImmediate( () => { var _a, _b; return [ - (_b = (_a = firstParamTargets.value) == null ? void 0 : _a.map((e) => unrefElement(e))) != null ? _b : [defaultWindow].filter((e) => e != null), + (_b = + (_a = firstParamTargets.value) == null + ? void 0 + : _a.map((e) => unrefElement(e))) != null + ? _b + : [defaultWindow].filter((e) => e != null), toArray(toValue(firstParamTargets.value ? args[1] : args[0])), toArray(unref(firstParamTargets.value ? args[2] : args[1])), // @ts-expect-error - TypeScript gets the correct types, but somehow still complains - toValue(firstParamTargets.value ? args[3] : args[2]) + toValue(firstParamTargets.value ? args[3] : args[2]), ]; }, ([raw_targets, raw_events, raw_listeners, raw_options]) => { cleanup(); - if (!(raw_targets == null ? void 0 : raw_targets.length) || !(raw_events == null ? void 0 : raw_events.length) || !(raw_listeners == null ? void 0 : raw_listeners.length)) + if ( + !(raw_targets == null ? void 0 : raw_targets.length) || + !(raw_events == null ? void 0 : raw_events.length) || + !(raw_listeners == null ? void 0 : raw_listeners.length) + ) return; - const optionsClone = isObject(raw_options) ? { ...raw_options } : raw_options; + const optionsClone = isObject(raw_options) + ? { ...raw_options } + : raw_options; cleanups.push( - ...raw_targets.flatMap( - (el) => raw_events.flatMap( - (event) => raw_listeners.map((listener) => register(el, event, listener, optionsClone)) + ...raw_targets.flatMap((el) => + raw_events.flatMap((event) => + raw_listeners.map((listener) => + register(el, event, listener, optionsClone) + ) ) ) ); }, - { flush: "post" } + { flush: 'post' } ); const stop = () => { stopWatch(); @@ -1791,21 +1901,36 @@ function useEventListener(...args) { } var _iOSWorkaround = false; function onClickOutside(target, handler, options = {}) { - const { window: window2 = defaultWindow, ignore = [], capture = true, detectIframe = false, controls = false } = options; + const { + window: window2 = defaultWindow, + ignore = [], + capture = true, + detectIframe = false, + controls = false, + } = options; if (!window2) { return controls ? { stop: noop, cancel: noop, trigger: noop } : noop; } if (isIOS && !_iOSWorkaround) { _iOSWorkaround = true; const listenerOptions = { passive: true }; - Array.from(window2.document.body.children).forEach((el) => useEventListener(el, "click", noop, listenerOptions)); - useEventListener(window2.document.documentElement, "click", noop, listenerOptions); + Array.from(window2.document.body.children).forEach((el) => + useEventListener(el, 'click', noop, listenerOptions) + ); + useEventListener( + window2.document.documentElement, + 'click', + noop, + listenerOptions + ); } let shouldListen = true; const shouldIgnore = (event) => { return toValue(ignore).some((target2) => { - if (typeof target2 === "string") { - return Array.from(window2.document.querySelectorAll(target2)).some((el) => el === event.target || event.composedPath().includes(el)); + if (typeof target2 === 'string') { + return Array.from(window2.document.querySelectorAll(target2)).some( + (el) => el === event.target || event.composedPath().includes(el) + ); } else { const el = unrefElement(target2); return el && (event.target === el || event.composedPath().includes(el)); @@ -1819,19 +1944,23 @@ function onClickOutside(target, handler, options = {}) { function checkMultipleRoots(target2, event) { const vm = toValue(target2); const children = vm.$.subTree && vm.$.subTree.children; - if (children == null || !Array.isArray(children)) - return false; - return children.some((child) => child.el === event.target || event.composedPath().includes(child.el)); + if (children == null || !Array.isArray(children)) return false; + return children.some( + (child) => + child.el === event.target || event.composedPath().includes(child.el) + ); } const listener = (event) => { const el = unrefElement(target); - if (event.target == null) + if (event.target == null) return; + if ( + !(el instanceof Element) && + hasMultipleRoots(target) && + checkMultipleRoots(target, event) + ) return; - if (!(el instanceof Element) && hasMultipleRoots(target) && checkMultipleRoots(target, event)) - return; - if (!el || el === event.target || event.composedPath().includes(el)) - return; - if ("detail" in event && event.detail === 0) + if (!el || el === event.target || event.composedPath().includes(el)) return; + if ('detail' in event && event.detail === 0) shouldListen = !shouldIgnore(event); if (!shouldListen) { shouldListen = true; @@ -1841,28 +1970,52 @@ function onClickOutside(target, handler, options = {}) { }; let isProcessingClick = false; const cleanup = [ - useEventListener(window2, "click", (event) => { - if (!isProcessingClick) { - isProcessingClick = true; - setTimeout(() => { - isProcessingClick = false; - }, 0); - listener(event); - } - }, { passive: true, capture }), - useEventListener(window2, "pointerdown", (e) => { - const el = unrefElement(target); - shouldListen = !shouldIgnore(e) && !!(el && !e.composedPath().includes(el)); - }, { passive: true }), - detectIframe && useEventListener(window2, "blur", (event) => { - setTimeout(() => { - var _a; - const el = unrefElement(target); - if (((_a = window2.document.activeElement) == null ? void 0 : _a.tagName) === "IFRAME" && !(el == null ? void 0 : el.contains(window2.document.activeElement))) { - handler(event); + useEventListener( + window2, + 'click', + (event) => { + if (!isProcessingClick) { + isProcessingClick = true; + setTimeout(() => { + isProcessingClick = false; + }, 0); + listener(event); } - }, 0); - }, { passive: true }) + }, + { passive: true, capture } + ), + useEventListener( + window2, + 'pointerdown', + (e) => { + const el = unrefElement(target); + shouldListen = + !shouldIgnore(e) && !!(el && !e.composedPath().includes(el)); + }, + { passive: true } + ), + detectIframe && + useEventListener( + window2, + 'blur', + (event) => { + setTimeout(() => { + var _a; + const el = unrefElement(target); + if ( + ((_a = window2.document.activeElement) == null + ? void 0 + : _a.tagName) === 'IFRAME' && + !(el == null + ? void 0 + : el.contains(window2.document.activeElement)) + ) { + handler(event); + } + }, 0); + }, + { passive: true } + ), ].filter(Boolean); const stop = () => cleanup.forEach((fn) => fn()); if (controls) { @@ -1875,7 +2028,7 @@ function onClickOutside(target, handler, options = {}) { shouldListen = true; listener(event); shouldListen = false; - } + }, }; } return stop; @@ -1900,7 +2053,9 @@ function useSupported(callback) { function useMutationObserver(target, callback, options = {}) { const { window: window2 = defaultWindow, ...mutationOptions } = options; let observer; - const isSupported = useSupported(() => window2 && "MutationObserver" in window2); + const isSupported = useSupported( + () => window2 && 'MutationObserver' in window2 + ); const cleanup = () => { if (observer) { observer.disconnect(); @@ -1921,7 +2076,7 @@ function useMutationObserver(target, callback, options = {}) { targets2.forEach((el) => observer.observe(el, mutationOptions)); } }, - { immediate: true, flush: "post" } + { immediate: true, flush: 'post' } ); const takeRecords = () => { return observer == null ? void 0 : observer.takeRecords(); @@ -1934,42 +2089,47 @@ function useMutationObserver(target, callback, options = {}) { return { isSupported, stop, - takeRecords + takeRecords, }; } function onElementRemoval(target, callback, options = {}) { const { window: window2 = defaultWindow, document: document2 = window2 == null ? void 0 : window2.document, - flush = "sync" + flush = 'sync', } = options; - if (!window2 || !document2) - return noop; + if (!window2 || !document2) return noop; let stopFn; const cleanupAndUpdate = (fn) => { stopFn == null ? void 0 : stopFn(); stopFn = fn; }; - const stopWatch = watchEffect(() => { - const el = unrefElement(target); - if (el) { - const { stop } = useMutationObserver( - document2, - (mutationsList) => { - const targetRemoved = mutationsList.map((mutation) => [...mutation.removedNodes]).flat().some((node) => node === el || node.contains(el)); - if (targetRemoved) { - callback(mutationsList); + const stopWatch = watchEffect( + () => { + const el = unrefElement(target); + if (el) { + const { stop } = useMutationObserver( + document2, + (mutationsList) => { + const targetRemoved = mutationsList + .map((mutation) => [...mutation.removedNodes]) + .flat() + .some((node) => node === el || node.contains(el)); + if (targetRemoved) { + callback(mutationsList); + } + }, + { + window: window2, + childList: true, + subtree: true, } - }, - { - window: window2, - childList: true, - subtree: true - } - ); - cleanupAndUpdate(stop); - } - }, { flush }); + ); + cleanupAndUpdate(stop); + } + }, + { flush } + ); const stopHandle = () => { stopWatch(); cleanupAndUpdate(); @@ -1978,9 +2138,8 @@ function onElementRemoval(target, callback, options = {}) { return stopHandle; } function createKeyPredicate(keyFilter) { - if (typeof keyFilter === "function") - return keyFilter; - else if (typeof keyFilter === "string") + if (typeof keyFilter === 'function') return keyFilter; + else if (typeof keyFilter === 'string') return (event) => event.key === keyFilter; else if (Array.isArray(keyFilter)) return (event) => keyFilter.includes(event.key); @@ -1995,7 +2154,7 @@ function onKeyStroke(...args) { handler = args[1]; options = args[2]; } else if (args.length === 2) { - if (typeof args[1] === "object") { + if (typeof args[1] === 'object') { key = true; handler = args[0]; options = args[1]; @@ -2009,27 +2168,25 @@ function onKeyStroke(...args) { } const { target = defaultWindow, - eventName = "keydown", + eventName = 'keydown', passive = false, - dedupe = false + dedupe = false, } = options; const predicate = createKeyPredicate(key); const listener = (e) => { - if (e.repeat && toValue(dedupe)) - return; - if (predicate(e)) - handler(e); + if (e.repeat && toValue(dedupe)) return; + if (predicate(e)) handler(e); }; return useEventListener(target, eventName, listener, passive); } function onKeyDown(key, handler, options = {}) { - return onKeyStroke(key, handler, { ...options, eventName: "keydown" }); + return onKeyStroke(key, handler, { ...options, eventName: 'keydown' }); } function onKeyPressed(key, handler, options = {}) { - return onKeyStroke(key, handler, { ...options, eventName: "keypress" }); + return onKeyStroke(key, handler, { ...options, eventName: 'keypress' }); } function onKeyUp(key, handler, options = {}) { - return onKeyStroke(key, handler, { ...options, eventName: "keyup" }); + return onKeyStroke(key, handler, { ...options, eventName: 'keyup' }); } var DEFAULT_DELAY = 500; var DEFAULT_THRESHOLD = 10; @@ -2051,33 +2208,71 @@ function onLongPress(target, handler, options) { } function onRelease(ev) { var _a2, _b2, _c; - const [_startTimestamp, _posStart, _hasLongPressed] = [startTimestamp, posStart, hasLongPressed]; + const [_startTimestamp, _posStart, _hasLongPressed] = [ + startTimestamp, + posStart, + hasLongPressed, + ]; clear(); - if (!(options == null ? void 0 : options.onMouseUp) || !_posStart || !_startTimestamp) + if ( + !(options == null ? void 0 : options.onMouseUp) || + !_posStart || + !_startTimestamp + ) return; - if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value) + if ( + ((_a2 = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _a2.self) && + ev.target !== elementRef.value + ) return; - if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent) + if ( + (_b2 = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _b2.prevent + ) ev.preventDefault(); - if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop) + if ( + (_c = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _c.stop + ) ev.stopPropagation(); const dx = ev.x - _posStart.x; const dy = ev.y - _posStart.y; const distance = Math.sqrt(dx * dx + dy * dy); - options.onMouseUp(ev.timeStamp - _startTimestamp, distance, _hasLongPressed); + options.onMouseUp( + ev.timeStamp - _startTimestamp, + distance, + _hasLongPressed + ); } function onDown(ev) { var _a2, _b2, _c, _d; - if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value) + if ( + ((_a2 = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _a2.self) && + ev.target !== elementRef.value + ) return; clear(); - if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent) + if ( + (_b2 = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _b2.prevent + ) ev.preventDefault(); - if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop) + if ( + (_c = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _c.stop + ) ev.stopPropagation(); posStart = { x: ev.x, - y: ev.y + y: ev.y, }; startTimestamp = ev.timeStamp; timeout = setTimeout( @@ -2085,62 +2280,87 @@ function onLongPress(target, handler, options) { hasLongPressed = true; handler(ev); }, - (_d = options == null ? void 0 : options.delay) != null ? _d : DEFAULT_DELAY + (_d = options == null ? void 0 : options.delay) != null + ? _d + : DEFAULT_DELAY ); } function onMove(ev) { var _a2, _b2, _c, _d; - if (((_a2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _a2.self) && ev.target !== elementRef.value) + if ( + ((_a2 = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _a2.self) && + ev.target !== elementRef.value + ) return; - if (!posStart || (options == null ? void 0 : options.distanceThreshold) === false) + if ( + !posStart || + (options == null ? void 0 : options.distanceThreshold) === false + ) return; - if ((_b2 = options == null ? void 0 : options.modifiers) == null ? void 0 : _b2.prevent) + if ( + (_b2 = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _b2.prevent + ) ev.preventDefault(); - if ((_c = options == null ? void 0 : options.modifiers) == null ? void 0 : _c.stop) + if ( + (_c = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _c.stop + ) ev.stopPropagation(); const dx = ev.x - posStart.x; const dy = ev.y - posStart.y; const distance = Math.sqrt(dx * dx + dy * dy); - if (distance >= ((_d = options == null ? void 0 : options.distanceThreshold) != null ? _d : DEFAULT_THRESHOLD)) + if ( + distance >= + ((_d = options == null ? void 0 : options.distanceThreshold) != null + ? _d + : DEFAULT_THRESHOLD) + ) clear(); } const listenerOptions = { - capture: (_a = options == null ? void 0 : options.modifiers) == null ? void 0 : _a.capture, - once: (_b = options == null ? void 0 : options.modifiers) == null ? void 0 : _b.once + capture: + (_a = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _a.capture, + once: + (_b = options == null ? void 0 : options.modifiers) == null + ? void 0 + : _b.once, }; const cleanup = [ - useEventListener(elementRef, "pointerdown", onDown, listenerOptions), - useEventListener(elementRef, "pointermove", onMove, listenerOptions), - useEventListener(elementRef, ["pointerup", "pointerleave"], onRelease, listenerOptions) + useEventListener(elementRef, 'pointerdown', onDown, listenerOptions), + useEventListener(elementRef, 'pointermove', onMove, listenerOptions), + useEventListener( + elementRef, + ['pointerup', 'pointerleave'], + onRelease, + listenerOptions + ), ]; const stop = () => cleanup.forEach((fn) => fn()); return stop; } function isFocusedElementEditable() { const { activeElement, body } = document; - if (!activeElement) - return false; - if (activeElement === body) - return false; + if (!activeElement) return false; + if (activeElement === body) return false; switch (activeElement.tagName) { - case "INPUT": - case "TEXTAREA": + case 'INPUT': + case 'TEXTAREA': return true; } - return activeElement.hasAttribute("contenteditable"); + return activeElement.hasAttribute('contenteditable'); } -function isTypedCharValid({ - keyCode, - metaKey, - ctrlKey, - altKey -}) { - if (metaKey || ctrlKey || altKey) - return false; - if (keyCode >= 48 && keyCode <= 57 || keyCode >= 96 && keyCode <= 105) - return true; - if (keyCode >= 65 && keyCode <= 90) +function isTypedCharValid({ keyCode, metaKey, ctrlKey, altKey }) { + if (metaKey || ctrlKey || altKey) return false; + if ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105)) return true; + if (keyCode >= 65 && keyCode <= 90) return true; return false; } function onStartTyping(callback, options = {}) { @@ -2151,22 +2371,25 @@ function onStartTyping(callback, options = {}) { } }; if (document2) - useEventListener(document2, "keydown", keydown, { passive: true }); + useEventListener(document2, 'keydown', keydown, { passive: true }); } function templateRef(key, initialValue = null) { const instance = getCurrentInstance(); - let _trigger = () => { - }; + let _trigger = () => {}; const element = customRef((track, trigger) => { _trigger = trigger; return { get() { var _a, _b; track(); - return (_b = (_a = instance == null ? void 0 : instance.proxy) == null ? void 0 : _a.$refs[key]) != null ? _b : initialValue; + return (_b = + (_a = instance == null ? void 0 : instance.proxy) == null + ? void 0 + : _a.$refs[key]) != null + ? _b + : initialValue; }, - set() { - } + set() {}, }; }); tryOnMounted(_trigger); @@ -2178,15 +2401,23 @@ function useActiveElement(options = {}) { const { window: window2 = defaultWindow, deep = true, - triggerOnRemoval = false + triggerOnRemoval = false, } = options; - const document2 = (_a = options.document) != null ? _a : window2 == null ? void 0 : window2.document; + const document2 = + (_a = options.document) != null + ? _a + : window2 == null + ? void 0 + : window2.document; const getDeepActiveElement = () => { var _a2; let element = document2 == null ? void 0 : document2.activeElement; if (deep) { while (element == null ? void 0 : element.shadowRoot) - element = (_a2 = element == null ? void 0 : element.shadowRoot) == null ? void 0 : _a2.activeElement; + element = + (_a2 = element == null ? void 0 : element.shadowRoot) == null + ? void 0 + : _a2.activeElement; } return element; }; @@ -2197,24 +2428,18 @@ function useActiveElement(options = {}) { if (window2) { const listenerOptions = { capture: true, - passive: true + passive: true, }; useEventListener( window2, - "blur", + 'blur', (event) => { - if (event.relatedTarget !== null) - return; + if (event.relatedTarget !== null) return; trigger(); }, listenerOptions ); - useEventListener( - window2, - "focus", - trigger, - listenerOptions - ); + useEventListener(window2, 'focus', trigger, listenerOptions); } if (triggerOnRemoval) { onElementRemoval(activeElement, trigger, { document: document2 }); @@ -2227,7 +2452,7 @@ function useRafFn(fn, options = {}) { immediate = true, fpsLimit = void 0, window: window2 = defaultWindow, - once = false + once = false, } = options; const isActive = shallowRef(false); const intervalLimit = computed(() => { @@ -2236,10 +2461,8 @@ function useRafFn(fn, options = {}) { let previousFrameTimestamp = 0; let rafId = null; function loop(timestamp2) { - if (!isActive.value || !window2) - return; - if (!previousFrameTimestamp) - previousFrameTimestamp = timestamp2; + if (!isActive.value || !window2) return; + if (!previousFrameTimestamp) previousFrameTimestamp = timestamp2; const delta = timestamp2 - previousFrameTimestamp; if (intervalLimit.value && delta < intervalLimit.value) { rafId = window2.requestAnimationFrame(loop); @@ -2268,13 +2491,12 @@ function useRafFn(fn, options = {}) { rafId = null; } } - if (immediate) - resume(); + if (immediate) resume(); tryOnScopeDispose(pause); return { isActive: readonly(isActive), pause, - resume + resume, }; } function useAnimate(target, keyframes, options) { @@ -2282,7 +2504,14 @@ function useAnimate(target, keyframes, options) { let animateOptions; if (isObject(options)) { config = options; - animateOptions = objectOmit(options, ["window", "immediate", "commitStyles", "persist", "onReady", "onError"]); + animateOptions = objectOmit(options, [ + 'window', + 'immediate', + 'commitStyles', + 'persist', + 'onReady', + 'onError', + ]); } else { config = { duration: options }; animateOptions = options; @@ -2296,9 +2525,11 @@ function useAnimate(target, keyframes, options) { onReady, onError = (e) => { console.error(e); - } + }, } = config; - const isSupported = useSupported(() => window2 && HTMLElement && "animate" in HTMLElement.prototype); + const isSupported = useSupported( + () => window2 && HTMLElement && 'animate' in HTMLElement.prototype + ); const animate = shallowRef(void 0); const store = shallowReactive({ startTime: null, @@ -2306,8 +2537,8 @@ function useAnimate(target, keyframes, options) { timeline: null, playbackRate: _playbackRate, pending: false, - playState: immediate ? "idle" : "paused", - replaceState: "active" + playState: immediate ? 'idle' : 'paused', + replaceState: 'active', }); const pending = computed(() => store.pending); const playState = computed(() => store.playState); @@ -2318,9 +2549,8 @@ function useAnimate(target, keyframes, options) { }, set(value) { store.startTime = value; - if (animate.value) - animate.value.startTime = value; - } + if (animate.value) animate.value.startTime = value; + }, }); const currentTime = computed({ get() { @@ -2332,7 +2562,7 @@ function useAnimate(target, keyframes, options) { animate.value.currentTime = value; syncResume(); } - } + }, }); const timeline = computed({ get() { @@ -2340,9 +2570,8 @@ function useAnimate(target, keyframes, options) { }, set(value) { store.timeline = value; - if (animate.value) - animate.value.timeline = value; - } + if (animate.value) animate.value.timeline = value; + }, }); const playbackRate = computed({ get() { @@ -2350,9 +2579,8 @@ function useAnimate(target, keyframes, options) { }, set(value) { store.playbackRate = value; - if (animate.value) - animate.value.playbackRate = value; - } + if (animate.value) animate.value.playbackRate = value; + }, }); const play = () => { if (animate.value) { @@ -2378,8 +2606,7 @@ function useAnimate(target, keyframes, options) { }; const reverse = () => { var _a; - if (!animate.value) - update(); + if (!animate.value) update(); try { (_a = animate.value) == null ? void 0 : _a.reverse(); syncResume(); @@ -2406,69 +2633,81 @@ function useAnimate(target, keyframes, options) { onError(e); } }; - watch(() => unrefElement(target), (el) => { - if (el) { - update(); - } else { - animate.value = void 0; - } - }); - watch(() => keyframes, (value) => { - if (animate.value) { - update(); - const targetEl = unrefElement(target); - if (targetEl) { - animate.value.effect = new KeyframeEffect( - targetEl, - toValue(value), - animateOptions - ); + watch( + () => unrefElement(target), + (el) => { + if (el) { + update(); + } else { + animate.value = void 0; } } - }, { deep: true }); + ); + watch( + () => keyframes, + (value) => { + if (animate.value) { + update(); + const targetEl = unrefElement(target); + if (targetEl) { + animate.value.effect = new KeyframeEffect( + targetEl, + toValue(value), + animateOptions + ); + } + } + }, + { deep: true } + ); tryOnMounted(() => update(true), false); tryOnScopeDispose(cancel); function update(init) { const el = unrefElement(target); - if (!isSupported.value || !el) - return; + if (!isSupported.value || !el) return; if (!animate.value) animate.value = el.animate(toValue(keyframes), animateOptions); - if (persist) - animate.value.persist(); - if (_playbackRate !== 1) - animate.value.playbackRate = _playbackRate; - if (init && !immediate) - animate.value.pause(); - else - syncResume(); + if (persist) animate.value.persist(); + if (_playbackRate !== 1) animate.value.playbackRate = _playbackRate; + if (init && !immediate) animate.value.pause(); + else syncResume(); onReady == null ? void 0 : onReady(animate.value); } const listenerOptions = { passive: true }; - useEventListener(animate, ["cancel", "finish", "remove"], syncPause, listenerOptions); - useEventListener(animate, "finish", () => { - var _a; - if (commitStyles) - (_a = animate.value) == null ? void 0 : _a.commitStyles(); - }, listenerOptions); - const { resume: resumeRef, pause: pauseRef } = useRafFn(() => { - if (!animate.value) - return; - store.pending = animate.value.pending; - store.playState = animate.value.playState; - store.replaceState = animate.value.replaceState; - store.startTime = animate.value.startTime; - store.currentTime = animate.value.currentTime; - store.timeline = animate.value.timeline; - store.playbackRate = animate.value.playbackRate; - }, { immediate: false }); + useEventListener( + animate, + ['cancel', 'finish', 'remove'], + syncPause, + listenerOptions + ); + useEventListener( + animate, + 'finish', + () => { + var _a; + if (commitStyles) + (_a = animate.value) == null ? void 0 : _a.commitStyles(); + }, + listenerOptions + ); + const { resume: resumeRef, pause: pauseRef } = useRafFn( + () => { + if (!animate.value) return; + store.pending = animate.value.pending; + store.playState = animate.value.playState; + store.replaceState = animate.value.replaceState; + store.startTime = animate.value.startTime; + store.currentTime = animate.value.currentTime; + store.timeline = animate.value.timeline; + store.playbackRate = animate.value.playbackRate; + }, + { immediate: false } + ); function syncResume() { - if (isSupported.value) - resumeRef(); + if (isSupported.value) resumeRef(); } function syncPause() { - if (isSupported.value && window2) - window2.requestAnimationFrame(pauseRef); + if (isSupported.value && window2) window2.requestAnimationFrame(pauseRef); } return { isSupported, @@ -2486,7 +2725,7 @@ function useAnimate(target, keyframes, options) { startTime, currentTime, timeline, - playbackRate + playbackRate, }; } function useAsyncQueue(tasks, options) { @@ -2494,22 +2733,25 @@ function useAsyncQueue(tasks, options) { interrupt = true, onError = noop, onFinished = noop, - signal + signal, } = options || {}; const promiseState = { - aborted: "aborted", - fulfilled: "fulfilled", - pending: "pending", - rejected: "rejected" + aborted: 'aborted', + fulfilled: 'fulfilled', + pending: 'pending', + rejected: 'rejected', }; - const initialResult = Array.from(Array.from({ length: tasks.length }), () => ({ state: promiseState.pending, data: null })); + const initialResult = Array.from( + Array.from({ length: tasks.length }), + () => ({ state: promiseState.pending, data: null }) + ); const result = reactive(initialResult); const activeIndex = shallowRef(-1); if (!tasks || tasks.length === 0) { onFinished(); return { activeIndex, - result + result, }; } function updateResult(state, res) { @@ -2518,47 +2760,49 @@ function useAsyncQueue(tasks, options) { result[activeIndex.value].state = state; } tasks.reduce((prev, curr) => { - return prev.then((prevRes) => { - var _a; - if (signal == null ? void 0 : signal.aborted) { - updateResult(promiseState.aborted, new Error("aborted")); - return; - } - if (((_a = result[activeIndex.value]) == null ? void 0 : _a.state) === promiseState.rejected && interrupt) { - onFinished(); - return; - } - const done = curr(prevRes).then((currentRes) => { - updateResult(promiseState.fulfilled, currentRes); - if (activeIndex.value === tasks.length - 1) + return prev + .then((prevRes) => { + var _a; + if (signal == null ? void 0 : signal.aborted) { + updateResult(promiseState.aborted, new Error('aborted')); + return; + } + if ( + ((_a = result[activeIndex.value]) == null ? void 0 : _a.state) === + promiseState.rejected && + interrupt + ) { onFinished(); - return currentRes; - }); - if (!signal) - return done; - return Promise.race([done, whenAborted(signal)]); - }).catch((e) => { - if (signal == null ? void 0 : signal.aborted) { - updateResult(promiseState.aborted, e); + return; + } + const done = curr(prevRes).then((currentRes) => { + updateResult(promiseState.fulfilled, currentRes); + if (activeIndex.value === tasks.length - 1) onFinished(); + return currentRes; + }); + if (!signal) return done; + return Promise.race([done, whenAborted(signal)]); + }) + .catch((e) => { + if (signal == null ? void 0 : signal.aborted) { + updateResult(promiseState.aborted, e); + return e; + } + updateResult(promiseState.rejected, e); + onError(); return e; - } - updateResult(promiseState.rejected, e); - onError(); - return e; - }); + }); }, Promise.resolve()); return { activeIndex, - result + result, }; } function whenAborted(signal) { return new Promise((resolve, reject) => { - const error = new Error("aborted"); - if (signal.aborted) - reject(error); - else - signal.addEventListener("abort", () => reject(error), { once: true }); + const error = new Error('aborted'); + if (signal.aborted) reject(error); + else signal.addEventListener('abort', () => reject(error), { once: true }); }); } function useAsyncState(promise, initialState, options) { @@ -2569,21 +2813,19 @@ function useAsyncState(promise, initialState, options) { onSuccess = noop, resetOnExecute = true, shallow = true, - throwError + throwError, } = options != null ? options : {}; const state = shallow ? shallowRef(initialState) : ref(initialState); const isReady = shallowRef(false); const isLoading = shallowRef(false); const error = shallowRef(void 0); async function execute(delay2 = 0, ...args) { - if (resetOnExecute) - state.value = initialState; + if (resetOnExecute) state.value = initialState; error.value = void 0; isReady.value = false; isLoading.value = true; - if (delay2 > 0) - await promiseTimeout(delay2); - const _promise = typeof promise === "function" ? promise(...args) : promise; + if (delay2 > 0) await promiseTimeout(delay2); + const _promise = typeof promise === 'function' ? promise(...args) : promise; try { const data = await _promise; state.value = data; @@ -2592,8 +2834,7 @@ function useAsyncState(promise, initialState, options) { } catch (e) { error.value = e; onError(e); - if (throwError) - throw e; + if (throwError) throw e; } finally { isLoading.value = false; } @@ -2607,18 +2848,21 @@ function useAsyncState(promise, initialState, options) { isReady, isLoading, error, - execute + execute, }; function waitUntilIsLoaded() { return new Promise((resolve, reject) => { - until(isLoading).toBe(false).then(() => resolve(shell)).catch(reject); + until(isLoading) + .toBe(false) + .then(() => resolve(shell)) + .catch(reject); }); } return { ...shell, then(onFulfilled, onRejected) { return waitUntilIsLoaded().then(onFulfilled, onRejected); - } + }, }; } var defaults = { @@ -2626,74 +2870,86 @@ var defaults = { object: (v) => JSON.stringify(v), set: (v) => JSON.stringify(Array.from(v)), map: (v) => JSON.stringify(Object.fromEntries(v)), - null: () => "" + null: () => '', }; function getDefaultSerialization(target) { - if (!target) - return defaults.null; - if (target instanceof Map) - return defaults.map; - else if (target instanceof Set) - return defaults.set; - else if (Array.isArray(target)) - return defaults.array; - else - return defaults.object; + if (!target) return defaults.null; + if (target instanceof Map) return defaults.map; + else if (target instanceof Set) return defaults.set; + else if (Array.isArray(target)) return defaults.array; + else return defaults.object; } function useBase64(target, options) { - const base64 = shallowRef(""); + const base64 = shallowRef(''); const promise = shallowRef(); function execute() { - if (!isClient) - return; + if (!isClient) return; promise.value = new Promise((resolve, reject) => { try { const _target = toValue(target); if (_target == null) { - resolve(""); - } else if (typeof _target === "string") { - resolve(blobToBase64(new Blob([_target], { type: "text/plain" }))); + resolve(''); + } else if (typeof _target === 'string') { + resolve(blobToBase64(new Blob([_target], { type: 'text/plain' }))); } else if (_target instanceof Blob) { resolve(blobToBase64(_target)); } else if (_target instanceof ArrayBuffer) { resolve(window.btoa(String.fromCharCode(...new Uint8Array(_target)))); } else if (_target instanceof HTMLCanvasElement) { - resolve(_target.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality)); + resolve( + _target.toDataURL( + options == null ? void 0 : options.type, + options == null ? void 0 : options.quality + ) + ); } else if (_target instanceof HTMLImageElement) { const img = _target.cloneNode(false); - img.crossOrigin = "Anonymous"; - imgLoaded(img).then(() => { - const canvas = document.createElement("canvas"); - const ctx = canvas.getContext("2d"); - canvas.width = img.width; - canvas.height = img.height; - ctx.drawImage(img, 0, 0, canvas.width, canvas.height); - resolve(canvas.toDataURL(options == null ? void 0 : options.type, options == null ? void 0 : options.quality)); - }).catch(reject); - } else if (typeof _target === "object") { - const _serializeFn = (options == null ? void 0 : options.serializer) || getDefaultSerialization(_target); + img.crossOrigin = 'Anonymous'; + imgLoaded(img) + .then(() => { + const canvas = document.createElement('canvas'); + const ctx = canvas.getContext('2d'); + canvas.width = img.width; + canvas.height = img.height; + ctx.drawImage(img, 0, 0, canvas.width, canvas.height); + resolve( + canvas.toDataURL( + options == null ? void 0 : options.type, + options == null ? void 0 : options.quality + ) + ); + }) + .catch(reject); + } else if (typeof _target === 'object') { + const _serializeFn = + (options == null ? void 0 : options.serializer) || + getDefaultSerialization(_target); const serialized = _serializeFn(_target); - return resolve(blobToBase64(new Blob([serialized], { type: "application/json" }))); + return resolve( + blobToBase64(new Blob([serialized], { type: 'application/json' })) + ); } else { - reject(new Error("target is unsupported types")); + reject(new Error('target is unsupported types')); } } catch (error) { reject(error); } }); promise.value.then((res) => { - base64.value = (options == null ? void 0 : options.dataUrl) === false ? res.replace(/^data:.*?;base64,/, "") : res; + base64.value = + (options == null ? void 0 : options.dataUrl) === false + ? res.replace(/^data:.*?;base64,/, '') + : res; }); return promise.value; } - if (isRef(target) || typeof target === "function") + if (isRef(target) || typeof target === 'function') watch(target, execute, { immediate: true }); - else - execute(); + else execute(); return { base64, promise, - execute + execute, }; } function imgLoaded(img) { @@ -2720,8 +2976,18 @@ function blobToBase64(blob) { } function useBattery(options = {}) { const { navigator: navigator2 = defaultNavigator } = options; - const events2 = ["chargingchange", "chargingtimechange", "dischargingtimechange", "levelchange"]; - const isSupported = useSupported(() => navigator2 && "getBattery" in navigator2 && typeof navigator2.getBattery === "function"); + const events2 = [ + 'chargingchange', + 'chargingtimechange', + 'dischargingtimechange', + 'levelchange', + ]; + const isSupported = useSupported( + () => + navigator2 && + 'getBattery' in navigator2 && + typeof navigator2.getBattery === 'function' + ); const charging = shallowRef(false); const chargingTime = shallowRef(0); const dischargingTime = shallowRef(0); @@ -2745,36 +3011,36 @@ function useBattery(options = {}) { charging, chargingTime, dischargingTime, - level + level, }; } function useBluetooth(options) { - let { - acceptAllDevices = false - } = options || {}; + let { acceptAllDevices = false } = options || {}; const { filters = void 0, optionalServices = void 0, - navigator: navigator2 = defaultNavigator + navigator: navigator2 = defaultNavigator, } = options || {}; - const isSupported = useSupported(() => navigator2 && "bluetooth" in navigator2); + const isSupported = useSupported( + () => navigator2 && 'bluetooth' in navigator2 + ); const device = shallowRef(); const error = shallowRef(null); watch(device, () => { connectToBluetoothGATTServer(); }); async function requestDevice() { - if (!isSupported.value) - return; + if (!isSupported.value) return; error.value = null; - if (filters && filters.length > 0) - acceptAllDevices = false; + if (filters && filters.length > 0) acceptAllDevices = false; try { - device.value = await (navigator2 == null ? void 0 : navigator2.bluetooth.requestDevice({ - acceptAllDevices, - filters, - optionalServices - })); + device.value = await (navigator2 == null + ? void 0 + : navigator2.bluetooth.requestDevice({ + acceptAllDevices, + filters, + optionalServices, + })); } catch (err) { error.value = err; } @@ -2789,7 +3055,9 @@ function useBluetooth(options) { async function connectToBluetoothGATTServer() { error.value = null; if (device.value && device.value.gatt) { - useEventListener(device, "gattserverdisconnected", reset, { passive: true }); + useEventListener(device, 'gattserverdisconnected', reset, { + passive: true, + }); try { server.value = await device.value.gatt.connect(); isConnected.value = server.value.connected; @@ -2800,8 +3068,7 @@ function useBluetooth(options) { } tryOnMounted(() => { var _a; - if (device.value) - (_a = device.value.gatt) == null ? void 0 : _a.connect(); + if (device.value) (_a = device.value.gatt) == null ? void 0 : _a.connect(); }); tryOnScopeDispose(() => { var _a; @@ -2817,13 +3084,15 @@ function useBluetooth(options) { // Server: server, // Errors: - error + error, }; } -var ssrWidthSymbol = Symbol("vueuse-ssr-width"); +var ssrWidthSymbol = Symbol('vueuse-ssr-width'); function useSSRWidth() { - const ssrWidth = hasInjectionContext() ? injectLocal(ssrWidthSymbol, null) : null; - return typeof ssrWidth === "number" ? ssrWidth : void 0; + const ssrWidth = hasInjectionContext() + ? injectLocal(ssrWidthSymbol, null) + : null; + return typeof ssrWidth === 'number' ? ssrWidth : void 0; } function provideSSRWidth(width, app) { if (app !== void 0) { @@ -2834,8 +3103,13 @@ function provideSSRWidth(width, app) { } function useMediaQuery(query, options = {}) { const { window: window2 = defaultWindow, ssrWidth = useSSRWidth() } = options; - const isSupported = useSupported(() => window2 && "matchMedia" in window2 && typeof window2.matchMedia === "function"); - const ssrSupport = shallowRef(typeof ssrWidth === "number"); + const isSupported = useSupported( + () => + window2 && + 'matchMedia' in window2 && + typeof window2.matchMedia === 'function' + ); + const ssrSupport = shallowRef(typeof ssrWidth === 'number'); const mediaQuery = shallowRef(); const matches = shallowRef(false); const handler = (event) => { @@ -2844,11 +3118,15 @@ function useMediaQuery(query, options = {}) { watchEffect(() => { if (ssrSupport.value) { ssrSupport.value = !isSupported.value; - const queryStrings = toValue(query).split(","); + const queryStrings = toValue(query).split(','); matches.value = queryStrings.some((queryString) => { - const not = queryString.includes("not all"); - const minWidth = queryString.match(/\(\s*min-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/); - const maxWidth = queryString.match(/\(\s*max-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/); + const not = queryString.includes('not all'); + const minWidth = queryString.match( + /\(\s*min-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/ + ); + const maxWidth = queryString.match( + /\(\s*max-width:\s*(-?\d+(?:\.\d*)?[a-z]+\s*)\)/ + ); let res = Boolean(minWidth || maxWidth); if (minWidth && res) { res = ssrWidth >= pxValue(minWidth[1]); @@ -2860,20 +3138,19 @@ function useMediaQuery(query, options = {}) { }); return; } - if (!isSupported.value) - return; + if (!isSupported.value) return; mediaQuery.value = window2.matchMedia(toValue(query)); matches.value = mediaQuery.value.matches; }); - useEventListener(mediaQuery, "change", handler, { passive: true }); + useEventListener(mediaQuery, 'change', handler, { passive: true }); return computed(() => matches.value); } var breakpointsTailwind = { - "sm": 640, - "md": 768, - "lg": 1024, - "xl": 1280, - "2xl": 1536 + sm: 640, + md: 768, + lg: 1024, + xl: 1280, + '2xl': 1536, }; var breakpointsBootstrapV5 = { xs: 0, @@ -2881,14 +3158,14 @@ var breakpointsBootstrapV5 = { md: 768, lg: 992, xl: 1200, - xxl: 1400 + xxl: 1400, }; var breakpointsVuetifyV2 = { xs: 0, sm: 600, md: 960, lg: 1264, - xl: 1904 + xl: 1904, }; var breakpointsVuetifyV3 = { xs: 0, @@ -2896,7 +3173,7 @@ var breakpointsVuetifyV3 = { md: 960, lg: 1280, xl: 1920, - xxl: 2560 + xxl: 2560, }; var breakpointsVuetify = breakpointsVuetifyV2; var breakpointsAntDesign = { @@ -2905,14 +3182,14 @@ var breakpointsAntDesign = { md: 768, lg: 992, xl: 1200, - xxl: 1600 + xxl: 1600, }; var breakpointsQuasar = { xs: 0, sm: 600, md: 1024, lg: 1440, - xl: 1920 + xl: 1920, }; var breakpointsSematic = { mobileS: 320, @@ -2921,54 +3198,57 @@ var breakpointsSematic = { tablet: 768, laptop: 1024, laptopL: 1440, - desktop4K: 2560 + desktop4K: 2560, }; var breakpointsMasterCss = { - "3xs": 360, - "2xs": 480, - "xs": 600, - "sm": 768, - "md": 1024, - "lg": 1280, - "xl": 1440, - "2xl": 1600, - "3xl": 1920, - "4xl": 2560 + '3xs': 360, + '2xs': 480, + xs: 600, + sm: 768, + md: 1024, + lg: 1280, + xl: 1440, + '2xl': 1600, + '3xl': 1920, + '4xl': 2560, }; var breakpointsPrimeFlex = { sm: 576, md: 768, lg: 992, - xl: 1200 + xl: 1200, }; var breakpointsElement = { xs: 0, sm: 768, md: 992, lg: 1200, - xl: 1920 + xl: 1920, }; function useBreakpoints(breakpoints, options = {}) { function getValue2(k, delta) { let v = toValue(breakpoints[toValue(k)]); - if (delta != null) - v = increaseWithUnit(v, delta); - if (typeof v === "number") - v = `${v}px`; + if (delta != null) v = increaseWithUnit(v, delta); + if (typeof v === 'number') v = `${v}px`; return v; } - const { window: window2 = defaultWindow, strategy = "min-width", ssrWidth = useSSRWidth() } = options; - const ssrSupport = typeof ssrWidth === "number"; + const { + window: window2 = defaultWindow, + strategy = 'min-width', + ssrWidth = useSSRWidth(), + } = options; + const ssrSupport = typeof ssrWidth === 'number'; const mounted = ssrSupport ? shallowRef(false) : { value: true }; if (ssrSupport) { - tryOnMounted(() => mounted.value = !!window2); + tryOnMounted(() => (mounted.value = !!window2)); } function match(query, size) { if (!mounted.value && ssrSupport) { - return query === "min" ? ssrWidth >= pxValue(size) : ssrWidth <= pxValue(size); + return query === 'min' + ? ssrWidth >= pxValue(size) + : ssrWidth <= pxValue(size); } - if (!window2) - return false; + if (!window2) return false; return window2.matchMedia(`(${query}-width: ${size})`).matches; } const greaterOrEqual = (k) => { @@ -2979,14 +3259,17 @@ function useBreakpoints(breakpoints, options = {}) { }; const shortcutMethods = Object.keys(breakpoints).reduce((shortcuts, k) => { Object.defineProperty(shortcuts, k, { - get: () => strategy === "min-width" ? greaterOrEqual(k) : smallerOrEqual(k), + get: () => + strategy === 'min-width' ? greaterOrEqual(k) : smallerOrEqual(k), enumerable: true, - configurable: true + configurable: true, }); return shortcuts; }, {}); function current() { - const points = Object.keys(breakpoints).map((k) => [k, shortcutMethods[k], pxValue(getValue2(k))]).sort((a, b) => a[2] - b[2]); + const points = Object.keys(breakpoints) + .map((k) => [k, shortcutMethods[k], pxValue(getValue2(k))]) + .sort((a, b) => a[2] - b[2]); return computed(() => points.filter(([, v]) => v.value).map(([k]) => k)); } return Object.assign(shortcutMethods, { @@ -2999,47 +3282,52 @@ function useBreakpoints(breakpoints, options = {}) { return useMediaQuery(() => `(max-width: ${getValue2(k, -0.1)})`, options); }, between(a, b) { - return useMediaQuery(() => `(min-width: ${getValue2(a)}) and (max-width: ${getValue2(b, -0.1)})`, options); + return useMediaQuery( + () => + `(min-width: ${getValue2(a)}) and (max-width: ${getValue2(b, -0.1)})`, + options + ); }, isGreater(k) { - return match("min", getValue2(k, 0.1)); + return match('min', getValue2(k, 0.1)); }, isGreaterOrEqual(k) { - return match("min", getValue2(k)); + return match('min', getValue2(k)); }, isSmaller(k) { - return match("max", getValue2(k, -0.1)); + return match('max', getValue2(k, -0.1)); }, isSmallerOrEqual(k) { - return match("max", getValue2(k)); + return match('max', getValue2(k)); }, isInBetween(a, b) { - return match("min", getValue2(a)) && match("max", getValue2(b, -0.1)); + return match('min', getValue2(a)) && match('max', getValue2(b, -0.1)); }, current, active() { const bps = current(); - return computed(() => bps.value.length === 0 ? "" : bps.value.at(strategy === "min-width" ? -1 : 0)); - } + return computed(() => + bps.value.length === 0 + ? '' + : bps.value.at(strategy === 'min-width' ? -1 : 0) + ); + }, }); } function useBroadcastChannel(options) { - const { - name, - window: window2 = defaultWindow - } = options; - const isSupported = useSupported(() => window2 && "BroadcastChannel" in window2); + const { name, window: window2 = defaultWindow } = options; + const isSupported = useSupported( + () => window2 && 'BroadcastChannel' in window2 + ); const isClosed = shallowRef(false); const channel = ref(); const data = ref(); const error = shallowRef(null); const post = (data2) => { - if (channel.value) - channel.value.postMessage(data2); + if (channel.value) channel.value.postMessage(data2); }; const close = () => { - if (channel.value) - channel.value.close(); + if (channel.value) channel.value.close(); isClosed.value = true; }; if (isSupported.value) { @@ -3047,17 +3335,32 @@ function useBroadcastChannel(options) { error.value = null; channel.value = new BroadcastChannel(name); const listenerOptions = { - passive: true + passive: true, }; - useEventListener(channel, "message", (e) => { - data.value = e.data; - }, listenerOptions); - useEventListener(channel, "messageerror", (e) => { - error.value = e; - }, listenerOptions); - useEventListener(channel, "close", () => { - isClosed.value = true; - }, listenerOptions); + useEventListener( + channel, + 'message', + (e) => { + data.value = e.data; + }, + listenerOptions + ); + useEventListener( + channel, + 'messageerror', + (e) => { + error.value = e; + }, + listenerOptions + ); + useEventListener( + channel, + 'close', + () => { + isClosed.value = true; + }, + listenerOptions + ); }); } tryOnScopeDispose(() => { @@ -3070,18 +3373,18 @@ function useBroadcastChannel(options) { post, close, error, - isClosed + isClosed, }; } var WRITABLE_PROPERTIES = [ - "hash", - "host", - "hostname", - "href", - "pathname", - "port", - "protocol", - "search" + 'hash', + 'host', + 'hostname', + 'href', + 'pathname', + 'port', + 'protocol', + 'search', ]; function useBrowserLocation(options = {}) { const { window: window2 = defaultWindow } = options; @@ -3090,59 +3393,84 @@ function useBrowserLocation(options = {}) { ); for (const [key, ref2] of objectEntries(refs)) { watch(ref2, (value) => { - if (!(window2 == null ? void 0 : window2.location) || window2.location[key] === value) + if ( + !(window2 == null ? void 0 : window2.location) || + window2.location[key] === value + ) return; window2.location[key] = value; }); } const buildState = (trigger) => { var _a; - const { state: state2, length } = (window2 == null ? void 0 : window2.history) || {}; + const { state: state2, length } = + (window2 == null ? void 0 : window2.history) || {}; const { origin } = (window2 == null ? void 0 : window2.location) || {}; for (const key of WRITABLE_PROPERTIES) - refs[key].value = (_a = window2 == null ? void 0 : window2.location) == null ? void 0 : _a[key]; + refs[key].value = + (_a = window2 == null ? void 0 : window2.location) == null + ? void 0 + : _a[key]; return reactive({ trigger, state: state2, length, origin, - ...refs + ...refs, }); }; - const state = ref(buildState("load")); + const state = ref(buildState('load')); if (window2) { const listenerOptions = { passive: true }; - useEventListener(window2, "popstate", () => state.value = buildState("popstate"), listenerOptions); - useEventListener(window2, "hashchange", () => state.value = buildState("hashchange"), listenerOptions); + useEventListener( + window2, + 'popstate', + () => (state.value = buildState('popstate')), + listenerOptions + ); + useEventListener( + window2, + 'hashchange', + () => (state.value = buildState('hashchange')), + listenerOptions + ); } return state; } function useCached(refValue, comparator = (a, b) => a === b, options) { const { deepRefs = true, ...watchOptions } = options || {}; const cachedValue = createRef(refValue.value, deepRefs); - watch(() => refValue.value, (value) => { - if (!comparator(value, cachedValue.value)) - cachedValue.value = value; - }, watchOptions); + watch( + () => refValue.value, + (value) => { + if (!comparator(value, cachedValue.value)) cachedValue.value = value; + }, + watchOptions + ); return cachedValue; } function usePermission(permissionDesc, options = {}) { - const { - controls = false, - navigator: navigator2 = defaultNavigator - } = options; - const isSupported = useSupported(() => navigator2 && "permissions" in navigator2); + const { controls = false, navigator: navigator2 = defaultNavigator } = + options; + const isSupported = useSupported( + () => navigator2 && 'permissions' in navigator2 + ); const permissionStatus = shallowRef(); - const desc = typeof permissionDesc === "string" ? { name: permissionDesc } : permissionDesc; + const desc = + typeof permissionDesc === 'string' + ? { name: permissionDesc } + : permissionDesc; const state = shallowRef(); const update = () => { var _a, _b; - state.value = (_b = (_a = permissionStatus.value) == null ? void 0 : _a.state) != null ? _b : "prompt"; + state.value = + (_b = (_a = permissionStatus.value) == null ? void 0 : _a.state) != null + ? _b + : 'prompt'; }; - useEventListener(permissionStatus, "change", update, { passive: true }); + useEventListener(permissionStatus, 'change', update, { passive: true }); const query = createSingletonPromise(async () => { - if (!isSupported.value) - return; + if (!isSupported.value) return; if (!permissionStatus.value) { try { permissionStatus.value = await navigator2.permissions.query(desc); @@ -3152,15 +3480,14 @@ function usePermission(permissionDesc, options = {}) { update(); } } - if (controls) - return toRaw(permissionStatus.value); + if (controls) return toRaw(permissionStatus.value); }); query(); if (controls) { return { state, isSupported, - query + query, }; } else { return state; @@ -3172,17 +3499,23 @@ function useClipboard(options = {}) { read = false, source, copiedDuring = 1500, - legacy = false + legacy = false, } = options; - const isClipboardApiSupported = useSupported(() => navigator2 && "clipboard" in navigator2); - const permissionRead = usePermission("clipboard-read"); - const permissionWrite = usePermission("clipboard-write"); + const isClipboardApiSupported = useSupported( + () => navigator2 && 'clipboard' in navigator2 + ); + const permissionRead = usePermission('clipboard-read'); + const permissionWrite = usePermission('clipboard-write'); const isSupported = computed(() => isClipboardApiSupported.value || legacy); - const text = shallowRef(""); + const text = shallowRef(''); const copied = shallowRef(false); - const timeout = useTimeoutFn(() => copied.value = false, copiedDuring, { immediate: false }); + const timeout = useTimeoutFn(() => (copied.value = false), copiedDuring, { + immediate: false, + }); async function updateText() { - let useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionRead.value)); + let useLegacy = !( + isClipboardApiSupported.value && isAllowed(permissionRead.value) + ); if (!useLegacy) { try { text.value = await navigator2.clipboard.readText(); @@ -3195,10 +3528,12 @@ function useClipboard(options = {}) { } } if (isSupported.value && read) - useEventListener(["copy", "cut"], updateText, { passive: true }); + useEventListener(['copy', 'cut'], updateText, { passive: true }); async function copy(value = toValue(source)) { if (isSupported.value && value != null) { - let useLegacy = !(isClipboardApiSupported.value && isAllowed(permissionWrite.value)); + let useLegacy = !( + isClipboardApiSupported.value && isAllowed(permissionWrite.value) + ); if (!useLegacy) { try { await navigator2.clipboard.writeText(value); @@ -3206,35 +3541,42 @@ function useClipboard(options = {}) { useLegacy = true; } } - if (useLegacy) - legacyCopy(value); + if (useLegacy) legacyCopy(value); text.value = value; copied.value = true; timeout.start(); } } function legacyCopy(value) { - const ta = document.createElement("textarea"); - ta.value = value != null ? value : ""; - ta.style.position = "absolute"; - ta.style.opacity = "0"; + const ta = document.createElement('textarea'); + ta.value = value != null ? value : ''; + ta.style.position = 'absolute'; + ta.style.opacity = '0'; document.body.appendChild(ta); ta.select(); - document.execCommand("copy"); + document.execCommand('copy'); ta.remove(); } function legacyRead() { var _a, _b, _c; - return (_c = (_b = (_a = document == null ? void 0 : document.getSelection) == null ? void 0 : _a.call(document)) == null ? void 0 : _b.toString()) != null ? _c : ""; + return (_c = + (_b = + (_a = document == null ? void 0 : document.getSelection) == null + ? void 0 + : _a.call(document)) == null + ? void 0 + : _b.toString()) != null + ? _c + : ''; } function isAllowed(status) { - return status === "granted" || status === "prompt"; + return status === 'granted' || status === 'prompt'; } return { isSupported, text, copied, - copy + copy, }; } function useClipboardItems(options = {}) { @@ -3242,12 +3584,16 @@ function useClipboardItems(options = {}) { navigator: navigator2 = defaultNavigator, read = false, source, - copiedDuring = 1500 + copiedDuring = 1500, } = options; - const isSupported = useSupported(() => navigator2 && "clipboard" in navigator2); + const isSupported = useSupported( + () => navigator2 && 'clipboard' in navigator2 + ); const content = ref([]); const copied = shallowRef(false); - const timeout = useTimeoutFn(() => copied.value = false, copiedDuring, { immediate: false }); + const timeout = useTimeoutFn(() => (copied.value = false), copiedDuring, { + immediate: false, + }); function updateContent() { if (isSupported.value) { navigator2.clipboard.read().then((items) => { @@ -3256,7 +3602,7 @@ function useClipboardItems(options = {}) { } } if (isSupported.value && read) - useEventListener(["copy", "cut"], updateContent, { passive: true }); + useEventListener(['copy', 'cut'], updateContent, { passive: true }); async function copy(value = toValue(source)) { if (isSupported.value && value != null) { await navigator2.clipboard.write(value); @@ -3269,7 +3615,7 @@ function useClipboardItems(options = {}) { isSupported, content, copied, - copy + copy, }; } function cloneFnJSON(source) { @@ -3284,40 +3630,52 @@ function useCloned(source, options = {}) { clone = cloneFnJSON, // watch options deep = true, - immediate = true + immediate = true, } = options; - watch(cloned, () => { - if (_lastSync) { - _lastSync = false; - return; + watch( + cloned, + () => { + if (_lastSync) { + _lastSync = false; + return; + } + isModified.value = true; + }, + { + deep: true, + flush: 'sync', } - isModified.value = true; - }, { - deep: true, - flush: "sync" - }); + ); function sync() { _lastSync = true; isModified.value = false; cloned.value = clone(toValue(source)); } - if (!manual && (isRef(source) || typeof source === "function")) { + if (!manual && (isRef(source) || typeof source === 'function')) { watch(source, sync, { ...options, deep, - immediate + immediate, }); } else { sync(); } return { cloned, isModified, sync }; } -var _global = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -var globalKey = "__vueuse_ssr_handlers__"; +var _global = + typeof globalThis !== 'undefined' + ? globalThis + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : typeof self !== 'undefined' + ? self + : {}; +var globalKey = '__vueuse_ssr_handlers__'; var handlers = getHandlers(); function getHandlers() { - if (!(globalKey in _global)) - _global[globalKey] = _global[globalKey] || {}; + if (!(globalKey in _global)) _global[globalKey] = _global[globalKey] || {}; return _global[globalKey]; } function getSSRHandler(key, fallback) { @@ -3327,50 +3685,66 @@ function setSSRHandler(key, fn) { handlers[key] = fn; } function usePreferredDark(options) { - return useMediaQuery("(prefers-color-scheme: dark)", options); + return useMediaQuery('(prefers-color-scheme: dark)', options); } function guessSerializerType(rawInit) { - return rawInit == null ? "any" : rawInit instanceof Set ? "set" : rawInit instanceof Map ? "map" : rawInit instanceof Date ? "date" : typeof rawInit === "boolean" ? "boolean" : typeof rawInit === "string" ? "string" : typeof rawInit === "object" ? "object" : !Number.isNaN(rawInit) ? "number" : "any"; + return rawInit == null + ? 'any' + : rawInit instanceof Set + ? 'set' + : rawInit instanceof Map + ? 'map' + : rawInit instanceof Date + ? 'date' + : typeof rawInit === 'boolean' + ? 'boolean' + : typeof rawInit === 'string' + ? 'string' + : typeof rawInit === 'object' + ? 'object' + : !Number.isNaN(rawInit) + ? 'number' + : 'any'; } var StorageSerializers = { boolean: { - read: (v) => v === "true", - write: (v) => String(v) + read: (v) => v === 'true', + write: (v) => String(v), }, object: { read: (v) => JSON.parse(v), - write: (v) => JSON.stringify(v) + write: (v) => JSON.stringify(v), }, number: { read: (v) => Number.parseFloat(v), - write: (v) => String(v) + write: (v) => String(v), }, any: { read: (v) => v, - write: (v) => String(v) + write: (v) => String(v), }, string: { read: (v) => v, - write: (v) => String(v) + write: (v) => String(v), }, map: { read: (v) => new Map(JSON.parse(v)), - write: (v) => JSON.stringify(Array.from(v.entries())) + write: (v) => JSON.stringify(Array.from(v.entries())), }, set: { read: (v) => new Set(JSON.parse(v)), - write: (v) => JSON.stringify(Array.from(v)) + write: (v) => JSON.stringify(Array.from(v)), }, date: { read: (v) => new Date(v), - write: (v) => v.toISOString() - } + write: (v) => v.toISOString(), + }, }; -var customStorageEventName = "vueuse-storage"; +var customStorageEventName = 'vueuse-storage'; function useStorage(key, defaults2, storage, options = {}) { var _a; const { - flush = "pre", + flush = 'pre', deep = true, listenToStorageChanges = true, writeDefaults = true, @@ -3381,13 +3755,15 @@ function useStorage(key, defaults2, storage, options = {}) { onError = (e) => { console.error(e); }, - initOnMounted + initOnMounted, } = options; - const data = (shallow ? shallowRef : ref)(typeof defaults2 === "function" ? defaults2() : defaults2); + const data = (shallow ? shallowRef : ref)( + typeof defaults2 === 'function' ? defaults2() : defaults2 + ); const keyComputed = computed(() => toValue(key)); if (!storage) { try { - storage = getSSRHandler("getDefaultStorage", () => { + storage = getSSRHandler('getDefaultStorage', () => { var _a2; return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage; })(); @@ -3395,11 +3771,11 @@ function useStorage(key, defaults2, storage, options = {}) { onError(e); } } - if (!storage) - return data; + if (!storage) return data; const rawInit = toValue(defaults2); const type = guessSerializerType(rawInit); - const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type]; + const serializer = + (_a = options.serializer) != null ? _a : StorageSerializers[type]; const { pause: pauseWatch, resume: resumeWatch } = watchPausable( data, () => write(data.value), @@ -3409,26 +3785,32 @@ function useStorage(key, defaults2, storage, options = {}) { if (window2 && listenToStorageChanges) { tryOnMounted(() => { if (storage instanceof Storage) - useEventListener(window2, "storage", update, { passive: true }); + useEventListener(window2, 'storage', update, { passive: true }); else - useEventListener(window2, customStorageEventName, updateFromCustomEvent); - if (initOnMounted) - update(); + useEventListener( + window2, + customStorageEventName, + updateFromCustomEvent + ); + if (initOnMounted) update(); }); } - if (!initOnMounted) - update(); + if (!initOnMounted) update(); function dispatchWriteEvent(oldValue, newValue) { if (window2) { const payload = { key: keyComputed.value, oldValue, newValue, - storageArea: storage + storageArea: storage, }; - window2.dispatchEvent(storage instanceof Storage ? new StorageEvent("storage", payload) : new CustomEvent(customStorageEventName, { - detail: payload - })); + window2.dispatchEvent( + storage instanceof Storage + ? new StorageEvent('storage', payload) + : new CustomEvent(customStorageEventName, { + detail: payload, + }) + ); } } function write(v) { @@ -3449,44 +3831,45 @@ function useStorage(key, defaults2, storage, options = {}) { } } function read(event) { - const rawValue = event ? event.newValue : storage.getItem(keyComputed.value); + const rawValue = event + ? event.newValue + : storage.getItem(keyComputed.value); if (rawValue == null) { if (writeDefaults && rawInit != null) storage.setItem(keyComputed.value, serializer.write(rawInit)); return rawInit; } else if (!event && mergeDefaults) { const value = serializer.read(rawValue); - if (typeof mergeDefaults === "function") + if (typeof mergeDefaults === 'function') return mergeDefaults(value, rawInit); - else if (type === "object" && !Array.isArray(value)) + else if (type === 'object' && !Array.isArray(value)) return { ...rawInit, ...value }; return value; - } else if (typeof rawValue !== "string") { + } else if (typeof rawValue !== 'string') { return rawValue; } else { return serializer.read(rawValue); } } function update(event) { - if (event && event.storageArea !== storage) - return; + if (event && event.storageArea !== storage) return; if (event && event.key == null) { data.value = rawInit; return; } - if (event && event.key !== keyComputed.value) - return; + if (event && event.key !== keyComputed.value) return; pauseWatch(); try { - if ((event == null ? void 0 : event.newValue) !== serializer.write(data.value)) + if ( + (event == null ? void 0 : event.newValue) !== + serializer.write(data.value) + ) data.value = read(event); } catch (e) { onError(e); } finally { - if (event) - nextTick(resumeWatch); - else - resumeWatch(); + if (event) nextTick(resumeWatch); + else resumeWatch(); } } function updateFromCustomEvent(event) { @@ -3494,55 +3877,74 @@ function useStorage(key, defaults2, storage, options = {}) { } return data; } -var CSS_DISABLE_TRANS = "*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}"; +var CSS_DISABLE_TRANS = + '*,*::before,*::after{-webkit-transition:none!important;-moz-transition:none!important;-o-transition:none!important;-ms-transition:none!important;transition:none!important}'; function useColorMode(options = {}) { const { - selector = "html", - attribute = "class", - initialValue = "auto", + selector = 'html', + attribute = 'class', + initialValue = 'auto', window: window2 = defaultWindow, storage, - storageKey = "vueuse-color-scheme", + storageKey = 'vueuse-color-scheme', listenToStorageChanges = true, storageRef, emitAuto, - disableTransition = true + disableTransition = true, } = options; const modes = { - auto: "", - light: "light", - dark: "dark", - ...options.modes || {} + auto: '', + light: 'light', + dark: 'dark', + ...(options.modes || {}), }; const preferredDark = usePreferredDark({ window: window2 }); - const system = computed(() => preferredDark.value ? "dark" : "light"); - const store = storageRef || (storageKey == null ? toRef2(initialValue) : useStorage(storageKey, initialValue, storage, { window: window2, listenToStorageChanges })); - const state = computed(() => store.value === "auto" ? system.value : store.value); + const system = computed(() => (preferredDark.value ? 'dark' : 'light')); + const store = + storageRef || + (storageKey == null + ? toRef2(initialValue) + : useStorage(storageKey, initialValue, storage, { + window: window2, + listenToStorageChanges, + })); + const state = computed(() => + store.value === 'auto' ? system.value : store.value + ); const updateHTMLAttrs = getSSRHandler( - "updateHTMLAttrs", + 'updateHTMLAttrs', (selector2, attribute2, value) => { - const el = typeof selector2 === "string" ? window2 == null ? void 0 : window2.document.querySelector(selector2) : unrefElement(selector2); - if (!el) - return; + const el = + typeof selector2 === 'string' + ? window2 == null + ? void 0 + : window2.document.querySelector(selector2) + : unrefElement(selector2); + if (!el) return; const classesToAdd = /* @__PURE__ */ new Set(); const classesToRemove = /* @__PURE__ */ new Set(); let attributeToChange = null; - if (attribute2 === "class") { + if (attribute2 === 'class') { const current = value.split(/\s/g); - Object.values(modes).flatMap((i) => (i || "").split(/\s/g)).filter(Boolean).forEach((v) => { - if (current.includes(v)) - classesToAdd.add(v); - else - classesToRemove.add(v); - }); + Object.values(modes) + .flatMap((i) => (i || '').split(/\s/g)) + .filter(Boolean) + .forEach((v) => { + if (current.includes(v)) classesToAdd.add(v); + else classesToRemove.add(v); + }); } else { attributeToChange = { key: attribute2, value }; } - if (classesToAdd.size === 0 && classesToRemove.size === 0 && attributeToChange === null) + if ( + classesToAdd.size === 0 && + classesToRemove.size === 0 && + attributeToChange === null + ) return; let style; if (disableTransition) { - style = window2.document.createElement("style"); + style = window2.document.createElement('style'); style.appendChild(document.createTextNode(CSS_DISABLE_TRANS)); window2.document.head.appendChild(style); } @@ -3563,15 +3965,17 @@ function useColorMode(options = {}) { ); function defaultOnChanged(mode) { var _a; - updateHTMLAttrs(selector, attribute, (_a = modes[mode]) != null ? _a : mode); + updateHTMLAttrs( + selector, + attribute, + (_a = modes[mode]) != null ? _a : mode + ); } function onChanged(mode) { - if (options.onChanged) - options.onChanged(mode, defaultOnChanged); - else - defaultOnChanged(mode); + if (options.onChanged) options.onChanged(mode, defaultOnChanged); + else defaultOnChanged(mode); } - watch(state, onChanged, { flush: "post", immediate: true }); + watch(state, onChanged, { flush: 'post', immediate: true }); tryOnMounted(() => onChanged(state.value)); const auto = computed({ get() { @@ -3579,7 +3983,7 @@ function useColorMode(options = {}) { }, set(v) { store.value = v; - } + }, }); return Object.assign(auto, { store, system, state }); } @@ -3612,25 +4016,39 @@ function useConfirmDialog(revealed = shallowRef(false)) { cancel, onReveal: revealHook.on, onConfirm: confirmHook.on, - onCancel: cancelHook.on + onCancel: cancelHook.on, }; } function useCountdown(initialCountdown, options) { var _a, _b; const remaining = shallowRef(toValue(initialCountdown)); - const intervalController = useIntervalFn(() => { - var _a2, _b2; - const value = remaining.value - 1; - remaining.value = value < 0 ? 0 : value; - (_a2 = options == null ? void 0 : options.onTick) == null ? void 0 : _a2.call(options); - if (remaining.value <= 0) { - intervalController.pause(); - (_b2 = options == null ? void 0 : options.onComplete) == null ? void 0 : _b2.call(options); + const intervalController = useIntervalFn( + () => { + var _a2, _b2; + const value = remaining.value - 1; + remaining.value = value < 0 ? 0 : value; + (_a2 = options == null ? void 0 : options.onTick) == null + ? void 0 + : _a2.call(options); + if (remaining.value <= 0) { + intervalController.pause(); + (_b2 = options == null ? void 0 : options.onComplete) == null + ? void 0 + : _b2.call(options); + } + }, + (_a = options == null ? void 0 : options.interval) != null ? _a : 1e3, + { + immediate: + (_b = options == null ? void 0 : options.immediate) != null + ? _b + : false, } - }, (_a = options == null ? void 0 : options.interval) != null ? _a : 1e3, { immediate: (_b = options == null ? void 0 : options.immediate) != null ? _b : false }); + ); const reset = (countdown) => { var _a2; - remaining.value = (_a2 = toValue(countdown)) != null ? _a2 : toValue(initialCountdown); + remaining.value = + (_a2 = toValue(countdown)) != null ? _a2 : toValue(initialCountdown); }; const stop = () => { intervalController.pause(); @@ -3654,36 +4072,47 @@ function useCountdown(initialCountdown, options) { start, pause: intervalController.pause, resume, - isActive: intervalController.isActive + isActive: intervalController.isActive, }; } function useCssVar(prop, target, options = {}) { - const { window: window2 = defaultWindow, initialValue, observe = false } = options; + const { + window: window2 = defaultWindow, + initialValue, + observe = false, + } = options; const variable = shallowRef(initialValue); const elRef = computed(() => { var _a; - return unrefElement(target) || ((_a = window2 == null ? void 0 : window2.document) == null ? void 0 : _a.documentElement); + return ( + unrefElement(target) || + ((_a = window2 == null ? void 0 : window2.document) == null + ? void 0 + : _a.documentElement) + ); }); function updateCssVar() { var _a; const key = toValue(prop); const el = toValue(elRef); if (el && window2 && key) { - const value = (_a = window2.getComputedStyle(el).getPropertyValue(key)) == null ? void 0 : _a.trim(); + const value = + (_a = window2.getComputedStyle(el).getPropertyValue(key)) == null + ? void 0 + : _a.trim(); variable.value = value || variable.value || initialValue; } } if (observe) { useMutationObserver(elRef, updateCssVar, { - attributeFilter: ["style", "class"], - window: window2 + attributeFilter: ['style', 'class'], + window: window2, }); } watch( [elRef, () => toValue(prop)], (_, old) => { - if (old[0] && old[1]) - old[0].style.removeProperty(old[1]); + if (old[0] && old[1]) old[0].style.removeProperty(old[1]); updateCssVar(); }, { immediate: true } @@ -3693,10 +4122,8 @@ function useCssVar(prop, target, options = {}) { ([val, el]) => { const raw_prop = toValue(prop); if ((el == null ? void 0 : el.style) && raw_prop) { - if (val == null) - el.style.removeProperty(raw_prop); - else - el.style.setProperty(raw_prop, val); + if (val == null) el.style.removeProperty(raw_prop); + else el.style.setProperty(raw_prop, val); } }, { immediate: true } @@ -3707,7 +4134,7 @@ function useCurrentElement(rootComponent) { const vm = getCurrentInstance(); const currentElement = computedWithControl( () => null, - () => rootComponent ? unrefElement(rootComponent) : vm.proxy.$el + () => (rootComponent ? unrefElement(rootComponent) : vm.proxy.$el) ); onUpdated(currentElement.trigger); onMounted(currentElement.trigger); @@ -3720,19 +4147,24 @@ function useCycleList(list, options) { get() { var _a; const targetList = listRef.value; - let index2 = (options == null ? void 0 : options.getIndexOf) ? options.getIndexOf(state.value, targetList) : targetList.indexOf(state.value); + let index2 = (options == null ? void 0 : options.getIndexOf) + ? options.getIndexOf(state.value, targetList) + : targetList.indexOf(state.value); if (index2 < 0) - index2 = (_a = options == null ? void 0 : options.fallbackIndex) != null ? _a : 0; + index2 = + (_a = options == null ? void 0 : options.fallbackIndex) != null + ? _a + : 0; return index2; }, set(v) { set2(v); - } + }, }); function set2(i) { const targetList = listRef.value; const length = targetList.length; - const index2 = (i % length + length) % length; + const index2 = ((i % length) + length) % length; const value = targetList[index2]; state.value = value; return value; @@ -3748,7 +4180,13 @@ function useCycleList(list, options) { } function getInitialValue() { var _a, _b; - return (_b = toValue((_a = options == null ? void 0 : options.initialValue) != null ? _a : toValue(list)[0])) != null ? _b : void 0; + return (_b = toValue( + (_a = options == null ? void 0 : options.initialValue) != null + ? _a + : toValue(list)[0] + )) != null + ? _b + : void 0; } watch(listRef, () => set2(index.value)); return { @@ -3756,40 +4194,36 @@ function useCycleList(list, options) { index, next, prev, - go: set2 + go: set2, }; } function useDark(options = {}) { - const { - valueDark = "dark", - valueLight = "" - } = options; + const { valueDark = 'dark', valueLight = '' } = options; const mode = useColorMode({ ...options, onChanged: (mode2, defaultHandler) => { var _a; if (options.onChanged) - (_a = options.onChanged) == null ? void 0 : _a.call(options, mode2 === "dark", defaultHandler, mode2); - else - defaultHandler(mode2); + (_a = options.onChanged) == null + ? void 0 + : _a.call(options, mode2 === 'dark', defaultHandler, mode2); + else defaultHandler(mode2); }, modes: { dark: valueDark, - light: valueLight - } + light: valueLight, + }, }); const system = computed(() => mode.system.value); const isDark = computed({ get() { - return mode.value === "dark"; + return mode.value === 'dark'; }, set(v) { - const modeVal = v ? "dark" : "light"; - if (system.value === modeVal) - mode.value = "auto"; - else - mode.value = modeVal; - } + const modeVal = v ? 'dark' : 'light'; + if (system.value === modeVal) mode.value = 'auto'; + else mode.value = modeVal; + }, }); return isDark; } @@ -3797,25 +4231,25 @@ function fnBypass(v) { return v; } function fnSetSource(source, value) { - return source.value = value; + return (source.value = value); } function defaultDump(clone) { - return clone ? typeof clone === "function" ? clone : cloneFnJSON : fnBypass; + return clone ? (typeof clone === 'function' ? clone : cloneFnJSON) : fnBypass; } function defaultParse(clone) { - return clone ? typeof clone === "function" ? clone : cloneFnJSON : fnBypass; + return clone ? (typeof clone === 'function' ? clone : cloneFnJSON) : fnBypass; } function useManualRefHistory(source, options = {}) { const { clone = false, dump = defaultDump(clone), parse = defaultParse(clone), - setSource = fnSetSource + setSource = fnSetSource, } = options; function _createHistoryRecord() { return markRaw({ snapshot: dump(source.value), - timestamp: timestamp() + timestamp: timestamp(), }); } const last = ref(_createHistoryRecord()); @@ -3869,26 +4303,18 @@ function useManualRefHistory(source, options = {}) { commit, reset, undo, - redo + redo, }; } function useRefHistory(source, options = {}) { - const { - deep = false, - flush = "pre", - eventFilter - } = options; + const { deep = false, flush = 'pre', eventFilter } = options; const { eventFilter: composedFilter, pause, resume: resumeTracking, - isActive: isTracking + isActive: isTracking, } = pausableFilter(eventFilter); - const { - ignoreUpdates, - ignorePrevAsyncUpdates, - stop - } = watchIgnorable( + const { ignoreUpdates, ignorePrevAsyncUpdates, stop } = watchIgnorable( source, commit, { deep, flush, eventFilter: composedFilter } @@ -3899,7 +4325,11 @@ function useRefHistory(source, options = {}) { source2.value = value; }); } - const manualHistory = useManualRefHistory(source, { ...options, clone: options.clone || deep, setSource }); + const manualHistory = useManualRefHistory(source, { + ...options, + clone: options.clone || deep, + setSource, + }); const { clear, commit: manualCommit } = manualHistory; function commit() { ignorePrevAsyncUpdates(); @@ -3907,17 +4337,15 @@ function useRefHistory(source, options = {}) { } function resume(commitNow) { resumeTracking(); - if (commitNow) - commit(); + if (commitNow) commit(); } function batch(fn) { let canceled = false; - const cancel = () => canceled = true; + const cancel = () => (canceled = true); ignoreUpdates(() => { fn(cancel); }); - if (!canceled) - commit(); + if (!canceled) commit(); } function dispose() { stop(); @@ -3930,24 +4358,31 @@ function useRefHistory(source, options = {}) { resume, commit, batch, - dispose + dispose, }; } function useDebouncedRefHistory(source, options = {}) { const filter = options.debounce ? debounceFilter(options.debounce) : void 0; const history = useRefHistory(source, { ...options, eventFilter: filter }); return { - ...history + ...history, }; } function useDeviceMotion(options = {}) { const { window: window2 = defaultWindow, requestPermissions = false, - eventFilter = bypassFilter + eventFilter = bypassFilter, } = options; - const isSupported = useSupported(() => typeof DeviceMotionEvent !== "undefined"); - const requirePermissions = useSupported(() => isSupported.value && "requestPermission" in DeviceMotionEvent && typeof DeviceMotionEvent.requestPermission === "function"); + const isSupported = useSupported( + () => typeof DeviceMotionEvent !== 'undefined' + ); + const requirePermissions = useSupported( + () => + isSupported.value && + 'requestPermission' in DeviceMotionEvent && + typeof DeviceMotionEvent.requestPermission === 'function' + ); const permissionGranted = shallowRef(false); const acceleration = ref({ x: null, y: null, z: null }); const rotationRate = ref({ alpha: null, beta: null, gamma: null }); @@ -3955,45 +4390,53 @@ function useDeviceMotion(options = {}) { const accelerationIncludingGravity = ref({ x: null, y: null, - z: null + z: null, }); function init() { if (window2) { - const onDeviceMotion = createFilterWrapper( - eventFilter, - (event) => { - var _a, _b, _c, _d, _e, _f, _g, _h, _i; - acceleration.value = { - x: ((_a = event.acceleration) == null ? void 0 : _a.x) || null, - y: ((_b = event.acceleration) == null ? void 0 : _b.y) || null, - z: ((_c = event.acceleration) == null ? void 0 : _c.z) || null - }; - accelerationIncludingGravity.value = { - x: ((_d = event.accelerationIncludingGravity) == null ? void 0 : _d.x) || null, - y: ((_e = event.accelerationIncludingGravity) == null ? void 0 : _e.y) || null, - z: ((_f = event.accelerationIncludingGravity) == null ? void 0 : _f.z) || null - }; - rotationRate.value = { - alpha: ((_g = event.rotationRate) == null ? void 0 : _g.alpha) || null, - beta: ((_h = event.rotationRate) == null ? void 0 : _h.beta) || null, - gamma: ((_i = event.rotationRate) == null ? void 0 : _i.gamma) || null - }; - interval.value = event.interval; - } - ); - useEventListener(window2, "devicemotion", onDeviceMotion, { passive: true }); + const onDeviceMotion = createFilterWrapper(eventFilter, (event) => { + var _a, _b, _c, _d, _e, _f, _g, _h, _i; + acceleration.value = { + x: ((_a = event.acceleration) == null ? void 0 : _a.x) || null, + y: ((_b = event.acceleration) == null ? void 0 : _b.y) || null, + z: ((_c = event.acceleration) == null ? void 0 : _c.z) || null, + }; + accelerationIncludingGravity.value = { + x: + ((_d = event.accelerationIncludingGravity) == null + ? void 0 + : _d.x) || null, + y: + ((_e = event.accelerationIncludingGravity) == null + ? void 0 + : _e.y) || null, + z: + ((_f = event.accelerationIncludingGravity) == null + ? void 0 + : _f.z) || null, + }; + rotationRate.value = { + alpha: + ((_g = event.rotationRate) == null ? void 0 : _g.alpha) || null, + beta: ((_h = event.rotationRate) == null ? void 0 : _h.beta) || null, + gamma: + ((_i = event.rotationRate) == null ? void 0 : _i.gamma) || null, + }; + interval.value = event.interval; + }); + useEventListener(window2, 'devicemotion', onDeviceMotion, { + passive: true, + }); } } const ensurePermissions = async () => { - if (!requirePermissions.value) - permissionGranted.value = true; - if (permissionGranted.value) - return; + if (!requirePermissions.value) permissionGranted.value = true; + if (permissionGranted.value) return; if (requirePermissions.value) { const requestPermission = DeviceMotionEvent.requestPermission; try { const response = await requestPermission(); - if (response === "granted") { + if (response === 'granted') { permissionGranted.value = true; init(); } @@ -4017,45 +4460,56 @@ function useDeviceMotion(options = {}) { isSupported, requirePermissions, ensurePermissions, - permissionGranted + permissionGranted, }; } function useDeviceOrientation(options = {}) { const { window: window2 = defaultWindow } = options; - const isSupported = useSupported(() => window2 && "DeviceOrientationEvent" in window2); + const isSupported = useSupported( + () => window2 && 'DeviceOrientationEvent' in window2 + ); const isAbsolute = shallowRef(false); const alpha = shallowRef(null); const beta = shallowRef(null); const gamma = shallowRef(null); if (window2 && isSupported.value) { - useEventListener(window2, "deviceorientation", (event) => { - isAbsolute.value = event.absolute; - alpha.value = event.alpha; - beta.value = event.beta; - gamma.value = event.gamma; - }, { passive: true }); + useEventListener( + window2, + 'deviceorientation', + (event) => { + isAbsolute.value = event.absolute; + alpha.value = event.alpha; + beta.value = event.beta; + gamma.value = event.gamma; + }, + { passive: true } + ); } return { isSupported, isAbsolute, alpha, beta, - gamma + gamma, }; } function useDevicePixelRatio(options = {}) { - const { - window: window2 = defaultWindow - } = options; + const { window: window2 = defaultWindow } = options; const pixelRatio = shallowRef(1); - const query = useMediaQuery(() => `(resolution: ${pixelRatio.value}dppx)`, options); + const query = useMediaQuery( + () => `(resolution: ${pixelRatio.value}dppx)`, + options + ); let stop = noop; if (window2) { - stop = watchImmediate(query, () => pixelRatio.value = window2.devicePixelRatio); + stop = watchImmediate( + query, + () => (pixelRatio.value = window2.devicePixelRatio) + ); } return { pixelRatio: readonly(pixelRatio), - stop + stop, }; } function useDevicesList(options = {}) { @@ -4063,18 +4517,28 @@ function useDevicesList(options = {}) { navigator: navigator2 = defaultNavigator, requestPermissions = false, constraints = { audio: true, video: true }, - onUpdated: onUpdated2 + onUpdated: onUpdated2, } = options; const devices = ref([]); - const videoInputs = computed(() => devices.value.filter((i) => i.kind === "videoinput")); - const audioInputs = computed(() => devices.value.filter((i) => i.kind === "audioinput")); - const audioOutputs = computed(() => devices.value.filter((i) => i.kind === "audiooutput")); - const isSupported = useSupported(() => navigator2 && navigator2.mediaDevices && navigator2.mediaDevices.enumerateDevices); + const videoInputs = computed(() => + devices.value.filter((i) => i.kind === 'videoinput') + ); + const audioInputs = computed(() => + devices.value.filter((i) => i.kind === 'audioinput') + ); + const audioOutputs = computed(() => + devices.value.filter((i) => i.kind === 'audiooutput') + ); + const isSupported = useSupported( + () => + navigator2 && + navigator2.mediaDevices && + navigator2.mediaDevices.enumerateDevices + ); const permissionGranted = shallowRef(false); let stream; async function update() { - if (!isSupported.value) - return; + if (!isSupported.value) return; devices.value = await navigator2.mediaDevices.enumerateDevices(); onUpdated2 == null ? void 0 : onUpdated2(devices.value); if (stream) { @@ -4083,14 +4547,12 @@ function useDevicesList(options = {}) { } } async function ensurePermissions() { - const deviceName = constraints.video ? "camera" : "microphone"; - if (!isSupported.value) - return false; - if (permissionGranted.value) - return true; + const deviceName = constraints.video ? 'camera' : 'microphone'; + if (!isSupported.value) return false; + if (permissionGranted.value) return true; const { state, query } = usePermission(deviceName, { controls: true }); await query(); - if (state.value !== "granted") { + if (state.value !== 'granted') { let granted = true; try { stream = await navigator2.mediaDevices.getUserMedia(constraints); @@ -4106,9 +4568,10 @@ function useDevicesList(options = {}) { return permissionGranted.value; } if (isSupported.value) { - if (requestPermissions) - ensurePermissions(); - useEventListener(navigator2.mediaDevices, "devicechange", update, { passive: true }); + if (requestPermissions) ensurePermissions(); + useEventListener(navigator2.mediaDevices, 'devicechange', update, { + passive: true, + }); update(); } return { @@ -4118,7 +4581,7 @@ function useDevicesList(options = {}) { videoInputs, audioInputs, audioOutputs, - isSupported + isSupported, }; } function useDisplayMedia(options = {}) { @@ -4129,21 +4592,30 @@ function useDisplayMedia(options = {}) { const { navigator: navigator2 = defaultNavigator } = options; const isSupported = useSupported(() => { var _a2; - return (_a2 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null ? void 0 : _a2.getDisplayMedia; + return (_a2 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null + ? void 0 + : _a2.getDisplayMedia; }); const constraint = { audio, video }; const stream = shallowRef(); async function _start() { var _a2; - if (!isSupported.value || stream.value) - return; + if (!isSupported.value || stream.value) return; stream.value = await navigator2.mediaDevices.getDisplayMedia(constraint); - (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => useEventListener(t, "ended", stop, { passive: true })); + (_a2 = stream.value) == null + ? void 0 + : _a2 + .getTracks() + .forEach((t) => + useEventListener(t, 'ended', stop, { passive: true }) + ); return stream.value; } async function _stop() { var _a2; - (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop()); + (_a2 = stream.value) == null + ? void 0 + : _a2.getTracks().forEach((t) => t.stop()); stream.value = void 0; } function stop() { @@ -4152,17 +4624,14 @@ function useDisplayMedia(options = {}) { } async function start() { await _start(); - if (stream.value) - enabled.value = true; + if (stream.value) enabled.value = true; return stream.value; } watch( enabled, (v) => { - if (v) - _start(); - else - _stop(); + if (v) _start(); + else _stop(); }, { immediate: true } ); @@ -4171,17 +4640,21 @@ function useDisplayMedia(options = {}) { stream, start, stop, - enabled + enabled, }; } function useDocumentVisibility(options = {}) { const { document: document2 = defaultDocument } = options; - if (!document2) - return shallowRef("visible"); + if (!document2) return shallowRef('visible'); const visibility = shallowRef(document2.visibilityState); - useEventListener(document2, "visibilitychange", () => { - visibility.value = document2.visibilityState; - }, { passive: true }); + useEventListener( + document2, + 'visibilitychange', + () => { + visibility.value = document2.visibilityState; + }, + { passive: true } + ); return visibility; } function useDraggable(target, options = {}) { @@ -4195,77 +4668,81 @@ function useDraggable(target, options = {}) { onEnd, onStart, initialValue, - axis = "both", + axis = 'both', draggingElement = defaultWindow, containerElement, handle: draggingHandle = target, - buttons = [0] + buttons = [0], } = options; const position = ref( (_a = toValue(initialValue)) != null ? _a : { x: 0, y: 0 } ); const pressedDelta = ref(); const filterEvent = (e) => { - if (pointerTypes) - return pointerTypes.includes(e.pointerType); + if (pointerTypes) return pointerTypes.includes(e.pointerType); return true; }; const handleEvent = (e) => { - if (toValue(preventDefault2)) - e.preventDefault(); - if (toValue(stopPropagation)) - e.stopPropagation(); + if (toValue(preventDefault2)) e.preventDefault(); + if (toValue(stopPropagation)) e.stopPropagation(); }; const start = (e) => { var _a2; - if (!toValue(buttons).includes(e.button)) - return; - if (toValue(options.disabled) || !filterEvent(e)) - return; - if (toValue(exact) && e.target !== toValue(target)) - return; + if (!toValue(buttons).includes(e.button)) return; + if (toValue(options.disabled) || !filterEvent(e)) return; + if (toValue(exact) && e.target !== toValue(target)) return; const container = toValue(containerElement); - const containerRect = (_a2 = container == null ? void 0 : container.getBoundingClientRect) == null ? void 0 : _a2.call(container); + const containerRect = + (_a2 = container == null ? void 0 : container.getBoundingClientRect) == + null + ? void 0 + : _a2.call(container); const targetRect = toValue(target).getBoundingClientRect(); const pos = { - x: e.clientX - (container ? targetRect.left - containerRect.left + container.scrollLeft : targetRect.left), - y: e.clientY - (container ? targetRect.top - containerRect.top + container.scrollTop : targetRect.top) + x: + e.clientX - + (container + ? targetRect.left - containerRect.left + container.scrollLeft + : targetRect.left), + y: + e.clientY - + (container + ? targetRect.top - containerRect.top + container.scrollTop + : targetRect.top), }; - if ((onStart == null ? void 0 : onStart(pos, e)) === false) - return; + if ((onStart == null ? void 0 : onStart(pos, e)) === false) return; pressedDelta.value = pos; handleEvent(e); }; const move = (e) => { - if (toValue(options.disabled) || !filterEvent(e)) - return; - if (!pressedDelta.value) - return; + if (toValue(options.disabled) || !filterEvent(e)) return; + if (!pressedDelta.value) return; const container = toValue(containerElement); const targetRect = toValue(target).getBoundingClientRect(); let { x, y } = position.value; - if (axis === "x" || axis === "both") { + if (axis === 'x' || axis === 'both') { x = e.clientX - pressedDelta.value.x; if (container) x = Math.min(Math.max(0, x), container.scrollWidth - targetRect.width); } - if (axis === "y" || axis === "both") { + if (axis === 'y' || axis === 'both') { y = e.clientY - pressedDelta.value.y; if (container) - y = Math.min(Math.max(0, y), container.scrollHeight - targetRect.height); + y = Math.min( + Math.max(0, y), + container.scrollHeight - targetRect.height + ); } position.value = { x, - y + y, }; onMove == null ? void 0 : onMove(position.value, e); handleEvent(e); }; const end = (e) => { - if (toValue(options.disabled) || !filterEvent(e)) - return; - if (!pressedDelta.value) - return; + if (toValue(options.disabled) || !filterEvent(e)) return; + if (!pressedDelta.value) return; pressedDelta.value = void 0; onEnd == null ? void 0 : onEnd(position.value, e); handleEvent(e); @@ -4275,12 +4752,12 @@ function useDraggable(target, options = {}) { var _a2; return { capture: (_a2 = options.capture) != null ? _a2 : true, - passive: !toValue(preventDefault2) + passive: !toValue(preventDefault2), }; }; - useEventListener(draggingHandle, "pointerdown", start, config); - useEventListener(draggingElement, "pointermove", move, config); - useEventListener(draggingElement, "pointerup", end, config); + useEventListener(draggingHandle, 'pointerdown', start, config); + useEventListener(draggingElement, 'pointermove', move, config); + useEventListener(draggingElement, 'pointerup', end, config); } return { ...toRefs2(position), @@ -4288,7 +4765,7 @@ function useDraggable(target, options = {}) { isDragging: computed(() => !!pressedDelta.value), style: computed( () => `left:${position.value.x}px;top:${position.value.y}px;` - ) + ), }; } function useDropZone(target, options = {}) { @@ -4298,90 +4775,117 @@ function useDropZone(target, options = {}) { let counter = 0; let isValid = true; if (isClient) { - const _options = typeof options === "function" ? { onDrop: options } : options; + const _options = + typeof options === 'function' ? { onDrop: options } : options; const multiple = (_a = _options.multiple) != null ? _a : true; - const preventDefaultForUnhandled = (_b = _options.preventDefaultForUnhandled) != null ? _b : false; + const preventDefaultForUnhandled = + (_b = _options.preventDefaultForUnhandled) != null ? _b : false; const getFiles = (event) => { var _a2, _b2; - const list = Array.from((_b2 = (_a2 = event.dataTransfer) == null ? void 0 : _a2.files) != null ? _b2 : []); + const list = Array.from( + (_b2 = (_a2 = event.dataTransfer) == null ? void 0 : _a2.files) != null + ? _b2 + : [] + ); return list.length === 0 ? null : multiple ? list : [list[0]]; }; const checkDataTypes = (types) => { const dataTypes = unref(_options.dataTypes); - if (typeof dataTypes === "function") - return dataTypes(types); - if (!(dataTypes == null ? void 0 : dataTypes.length)) - return true; - if (types.length === 0) - return false; - return types.every( - (type) => dataTypes.some((allowedType) => type.includes(allowedType)) + if (typeof dataTypes === 'function') return dataTypes(types); + if (!(dataTypes == null ? void 0 : dataTypes.length)) return true; + if (types.length === 0) return false; + return types.every((type) => + dataTypes.some((allowedType) => type.includes(allowedType)) ); }; const checkValidity = (items) => { - const types = Array.from(items != null ? items : []).map((item) => item.type); + const types = Array.from(items != null ? items : []).map( + (item) => item.type + ); const dataTypesValid = checkDataTypes(types); const multipleFilesValid = multiple || items.length <= 1; return dataTypesValid && multipleFilesValid; }; - const isSafari = () => /^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent) && !("chrome" in window); + const isSafari = () => + /^(?:(?!chrome|android).)*safari/i.test(navigator.userAgent) && + !('chrome' in window); const handleDragEvent = (event, eventType) => { var _a2, _b2, _c, _d, _e, _f; - const dataTransferItemList = (_a2 = event.dataTransfer) == null ? void 0 : _a2.items; - isValid = (_b2 = dataTransferItemList && checkValidity(dataTransferItemList)) != null ? _b2 : false; + const dataTransferItemList = + (_a2 = event.dataTransfer) == null ? void 0 : _a2.items; + isValid = + (_b2 = dataTransferItemList && checkValidity(dataTransferItemList)) != + null + ? _b2 + : false; if (preventDefaultForUnhandled) { event.preventDefault(); } if (!isSafari() && !isValid) { if (event.dataTransfer) { - event.dataTransfer.dropEffect = "none"; + event.dataTransfer.dropEffect = 'none'; } return; } event.preventDefault(); if (event.dataTransfer) { - event.dataTransfer.dropEffect = "copy"; + event.dataTransfer.dropEffect = 'copy'; } const currentFiles = getFiles(event); switch (eventType) { - case "enter": + case 'enter': counter += 1; isOverDropZone.value = true; - (_c = _options.onEnter) == null ? void 0 : _c.call(_options, null, event); + (_c = _options.onEnter) == null + ? void 0 + : _c.call(_options, null, event); break; - case "over": - (_d = _options.onOver) == null ? void 0 : _d.call(_options, null, event); + case 'over': + (_d = _options.onOver) == null + ? void 0 + : _d.call(_options, null, event); break; - case "leave": + case 'leave': counter -= 1; - if (counter === 0) - isOverDropZone.value = false; - (_e = _options.onLeave) == null ? void 0 : _e.call(_options, null, event); + if (counter === 0) isOverDropZone.value = false; + (_e = _options.onLeave) == null + ? void 0 + : _e.call(_options, null, event); break; - case "drop": + case 'drop': counter = 0; isOverDropZone.value = false; if (isValid) { files.value = currentFiles; - (_f = _options.onDrop) == null ? void 0 : _f.call(_options, currentFiles, event); + (_f = _options.onDrop) == null + ? void 0 + : _f.call(_options, currentFiles, event); } break; } }; - useEventListener(target, "dragenter", (event) => handleDragEvent(event, "enter")); - useEventListener(target, "dragover", (event) => handleDragEvent(event, "over")); - useEventListener(target, "dragleave", (event) => handleDragEvent(event, "leave")); - useEventListener(target, "drop", (event) => handleDragEvent(event, "drop")); + useEventListener(target, 'dragenter', (event) => + handleDragEvent(event, 'enter') + ); + useEventListener(target, 'dragover', (event) => + handleDragEvent(event, 'over') + ); + useEventListener(target, 'dragleave', (event) => + handleDragEvent(event, 'leave') + ); + useEventListener(target, 'drop', (event) => handleDragEvent(event, 'drop')); } return { files, - isOverDropZone + isOverDropZone, }; } function useResizeObserver(target, callback, options = {}) { const { window: window2 = defaultWindow, ...observerOptions } = options; let observer; - const isSupported = useSupported(() => window2 && "ResizeObserver" in window2); + const isSupported = useSupported( + () => window2 && 'ResizeObserver' in window2 + ); const cleanup = () => { if (observer) { observer.disconnect(); @@ -4390,7 +4894,9 @@ function useResizeObserver(target, callback, options = {}) { }; const targets = computed(() => { const _targets = toValue(target); - return Array.isArray(_targets) ? _targets.map((el) => unrefElement(el)) : [unrefElement(_targets)]; + return Array.isArray(_targets) + ? _targets.map((el) => unrefElement(el)) + : [unrefElement(_targets)]; }); const stopWatch = watch( targets, @@ -4399,12 +4905,11 @@ function useResizeObserver(target, callback, options = {}) { if (isSupported.value && window2) { observer = new ResizeObserver(callback); for (const _el of els) { - if (_el) - observer.observe(_el, observerOptions); + if (_el) observer.observe(_el, observerOptions); } } }, - { immediate: true, flush: "post" } + { immediate: true, flush: 'post' } ); const stop = () => { cleanup(); @@ -4413,7 +4918,7 @@ function useResizeObserver(target, callback, options = {}) { tryOnScopeDispose(stop); return { isSupported, - stop + stop, }; } function useElementBounding(target, options = {}) { @@ -4422,7 +4927,7 @@ function useElementBounding(target, options = {}) { windowResize = true, windowScroll = true, immediate = true, - updateTiming = "sync" + updateTiming = 'sync', } = options; const height = shallowRef(0); const bottom = shallowRef(0); @@ -4458,23 +4963,23 @@ function useElementBounding(target, options = {}) { y.value = rect.y; } function update() { - if (updateTiming === "sync") - recalculate(); - else if (updateTiming === "next-frame") + if (updateTiming === 'sync') recalculate(); + else if (updateTiming === 'next-frame') requestAnimationFrame(() => recalculate()); } useResizeObserver(target, update); - watch(() => unrefElement(target), (ele) => !ele && update()); + watch( + () => unrefElement(target), + (ele) => !ele && update() + ); useMutationObserver(target, update, { - attributeFilter: ["style", "class"] + attributeFilter: ['style', 'class'], }); if (windowScroll) - useEventListener("scroll", update, { capture: true, passive: true }); - if (windowResize) - useEventListener("resize", update, { passive: true }); + useEventListener('scroll', update, { capture: true, passive: true }); + if (windowResize) useEventListener('resize', update, { passive: true }); tryOnMounted(() => { - if (immediate) - update(); + if (immediate) update(); }); return { height, @@ -4485,7 +4990,7 @@ function useElementBounding(target, options = {}) { width, x, y, - update + update, }; } function useElementByPoint(options) { @@ -4494,24 +4999,38 @@ function useElementByPoint(options) { y, document: document2 = defaultDocument, multiple, - interval = "requestAnimationFrame", - immediate = true + interval = 'requestAnimationFrame', + immediate = true, } = options; const isSupported = useSupported(() => { - if (toValue(multiple)) - return document2 && "elementsFromPoint" in document2; - return document2 && "elementFromPoint" in document2; + if (toValue(multiple)) return document2 && 'elementsFromPoint' in document2; + return document2 && 'elementFromPoint' in document2; }); const element = shallowRef(null); const cb = () => { var _a, _b; - element.value = toValue(multiple) ? (_a = document2 == null ? void 0 : document2.elementsFromPoint(toValue(x), toValue(y))) != null ? _a : [] : (_b = document2 == null ? void 0 : document2.elementFromPoint(toValue(x), toValue(y))) != null ? _b : null; + element.value = toValue(multiple) + ? (_a = + document2 == null + ? void 0 + : document2.elementsFromPoint(toValue(x), toValue(y))) != null + ? _a + : [] + : (_b = + document2 == null + ? void 0 + : document2.elementFromPoint(toValue(x), toValue(y))) != null + ? _b + : null; }; - const controls = interval === "requestAnimationFrame" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate }); + const controls = + interval === 'requestAnimationFrame' + ? useRafFn(cb, { immediate }) + : useIntervalFn(cb, interval, { immediate }); return { isSupported, element, - ...controls + ...controls, }; } function useElementHover(el, options = {}) { @@ -4519,7 +5038,7 @@ function useElementHover(el, options = {}) { delayEnter = 0, delayLeave = 0, triggerOnRemoval = false, - window: window2 = defaultWindow + window: window2 = defaultWindow, } = options; const isHovered = shallowRef(false); let timer; @@ -4529,15 +5048,12 @@ function useElementHover(el, options = {}) { clearTimeout(timer); timer = void 0; } - if (delay) - timer = setTimeout(() => isHovered.value = entering, delay); - else - isHovered.value = entering; + if (delay) timer = setTimeout(() => (isHovered.value = entering), delay); + else isHovered.value = entering; }; - if (!window2) - return isHovered; - useEventListener(el, "mouseenter", () => toggle(true), { passive: true }); - useEventListener(el, "mouseleave", () => toggle(false), { passive: true }); + if (!window2) return isHovered; + useEventListener(el, 'mouseenter', () => toggle(true), { passive: true }); + useEventListener(el, 'mouseleave', () => toggle(false), { passive: true }); if (triggerOnRemoval) { onElementRemoval( computed(() => unrefElement(el)), @@ -4546,18 +5062,30 @@ function useElementHover(el, options = {}) { } return isHovered; } -function useElementSize(target, initialSize = { width: 0, height: 0 }, options = {}) { - const { window: window2 = defaultWindow, box = "content-box" } = options; +function useElementSize( + target, + initialSize = { width: 0, height: 0 }, + options = {} +) { + const { window: window2 = defaultWindow, box = 'content-box' } = options; const isSVG = computed(() => { var _a, _b; - return (_b = (_a = unrefElement(target)) == null ? void 0 : _a.namespaceURI) == null ? void 0 : _b.includes("svg"); + return (_b = + (_a = unrefElement(target)) == null ? void 0 : _a.namespaceURI) == null + ? void 0 + : _b.includes('svg'); }); const width = shallowRef(initialSize.width); const height = shallowRef(initialSize.height); const { stop: stop1 } = useResizeObserver( target, ([entry]) => { - const boxSize = box === "border-box" ? entry.borderBoxSize : box === "content-box" ? entry.contentBoxSize : entry.devicePixelContentBoxSize; + const boxSize = + box === 'border-box' + ? entry.borderBoxSize + : box === 'content-box' + ? entry.contentBoxSize + : entry.devicePixelContentBoxSize; if (window2 && isSVG.value) { const $elem = unrefElement(target); if ($elem) { @@ -4568,8 +5096,14 @@ function useElementSize(target, initialSize = { width: 0, height: 0 }, options = } else { if (boxSize) { const formatBoxSize = toArray(boxSize); - width.value = formatBoxSize.reduce((acc, { inlineSize }) => acc + inlineSize, 0); - height.value = formatBoxSize.reduce((acc, { blockSize }) => acc + blockSize, 0); + width.value = formatBoxSize.reduce( + (acc, { inlineSize }) => acc + inlineSize, + 0 + ); + height.value = formatBoxSize.reduce( + (acc, { blockSize }) => acc + blockSize, + 0 + ); } else { width.value = entry.contentRect.width; height.value = entry.contentRect.height; @@ -4581,8 +5115,9 @@ function useElementSize(target, initialSize = { width: 0, height: 0 }, options = tryOnMounted(() => { const ele = unrefElement(target); if (ele) { - width.value = "offsetWidth" in ele ? ele.offsetWidth : initialSize.width; - height.value = "offsetHeight" in ele ? ele.offsetHeight : initialSize.height; + width.value = 'offsetWidth' in ele ? ele.offsetWidth : initialSize.width; + height.value = + 'offsetHeight' in ele ? ele.offsetHeight : initialSize.height; } }); const stop2 = watch( @@ -4599,48 +5134,47 @@ function useElementSize(target, initialSize = { width: 0, height: 0 }, options = return { width, height, - stop + stop, }; } function useIntersectionObserver(target, callback, options = {}) { const { root, - rootMargin = "0px", + rootMargin = '0px', threshold = 0, window: window2 = defaultWindow, - immediate = true + immediate = true, } = options; - const isSupported = useSupported(() => window2 && "IntersectionObserver" in window2); + const isSupported = useSupported( + () => window2 && 'IntersectionObserver' in window2 + ); const targets = computed(() => { const _target = toValue(target); return toArray(_target).map(unrefElement).filter(notNullish); }); let cleanup = noop; const isActive = shallowRef(immediate); - const stopWatch = isSupported.value ? watch( - () => [targets.value, unrefElement(root), isActive.value], - ([targets2, root2]) => { - cleanup(); - if (!isActive.value) - return; - if (!targets2.length) - return; - const observer = new IntersectionObserver( - callback, - { - root: unrefElement(root2), - rootMargin, - threshold - } - ); - targets2.forEach((el) => el && observer.observe(el)); - cleanup = () => { - observer.disconnect(); - cleanup = noop; - }; - }, - { immediate, flush: "post" } - ) : noop; + const stopWatch = isSupported.value + ? watch( + () => [targets.value, unrefElement(root), isActive.value], + ([targets2, root2]) => { + cleanup(); + if (!isActive.value) return; + if (!targets2.length) return; + const observer = new IntersectionObserver(callback, { + root: unrefElement(root2), + rootMargin, + threshold, + }); + targets2.forEach((el) => el && observer.observe(el)); + cleanup = () => { + observer.disconnect(); + cleanup = noop; + }; + }, + { immediate, flush: 'post' } + ) + : noop; const stop = () => { cleanup(); stopWatch(); @@ -4657,7 +5191,7 @@ function useIntersectionObserver(target, callback, options = {}) { resume() { isActive.value = true; }, - stop + stop, }; } function useElementVisibility(element, options = {}) { @@ -4666,7 +5200,7 @@ function useElementVisibility(element, options = {}) { scrollTarget, threshold = 0, rootMargin, - once = false + once = false, } = options; const elementIsVisible = shallowRef(false); const { stop } = useIntersectionObserver( @@ -4691,7 +5225,7 @@ function useElementVisibility(element, options = {}) { root: scrollTarget, window: window2, threshold, - rootMargin: toValue(rootMargin) + rootMargin: toValue(rootMargin), } ); return elementIsVisible; @@ -4705,7 +5239,9 @@ function useEventBus(key) { listeners.add(listener); events.set(key, listeners); const _off = () => off(listener); - (_a = scope == null ? void 0 : scope.cleanups) == null ? void 0 : _a.push(_off); + (_a = scope == null ? void 0 : scope.cleanups) == null + ? void 0 + : _a.push(_off); return _off; } function once(listener) { @@ -4717,30 +5253,29 @@ function useEventBus(key) { } function off(listener) { const listeners = events.get(key); - if (!listeners) - return; + if (!listeners) return; listeners.delete(listener); - if (!listeners.size) - reset(); + if (!listeners.size) reset(); } function reset() { events.delete(key); } function emit(event, payload) { var _a; - (_a = events.get(key)) == null ? void 0 : _a.forEach((v) => v(event, payload)); + (_a = events.get(key)) == null + ? void 0 + : _a.forEach((v) => v(event, payload)); } return { on, once, off, emit, reset }; } function resolveNestedOptions$1(options) { - if (options === true) - return {}; + if (options === true) return {}; return options; } function useEventSource(url, events2 = [], options = {}) { const event = shallowRef(null); const data = shallowRef(null); - const status = shallowRef("CONNECTING"); + const status = shallowRef('CONNECTING'); const eventSource = ref(null); const error = shallowRef(null); const urlRef = toRef2(url); @@ -4751,43 +5286,41 @@ function useEventSource(url, events2 = [], options = {}) { withCredentials = false, immediate = true, autoConnect = true, - autoReconnect + autoReconnect, } = options; const close = () => { if (isClient && eventSource.value) { eventSource.value.close(); eventSource.value = null; - status.value = "CLOSED"; + status.value = 'CLOSED'; explicitlyClosed = true; } }; const _init = () => { - if (explicitlyClosed || typeof urlRef.value === "undefined") - return; + if (explicitlyClosed || typeof urlRef.value === 'undefined') return; const es = new EventSource(urlRef.value, { withCredentials }); - status.value = "CONNECTING"; + status.value = 'CONNECTING'; eventSource.value = es; es.onopen = () => { - status.value = "OPEN"; + status.value = 'OPEN'; error.value = null; }; es.onerror = (e) => { - status.value = "CLOSED"; + status.value = 'CLOSED'; error.value = e; if (es.readyState === 2 && !explicitlyClosed && autoReconnect) { es.close(); const { retries = -1, delay = 1e3, - onFailed + onFailed, } = resolveNestedOptions$1(autoReconnect); retried += 1; - if (typeof retries === "number" && (retries < 0 || retried < retries)) + if (typeof retries === 'number' && (retries < 0 || retried < retries)) setTimeout(_init, delay); - else if (typeof retries === "function" && retries()) + else if (typeof retries === 'function' && retries()) setTimeout(_init, delay); - else - onFailed == null ? void 0 : onFailed(); + else onFailed == null ? void 0 : onFailed(); } }; es.onmessage = (e) => { @@ -4796,24 +5329,26 @@ function useEventSource(url, events2 = [], options = {}) { lastEventId.value = e.lastEventId; }; for (const event_name of events2) { - useEventListener(es, event_name, (e) => { - event.value = event_name; - data.value = e.data || null; - }, { passive: true }); + useEventListener( + es, + event_name, + (e) => { + event.value = event_name; + data.value = e.data || null; + }, + { passive: true } + ); } }; const open = () => { - if (!isClient) - return; + if (!isClient) return; close(); explicitlyClosed = false; retried = 0; _init(); }; - if (immediate) - open(); - if (autoConnect) - watch(urlRef, open); + if (immediate) open(); + if (autoConnect) watch(urlRef, open); tryOnScopeDispose(close); return { eventSource, @@ -4823,16 +5358,17 @@ function useEventSource(url, events2 = [], options = {}) { error, open, close, - lastEventId + lastEventId, }; } function useEyeDropper(options = {}) { - const { initialValue = "" } = options; - const isSupported = useSupported(() => typeof window !== "undefined" && "EyeDropper" in window); + const { initialValue = '' } = options; + const isSupported = useSupported( + () => typeof window !== 'undefined' && 'EyeDropper' in window + ); const sRGBHex = shallowRef(initialValue); async function open(openOptions) { - if (!isSupported.value) - return; + if (!isSupported.value) return; const eyeDropper = new window.EyeDropper(); const result = await eyeDropper.open(openOptions); sRGBHex.value = result.sRGBHex; @@ -4842,53 +5378,71 @@ function useEyeDropper(options = {}) { } function useFavicon(newIcon = null, options = {}) { const { - baseUrl = "", - rel = "icon", - document: document2 = defaultDocument + baseUrl = '', + rel = 'icon', + document: document2 = defaultDocument, } = options; const favicon = toRef2(newIcon); const applyIcon = (icon) => { - const elements = document2 == null ? void 0 : document2.head.querySelectorAll(`link[rel*="${rel}"]`); + const elements = + document2 == null + ? void 0 + : document2.head.querySelectorAll(`link[rel*="${rel}"]`); if (!elements || elements.length === 0) { - const link = document2 == null ? void 0 : document2.createElement("link"); + const link = document2 == null ? void 0 : document2.createElement('link'); if (link) { link.rel = rel; link.href = `${baseUrl}${icon}`; - link.type = `image/${icon.split(".").pop()}`; + link.type = `image/${icon.split('.').pop()}`; document2 == null ? void 0 : document2.head.append(link); } return; } - elements == null ? void 0 : elements.forEach((el) => el.href = `${baseUrl}${icon}`); + elements == null + ? void 0 + : elements.forEach((el) => (el.href = `${baseUrl}${icon}`)); }; watch( favicon, (i, o) => { - if (typeof i === "string" && i !== o) - applyIcon(i); + if (typeof i === 'string' && i !== o) applyIcon(i); }, { immediate: true } ); return favicon; } var payloadMapping = { - json: "application/json", - text: "text/plain" + json: 'application/json', + text: 'text/plain', }; function isFetchOptions(obj) { - return obj && containsProp(obj, "immediate", "refetch", "initialData", "timeout", "beforeFetch", "afterFetch", "onFetchError", "fetch", "updateDataOnError"); + return ( + obj && + containsProp( + obj, + 'immediate', + 'refetch', + 'initialData', + 'timeout', + 'beforeFetch', + 'afterFetch', + 'onFetchError', + 'fetch', + 'updateDataOnError' + ) + ); } var reAbsolute = /^(?:[a-z][a-z\d+\-.]*:)?\/\//i; function isAbsoluteURL(url) { return reAbsolute.test(url); } function headersToObject(headers) { - if (typeof Headers !== "undefined" && headers instanceof Headers) + if (typeof Headers !== 'undefined' && headers instanceof Headers) return Object.fromEntries(headers.entries()); return headers; } function combineCallbacks(combination, ...callbacks) { - if (combination === "overwrite") { + if (combination === 'overwrite') { return async (ctx) => { let callback; for (let i = callbacks.length - 1; i >= 0; i--) { @@ -4897,29 +5451,29 @@ function combineCallbacks(combination, ...callbacks) { break; } } - if (callback) - return { ...ctx, ...await callback(ctx) }; + if (callback) return { ...ctx, ...(await callback(ctx)) }; return ctx; }; } else { return async (ctx) => { for (const callback of callbacks) { - if (callback) - ctx = { ...ctx, ...await callback(ctx) }; + if (callback) ctx = { ...ctx, ...(await callback(ctx)) }; } return ctx; }; } } function createFetch(config = {}) { - const _combination = config.combination || "chain"; + const _combination = config.combination || 'chain'; const _options = config.options || {}; const _fetchOptions = config.fetchOptions || {}; function useFactoryFetch(url, ...args) { const computedUrl = computed(() => { const baseUrl = toValue(config.baseUrl); const targetUrl = toValue(url); - return baseUrl && !isAbsoluteURL(targetUrl) ? joinPaths(baseUrl, targetUrl) : targetUrl; + return baseUrl && !isAbsoluteURL(targetUrl) + ? joinPaths(baseUrl, targetUrl) + : targetUrl; }); let options = _options; let fetchOptions = _fetchOptions; @@ -4928,18 +5482,30 @@ function createFetch(config = {}) { options = { ...options, ...args[0], - beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[0].beforeFetch), - afterFetch: combineCallbacks(_combination, _options.afterFetch, args[0].afterFetch), - onFetchError: combineCallbacks(_combination, _options.onFetchError, args[0].onFetchError) + beforeFetch: combineCallbacks( + _combination, + _options.beforeFetch, + args[0].beforeFetch + ), + afterFetch: combineCallbacks( + _combination, + _options.afterFetch, + args[0].afterFetch + ), + onFetchError: combineCallbacks( + _combination, + _options.onFetchError, + args[0].onFetchError + ), }; } else { fetchOptions = { ...fetchOptions, ...args[0], headers: { - ...headersToObject(fetchOptions.headers) || {}, - ...headersToObject(args[0].headers) || {} - } + ...(headersToObject(fetchOptions.headers) || {}), + ...(headersToObject(args[0].headers) || {}), + }, }; } } @@ -4947,9 +5513,21 @@ function createFetch(config = {}) { options = { ...options, ...args[1], - beforeFetch: combineCallbacks(_combination, _options.beforeFetch, args[1].beforeFetch), - afterFetch: combineCallbacks(_combination, _options.afterFetch, args[1].afterFetch), - onFetchError: combineCallbacks(_combination, _options.onFetchError, args[1].onFetchError) + beforeFetch: combineCallbacks( + _combination, + _options.beforeFetch, + args[1].beforeFetch + ), + afterFetch: combineCallbacks( + _combination, + _options.afterFetch, + args[1].afterFetch + ), + onFetchError: combineCallbacks( + _combination, + _options.onFetchError, + args[1].onFetchError + ), }; } return useFetch(computedUrl, fetchOptions, options); @@ -4958,33 +5536,30 @@ function createFetch(config = {}) { } function useFetch(url, ...args) { var _a; - const supportsAbort = typeof AbortController === "function"; + const supportsAbort = typeof AbortController === 'function'; let fetchOptions = {}; let options = { immediate: true, refetch: false, timeout: 0, - updateDataOnError: false + updateDataOnError: false, }; const config = { - method: "GET", - type: "text", - payload: void 0 + method: 'GET', + type: 'text', + payload: void 0, }; if (args.length > 0) { - if (isFetchOptions(args[0])) - options = { ...options, ...args[0] }; - else - fetchOptions = args[0]; + if (isFetchOptions(args[0])) options = { ...options, ...args[0] }; + else fetchOptions = args[0]; } if (args.length > 1) { - if (isFetchOptions(args[1])) - options = { ...options, ...args[1] }; + if (isFetchOptions(args[1])) options = { ...options, ...args[1] }; } const { fetch = (_a = defaultWindow) == null ? void 0 : _a.fetch, initialData, - timeout + timeout, } = options; const responseEvent = createEventHook(); const errorEvent = createEventHook(); @@ -5003,10 +5578,10 @@ function useFetch(url, ...args) { if (supportsAbort) { controller == null ? void 0 : controller.abort(); controller = new AbortController(); - controller.signal.onabort = () => aborted.value = true; + controller.signal.onabort = () => (aborted.value = true); fetchOptions = { ...fetchOptions, - signal: controller.signal + signal: controller.signal, }; } }; @@ -5014,8 +5589,7 @@ function useFetch(url, ...args) { isFetching.value = isLoading; isFinished.value = !isLoading; }; - if (timeout) - timer = useTimeoutFn(abort, timeout, { immediate: false }); + if (timeout) timer = useTimeoutFn(abort, timeout, { immediate: false }); let executeCounter = 0; const execute = async (throwOnFailed = false) => { var _a2, _b; @@ -5028,28 +5602,37 @@ function useFetch(url, ...args) { const currentExecuteCounter = executeCounter; const defaultFetchOptions = { method: config.method, - headers: {} + headers: {}, }; const payload = toValue(config.payload); if (payload) { const headers = headersToObject(defaultFetchOptions.headers); const proto = Object.getPrototypeOf(payload); - if (!config.payloadType && payload && (proto === Object.prototype || Array.isArray(proto)) && !(payload instanceof FormData)) - config.payloadType = "json"; + if ( + !config.payloadType && + payload && + (proto === Object.prototype || Array.isArray(proto)) && + !(payload instanceof FormData) + ) + config.payloadType = 'json'; if (config.payloadType) - headers["Content-Type"] = (_a2 = payloadMapping[config.payloadType]) != null ? _a2 : config.payloadType; - defaultFetchOptions.body = config.payloadType === "json" ? JSON.stringify(payload) : payload; + headers['Content-Type'] = + (_a2 = payloadMapping[config.payloadType]) != null + ? _a2 + : config.payloadType; + defaultFetchOptions.body = + config.payloadType === 'json' ? JSON.stringify(payload) : payload; } let isCanceled = false; const context = { url: toValue(url), options: { ...defaultFetchOptions, - ...fetchOptions + ...fetchOptions, }, cancel: () => { isCanceled = true; - } + }, }; if (options.beforeFetch) Object.assign(context, await options.beforeFetch(context)); @@ -5058,72 +5641,65 @@ function useFetch(url, ...args) { return Promise.resolve(null); } let responseData = null; - if (timer) - timer.start(); - return fetch( - context.url, - { - ...defaultFetchOptions, - ...context.options, - headers: { - ...headersToObject(defaultFetchOptions.headers), - ...headersToObject((_b = context.options) == null ? void 0 : _b.headers) + if (timer) timer.start(); + return fetch(context.url, { + ...defaultFetchOptions, + ...context.options, + headers: { + ...headersToObject(defaultFetchOptions.headers), + ...headersToObject( + (_b = context.options) == null ? void 0 : _b.headers + ), + }, + }) + .then(async (fetchResponse) => { + response.value = fetchResponse; + statusCode.value = fetchResponse.status; + responseData = await fetchResponse.clone()[config.type](); + if (!fetchResponse.ok) { + data.value = initialData || null; + throw new Error(fetchResponse.statusText); + } + if (options.afterFetch) { + ({ data: responseData } = await options.afterFetch({ + data: responseData, + response: fetchResponse, + context, + execute, + })); } - } - ).then(async (fetchResponse) => { - response.value = fetchResponse; - statusCode.value = fetchResponse.status; - responseData = await fetchResponse.clone()[config.type](); - if (!fetchResponse.ok) { - data.value = initialData || null; - throw new Error(fetchResponse.statusText); - } - if (options.afterFetch) { - ({ data: responseData } = await options.afterFetch({ - data: responseData, - response: fetchResponse, - context, - execute - })); - } - data.value = responseData; - responseEvent.trigger(fetchResponse); - return fetchResponse; - }).catch(async (fetchError) => { - let errorData = fetchError.message || fetchError.name; - if (options.onFetchError) { - ({ error: errorData, data: responseData } = await options.onFetchError({ - data: responseData, - error: fetchError, - response: response.value, - context, - execute - })); - } - error.value = errorData; - if (options.updateDataOnError) data.value = responseData; - errorEvent.trigger(fetchError); - if (throwOnFailed) - throw fetchError; - return null; - }).finally(() => { - if (currentExecuteCounter === executeCounter) - loading(false); - if (timer) - timer.stop(); - finallyEvent.trigger(null); - }); + responseEvent.trigger(fetchResponse); + return fetchResponse; + }) + .catch(async (fetchError) => { + let errorData = fetchError.message || fetchError.name; + if (options.onFetchError) { + ({ error: errorData, data: responseData } = + await options.onFetchError({ + data: responseData, + error: fetchError, + response: response.value, + context, + execute, + })); + } + error.value = errorData; + if (options.updateDataOnError) data.value = responseData; + errorEvent.trigger(fetchError); + if (throwOnFailed) throw fetchError; + return null; + }) + .finally(() => { + if (currentExecuteCounter === executeCounter) loading(false); + if (timer) timer.stop(); + finallyEvent.trigger(null); + }); }; const refetch = toRef2(options.refetch); - watch( - [ - refetch, - toRef2(url) - ], - ([refetch2]) => refetch2 && execute(), - { deep: true } - ); + watch([refetch, toRef2(url)], ([refetch2]) => refetch2 && execute(), { + deep: true, + }); const shell = { isFinished: readonly(isFinished), isFetching: readonly(isFetching), @@ -5139,19 +5715,19 @@ function useFetch(url, ...args) { onFetchError: errorEvent.on, onFetchFinally: finallyEvent.on, // method - get: setMethod("GET"), - put: setMethod("PUT"), - post: setMethod("POST"), - delete: setMethod("DELETE"), - patch: setMethod("PATCH"), - head: setMethod("HEAD"), - options: setMethod("OPTIONS"), + get: setMethod('GET'), + put: setMethod('PUT'), + post: setMethod('POST'), + delete: setMethod('DELETE'), + patch: setMethod('PATCH'), + head: setMethod('HEAD'), + options: setMethod('OPTIONS'), // type - json: setType("json"), - text: setType("text"), - blob: setType("blob"), - arrayBuffer: setType("arrayBuffer"), - formData: setType("formData") + json: setType('json'), + text: setType('text'), + blob: setType('blob'), + arrayBuffer: setType('arrayBuffer'), + formData: setType('formData'), }; function setMethod(method) { return (payload, payloadType) => { @@ -5161,10 +5737,7 @@ function useFetch(url, ...args) { config.payloadType = payloadType; if (isRef(config.payload)) { watch( - [ - refetch, - toRef2(config.payload) - ], + [refetch, toRef2(config.payload)], ([refetch2]) => refetch2 && execute(), { deep: true } ); @@ -5173,7 +5746,7 @@ function useFetch(url, ...args) { ...shell, then(onFulfilled, onRejected) { return waitUntilFinished().then(onFulfilled, onRejected); - } + }, }; } return void 0; @@ -5181,7 +5754,10 @@ function useFetch(url, ...args) { } function waitUntilFinished() { return new Promise((resolve, reject) => { - until(isFinished).toBe(true).then(() => resolve(shell)).catch(reject); + until(isFinished) + .toBe(true) + .then(() => resolve(shell)) + .catch(reject); }); } function setType(type) { @@ -5192,41 +5768,38 @@ function useFetch(url, ...args) { ...shell, then(onFulfilled, onRejected) { return waitUntilFinished().then(onFulfilled, onRejected); - } + }, }; } return void 0; }; } - if (options.immediate) - Promise.resolve().then(() => execute()); + if (options.immediate) Promise.resolve().then(() => execute()); return { ...shell, then(onFulfilled, onRejected) { return waitUntilFinished().then(onFulfilled, onRejected); - } + }, }; } function joinPaths(start, end) { - if (!start.endsWith("/") && !end.startsWith("/")) { + if (!start.endsWith('/') && !end.startsWith('/')) { return `${start}/${end}`; } - if (start.endsWith("/") && end.startsWith("/")) { + if (start.endsWith('/') && end.startsWith('/')) { return `${start.slice(0, -1)}${end}`; } return `${start}${end}`; } var DEFAULT_OPTIONS = { multiple: true, - accept: "*", + accept: '*', reset: false, - directory: false + directory: false, }; function prepareInitialFiles(files) { - if (!files) - return null; - if (files instanceof FileList) - return files; + if (!files) return null; + if (files instanceof FileList) return files; const dt = new DataTransfer(); for (const file of files) { dt.items.add(file); @@ -5234,16 +5807,14 @@ function prepareInitialFiles(files) { return dt.files; } function useFileDialog(options = {}) { - const { - document: document2 = defaultDocument - } = options; + const { document: document2 = defaultDocument } = options; const files = ref(prepareInitialFiles(options.initialFiles)); const { on: onChange, trigger: changeTrigger } = createEventHook(); const { on: onCancel, trigger: cancelTrigger } = createEventHook(); let input; if (document2) { - input = document2.createElement("input"); - input.type = "file"; + input = document2.createElement('input'); + input.type = 'file'; input.onchange = (event) => { const result = event.target; files.value = result.files; @@ -5256,25 +5827,22 @@ function useFileDialog(options = {}) { const reset = () => { files.value = null; if (input && input.value) { - input.value = ""; + input.value = ''; changeTrigger(null); } }; const open = (localOptions) => { - if (!input) - return; + if (!input) return; const _options = { ...DEFAULT_OPTIONS, ...options, - ...localOptions + ...localOptions, }; input.multiple = _options.multiple; input.accept = _options.accept; input.webkitdirectory = _options.directory; - if (hasOwn(_options, "capture")) - input.capture = _options.capture; - if (_options.reset) - reset(); + if (hasOwn(_options, 'capture')) input.capture = _options.capture; + if (_options.reset) reset(); input.click(); }; return { @@ -5282,26 +5850,32 @@ function useFileDialog(options = {}) { open, reset, onCancel, - onChange + onChange, }; } function useFileSystemAccess(options = {}) { - const { - window: _window = defaultWindow, - dataType = "Text" - } = options; + const { window: _window = defaultWindow, dataType = 'Text' } = options; const window2 = _window; - const isSupported = useSupported(() => window2 && "showSaveFilePicker" in window2 && "showOpenFilePicker" in window2); + const isSupported = useSupported( + () => + window2 && + 'showSaveFilePicker' in window2 && + 'showOpenFilePicker' in window2 + ); const fileHandle = shallowRef(); const data = shallowRef(); const file = shallowRef(); const fileName = computed(() => { var _a, _b; - return (_b = (_a = file.value) == null ? void 0 : _a.name) != null ? _b : ""; + return (_b = (_a = file.value) == null ? void 0 : _a.name) != null + ? _b + : ''; }); const fileMIME = computed(() => { var _a, _b; - return (_b = (_a = file.value) == null ? void 0 : _a.type) != null ? _b : ""; + return (_b = (_a = file.value) == null ? void 0 : _a.type) != null + ? _b + : ''; }); const fileSize = computed(() => { var _a, _b; @@ -5309,27 +5883,31 @@ function useFileSystemAccess(options = {}) { }); const fileLastModified = computed(() => { var _a, _b; - return (_b = (_a = file.value) == null ? void 0 : _a.lastModified) != null ? _b : 0; + return (_b = (_a = file.value) == null ? void 0 : _a.lastModified) != null + ? _b + : 0; }); async function open(_options = {}) { - if (!isSupported.value) - return; - const [handle] = await window2.showOpenFilePicker({ ...toValue(options), ..._options }); + if (!isSupported.value) return; + const [handle] = await window2.showOpenFilePicker({ + ...toValue(options), + ..._options, + }); fileHandle.value = handle; await updateData(); } async function create(_options = {}) { - if (!isSupported.value) - return; - fileHandle.value = await window2.showSaveFilePicker({ ...options, ..._options }); + if (!isSupported.value) return; + fileHandle.value = await window2.showSaveFilePicker({ + ...options, + ..._options, + }); data.value = void 0; await updateData(); } async function save(_options = {}) { - if (!isSupported.value) - return; - if (!fileHandle.value) - return saveAs(_options); + if (!isSupported.value) return; + if (!fileHandle.value) return saveAs(_options); if (data.value) { const writableStream = await fileHandle.value.createWritable(); await writableStream.write(data.value); @@ -5338,9 +5916,11 @@ function useFileSystemAccess(options = {}) { await updateFile(); } async function saveAs(_options = {}) { - if (!isSupported.value) - return; - fileHandle.value = await window2.showSaveFilePicker({ ...options, ..._options }); + if (!isSupported.value) return; + fileHandle.value = await window2.showSaveFilePicker({ + ...options, + ..._options, + }); if (data.value) { const writableStream = await fileHandle.value.createWritable(); await writableStream.write(data.value); @@ -5350,18 +5930,21 @@ function useFileSystemAccess(options = {}) { } async function updateFile() { var _a; - file.value = await ((_a = fileHandle.value) == null ? void 0 : _a.getFile()); + file.value = await ((_a = fileHandle.value) == null + ? void 0 + : _a.getFile()); } async function updateData() { var _a, _b; await updateFile(); const type = toValue(dataType); - if (type === "Text") + if (type === 'Text') data.value = await ((_a = file.value) == null ? void 0 : _a.text()); - else if (type === "ArrayBuffer") - data.value = await ((_b = file.value) == null ? void 0 : _b.arrayBuffer()); - else if (type === "Blob") - data.value = file.value; + else if (type === 'ArrayBuffer') + data.value = await ((_b = file.value) == null + ? void 0 + : _b.arrayBuffer()); + else if (type === 'Blob') data.value = file.value; } watch(() => toValue(dataType), updateData); return { @@ -5376,20 +5959,39 @@ function useFileSystemAccess(options = {}) { create, save, saveAs, - updateData + updateData, }; } function useFocus(target, options = {}) { - const { initialValue = false, focusVisible = false, preventScroll = false } = options; + const { + initialValue = false, + focusVisible = false, + preventScroll = false, + } = options; const innerFocused = shallowRef(false); const targetElement = computed(() => unrefElement(target)); const listenerOptions = { passive: true }; - useEventListener(targetElement, "focus", (event) => { - var _a, _b; - if (!focusVisible || ((_b = (_a = event.target).matches) == null ? void 0 : _b.call(_a, ":focus-visible"))) - innerFocused.value = true; - }, listenerOptions); - useEventListener(targetElement, "blur", () => innerFocused.value = false, listenerOptions); + useEventListener( + targetElement, + 'focus', + (event) => { + var _a, _b; + if ( + !focusVisible || + ((_b = (_a = event.target).matches) == null + ? void 0 + : _b.call(_a, ':focus-visible')) + ) + innerFocused.value = true; + }, + listenerOptions + ); + useEventListener( + targetElement, + 'blur', + () => (innerFocused.value = false), + listenerOptions + ); const focused = computed({ get: () => innerFocused.value, set(value) { @@ -5397,21 +5999,23 @@ function useFocus(target, options = {}) { if (!value && innerFocused.value) (_a = targetElement.value) == null ? void 0 : _a.blur(); else if (value && !innerFocused.value) - (_b = targetElement.value) == null ? void 0 : _b.focus({ preventScroll }); - } + (_b = targetElement.value) == null + ? void 0 + : _b.focus({ preventScroll }); + }, }); watch( targetElement, () => { focused.value = initialValue; }, - { immediate: true, flush: "post" } + { immediate: true, flush: 'post' } ); return { focused }; } -var EVENT_FOCUS_IN = "focusin"; -var EVENT_FOCUS_OUT = "focusout"; -var PSEUDO_CLASS_FOCUS_WITHIN = ":focus-within"; +var EVENT_FOCUS_IN = 'focusin'; +var EVENT_FOCUS_OUT = 'focusout'; +var PSEUDO_CLASS_FOCUS_WITHIN = ':focus-within'; function useFocusWithin(target, options = {}) { const { window: window2 = defaultWindow } = options; const targetElement = computed(() => unrefElement(target)); @@ -5422,19 +6026,36 @@ function useFocusWithin(target, options = {}) { return { focused }; } const listenerOptions = { passive: true }; - useEventListener(targetElement, EVENT_FOCUS_IN, () => _focused.value = true, listenerOptions); - useEventListener(targetElement, EVENT_FOCUS_OUT, () => { - var _a, _b, _c; - return _focused.value = (_c = (_b = (_a = targetElement.value) == null ? void 0 : _a.matches) == null ? void 0 : _b.call(_a, PSEUDO_CLASS_FOCUS_WITHIN)) != null ? _c : false; - }, listenerOptions); + useEventListener( + targetElement, + EVENT_FOCUS_IN, + () => (_focused.value = true), + listenerOptions + ); + useEventListener( + targetElement, + EVENT_FOCUS_OUT, + () => { + var _a, _b, _c; + return (_focused.value = + (_c = + (_b = (_a = targetElement.value) == null ? void 0 : _a.matches) == + null + ? void 0 + : _b.call(_a, PSEUDO_CLASS_FOCUS_WITHIN)) != null + ? _c + : false); + }, + listenerOptions + ); return { focused }; } function useFps(options) { var _a; const fps = shallowRef(0); - if (typeof performance === "undefined") - return fps; - const every = (_a = options == null ? void 0 : options.every) != null ? _a : 10; + if (typeof performance === 'undefined') return fps; + const every = + (_a = options == null ? void 0 : options.every) != null ? _a : 10; let last = performance.now(); let ticks = 0; useRafFn(() => { @@ -5450,62 +6071,85 @@ function useFps(options) { return fps; } var eventHandlers = [ - "fullscreenchange", - "webkitfullscreenchange", - "webkitendfullscreen", - "mozfullscreenchange", - "MSFullscreenChange" + 'fullscreenchange', + 'webkitfullscreenchange', + 'webkitendfullscreen', + 'mozfullscreenchange', + 'MSFullscreenChange', ]; function useFullscreen(target, options = {}) { - const { - document: document2 = defaultDocument, - autoExit = false - } = options; + const { document: document2 = defaultDocument, autoExit = false } = options; const targetRef = computed(() => { var _a; - return (_a = unrefElement(target)) != null ? _a : document2 == null ? void 0 : document2.documentElement; + return (_a = unrefElement(target)) != null + ? _a + : document2 == null + ? void 0 + : document2.documentElement; }); const isFullscreen = shallowRef(false); const requestMethod = computed(() => { return [ - "requestFullscreen", - "webkitRequestFullscreen", - "webkitEnterFullscreen", - "webkitEnterFullScreen", - "webkitRequestFullScreen", - "mozRequestFullScreen", - "msRequestFullscreen" - ].find((m) => document2 && m in document2 || targetRef.value && m in targetRef.value); + 'requestFullscreen', + 'webkitRequestFullscreen', + 'webkitEnterFullscreen', + 'webkitEnterFullScreen', + 'webkitRequestFullScreen', + 'mozRequestFullScreen', + 'msRequestFullscreen', + ].find( + (m) => + (document2 && m in document2) || + (targetRef.value && m in targetRef.value) + ); }); const exitMethod = computed(() => { return [ - "exitFullscreen", - "webkitExitFullscreen", - "webkitExitFullScreen", - "webkitCancelFullScreen", - "mozCancelFullScreen", - "msExitFullscreen" - ].find((m) => document2 && m in document2 || targetRef.value && m in targetRef.value); + 'exitFullscreen', + 'webkitExitFullscreen', + 'webkitExitFullScreen', + 'webkitCancelFullScreen', + 'mozCancelFullScreen', + 'msExitFullscreen', + ].find( + (m) => + (document2 && m in document2) || + (targetRef.value && m in targetRef.value) + ); }); const fullscreenEnabled = computed(() => { return [ - "fullScreen", - "webkitIsFullScreen", - "webkitDisplayingFullscreen", - "mozFullScreen", - "msFullscreenElement" - ].find((m) => document2 && m in document2 || targetRef.value && m in targetRef.value); + 'fullScreen', + 'webkitIsFullScreen', + 'webkitDisplayingFullscreen', + 'mozFullScreen', + 'msFullscreenElement', + ].find( + (m) => + (document2 && m in document2) || + (targetRef.value && m in targetRef.value) + ); }); const fullscreenElementMethod = [ - "fullscreenElement", - "webkitFullscreenElement", - "mozFullScreenElement", - "msFullscreenElement" + 'fullscreenElement', + 'webkitFullscreenElement', + 'mozFullScreenElement', + 'msFullscreenElement', ].find((m) => document2 && m in document2); - const isSupported = useSupported(() => targetRef.value && document2 && requestMethod.value !== void 0 && exitMethod.value !== void 0 && fullscreenEnabled.value !== void 0); + const isSupported = useSupported( + () => + targetRef.value && + document2 && + requestMethod.value !== void 0 && + exitMethod.value !== void 0 && + fullscreenEnabled.value !== void 0 + ); const isCurrentElementFullScreen = () => { if (fullscreenElementMethod) - return (document2 == null ? void 0 : document2[fullscreenElementMethod]) === targetRef.value; + return ( + (document2 == null ? void 0 : document2[fullscreenElementMethod]) === + targetRef.value + ); return false; }; const isElementFullScreen = () => { @@ -5514,7 +6158,9 @@ function useFullscreen(target, options = {}) { return document2[fullscreenEnabled.value]; } else { const target2 = targetRef.value; - if ((target2 == null ? void 0 : target2[fullscreenEnabled.value]) != null) { + if ( + (target2 == null ? void 0 : target2[fullscreenEnabled.value]) != null + ) { return Boolean(target2[fullscreenEnabled.value]); } } @@ -5522,8 +6168,7 @@ function useFullscreen(target, options = {}) { return false; }; async function exit() { - if (!isSupported.value || !isFullscreen.value) - return; + if (!isSupported.value || !isFullscreen.value) return; if (exitMethod.value) { if ((document2 == null ? void 0 : document2[exitMethod.value]) != null) { await document2[exitMethod.value](); @@ -5536,12 +6181,13 @@ function useFullscreen(target, options = {}) { isFullscreen.value = false; } async function enter() { - if (!isSupported.value || isFullscreen.value) - return; - if (isElementFullScreen()) - await exit(); + if (!isSupported.value || isFullscreen.value) return; + if (isElementFullScreen()) await exit(); const target2 = targetRef.value; - if (requestMethod.value && (target2 == null ? void 0 : target2[requestMethod.value]) != null) { + if ( + requestMethod.value && + (target2 == null ? void 0 : target2[requestMethod.value]) != null + ) { await target2[requestMethod.value](); isFullscreen.value = true; } @@ -5551,20 +6197,27 @@ function useFullscreen(target, options = {}) { } const handlerCallback = () => { const isElementFullScreenValue = isElementFullScreen(); - if (!isElementFullScreenValue || isElementFullScreenValue && isCurrentElementFullScreen()) + if ( + !isElementFullScreenValue || + (isElementFullScreenValue && isCurrentElementFullScreen()) + ) isFullscreen.value = isElementFullScreenValue; }; const listenerOptions = { capture: false, passive: true }; useEventListener(document2, eventHandlers, handlerCallback, listenerOptions); - useEventListener(() => unrefElement(targetRef), eventHandlers, handlerCallback, listenerOptions); - if (autoExit) - tryOnScopeDispose(exit); + useEventListener( + () => unrefElement(targetRef), + eventHandlers, + handlerCallback, + listenerOptions + ); + if (autoExit) tryOnScopeDispose(exit); return { isSupported, isFullscreen, enter, exit, - toggle + toggle, }; } function mapGamepadToXbox360Controller(gamepad) { @@ -5575,54 +6228,54 @@ function mapGamepadToXbox360Controller(gamepad) { a: gamepad.value.buttons[0], b: gamepad.value.buttons[1], x: gamepad.value.buttons[2], - y: gamepad.value.buttons[3] + y: gamepad.value.buttons[3], }, bumper: { left: gamepad.value.buttons[4], - right: gamepad.value.buttons[5] + right: gamepad.value.buttons[5], }, triggers: { left: gamepad.value.buttons[6], - right: gamepad.value.buttons[7] + right: gamepad.value.buttons[7], }, stick: { left: { horizontal: gamepad.value.axes[0], vertical: gamepad.value.axes[1], - button: gamepad.value.buttons[10] + button: gamepad.value.buttons[10], }, right: { horizontal: gamepad.value.axes[2], vertical: gamepad.value.axes[3], - button: gamepad.value.buttons[11] - } + button: gamepad.value.buttons[11], + }, }, dpad: { up: gamepad.value.buttons[12], down: gamepad.value.buttons[13], left: gamepad.value.buttons[14], - right: gamepad.value.buttons[15] + right: gamepad.value.buttons[15], }, back: gamepad.value.buttons[8], - start: gamepad.value.buttons[9] + start: gamepad.value.buttons[9], }; } return null; }); } function useGamepad(options = {}) { - const { - navigator: navigator2 = defaultNavigator - } = options; - const isSupported = useSupported(() => navigator2 && "getGamepads" in navigator2); + const { navigator: navigator2 = defaultNavigator } = options; + const isSupported = useSupported( + () => navigator2 && 'getGamepads' in navigator2 + ); const gamepads = ref([]); const onConnectedHook = createEventHook(); const onDisconnectedHook = createEventHook(); const stateFromGamepad = (gamepad) => { const hapticActuators = []; - const vibrationActuator = "vibrationActuator" in gamepad ? gamepad.vibrationActuator : null; - if (vibrationActuator) - hapticActuators.push(vibrationActuator); + const vibrationActuator = + 'vibrationActuator' in gamepad ? gamepad.vibrationActuator : null; + if (vibrationActuator) hapticActuators.push(vibrationActuator); if (gamepad.hapticActuators) hapticActuators.push(...gamepad.hapticActuators); return { @@ -5634,11 +6287,16 @@ function useGamepad(options = {}) { vibrationActuator: gamepad.vibrationActuator, hapticActuators, axes: gamepad.axes.map((axes) => axes), - buttons: gamepad.buttons.map((button) => ({ pressed: button.pressed, touched: button.touched, value: button.value })) + buttons: gamepad.buttons.map((button) => ({ + pressed: button.pressed, + touched: button.touched, + value: button.value, + })), }; }; const updateGamepadState = () => { - const _gamepads = (navigator2 == null ? void 0 : navigator2.getGamepads()) || []; + const _gamepads = + (navigator2 == null ? void 0 : navigator2.getGamepads()) || []; for (const gamepad of _gamepads) { if (gamepad && gamepads.value[gamepad.index]) gamepads.value[gamepad.index] = stateFromGamepad(gamepad); @@ -5657,13 +6315,21 @@ function useGamepad(options = {}) { onDisconnectedHook.trigger(gamepad.index); }; const listenerOptions = { passive: true }; - useEventListener("gamepadconnected", (e) => onGamepadConnected(e.gamepad), listenerOptions); - useEventListener("gamepaddisconnected", (e) => onGamepadDisconnected(e.gamepad), listenerOptions); + useEventListener( + 'gamepadconnected', + (e) => onGamepadConnected(e.gamepad), + listenerOptions + ); + useEventListener( + 'gamepaddisconnected', + (e) => onGamepadDisconnected(e.gamepad), + listenerOptions + ); tryOnMounted(() => { - const _gamepads = (navigator2 == null ? void 0 : navigator2.getGamepads()) || []; + const _gamepads = + (navigator2 == null ? void 0 : navigator2.getGamepads()) || []; for (const gamepad of _gamepads) { - if (gamepad && gamepads.value[gamepad.index]) - onGamepadConnected(gamepad); + if (gamepad && gamepads.value[gamepad.index]) onGamepadConnected(gamepad); } }); pause(); @@ -5674,7 +6340,7 @@ function useGamepad(options = {}) { gamepads, pause, resume, - isActive + isActive, }; } function useGeolocation(options = {}) { @@ -5683,9 +6349,11 @@ function useGeolocation(options = {}) { maximumAge = 3e4, timeout = 27e3, navigator: navigator2 = defaultNavigator, - immediate = true + immediate = true, } = options; - const isSupported = useSupported(() => navigator2 && "geolocation" in navigator2); + const isSupported = useSupported( + () => navigator2 && 'geolocation' in navigator2 + ); const locatedAt = shallowRef(null); const error = shallowRef(null); const coords = ref({ @@ -5695,7 +6363,7 @@ function useGeolocation(options = {}) { altitude: null, altitudeAccuracy: null, heading: null, - speed: null + speed: null, }); function updatePosition(position) { locatedAt.value = position.timestamp; @@ -5707,20 +6375,18 @@ function useGeolocation(options = {}) { if (isSupported.value) { watcher = navigator2.geolocation.watchPosition( updatePosition, - (err) => error.value = err, + (err) => (error.value = err), { enableHighAccuracy, maximumAge, - timeout + timeout, } ); } } - if (immediate) - resume(); + if (immediate) resume(); function pause() { - if (watcher && navigator2) - navigator2.geolocation.clearWatch(watcher); + if (watcher && navigator2) navigator2.geolocation.clearWatch(watcher); } tryOnScopeDispose(() => { pause(); @@ -5731,10 +6397,17 @@ function useGeolocation(options = {}) { locatedAt, error, resume, - pause + pause, }; } -var defaultEvents$1 = ["mousemove", "mousedown", "resize", "keydown", "touchstart", "wheel"]; +var defaultEvents$1 = [ + 'mousemove', + 'mousedown', + 'resize', + 'keydown', + 'touchstart', + 'wheel', +]; var oneMinute = 6e4; function useIdle(timeout = oneMinute, options = {}) { const { @@ -5742,7 +6415,7 @@ function useIdle(timeout = oneMinute, options = {}) { listenForVisibilityChange = true, events: events2 = defaultEvents$1, window: window2 = defaultWindow, - eventFilter = throttleFilter(50) + eventFilter = throttleFilter(50), } = options; const idle = shallowRef(initialState); const lastActive = shallowRef(timestamp()); @@ -5750,76 +6423,75 @@ function useIdle(timeout = oneMinute, options = {}) { const reset = () => { idle.value = false; clearTimeout(timer); - timer = setTimeout(() => idle.value = true, timeout); + timer = setTimeout(() => (idle.value = true), timeout); }; - const onEvent = createFilterWrapper( - eventFilter, - () => { - lastActive.value = timestamp(); - reset(); - } - ); + const onEvent = createFilterWrapper(eventFilter, () => { + lastActive.value = timestamp(); + reset(); + }); if (window2) { const document2 = window2.document; const listenerOptions = { passive: true }; for (const event of events2) useEventListener(window2, event, onEvent, listenerOptions); if (listenForVisibilityChange) { - useEventListener(document2, "visibilitychange", () => { - if (!document2.hidden) - onEvent(); - }, listenerOptions); + useEventListener( + document2, + 'visibilitychange', + () => { + if (!document2.hidden) onEvent(); + }, + listenerOptions + ); } reset(); } return { idle, lastActive, - reset + reset, }; } async function loadImage(options) { return new Promise((resolve, reject) => { const img = new Image(); - const { src, srcset, sizes, class: clazz, loading, crossorigin, referrerPolicy, width, height, decoding, fetchPriority, ismap, usemap } = options; + const { + src, + srcset, + sizes, + class: clazz, + loading, + crossorigin, + referrerPolicy, + width, + height, + decoding, + fetchPriority, + ismap, + usemap, + } = options; img.src = src; - if (srcset != null) - img.srcset = srcset; - if (sizes != null) - img.sizes = sizes; - if (clazz != null) - img.className = clazz; - if (loading != null) - img.loading = loading; - if (crossorigin != null) - img.crossOrigin = crossorigin; - if (referrerPolicy != null) - img.referrerPolicy = referrerPolicy; - if (width != null) - img.width = width; - if (height != null) - img.height = height; - if (decoding != null) - img.decoding = decoding; - if (fetchPriority != null) - img.fetchPriority = fetchPriority; - if (ismap != null) - img.isMap = ismap; - if (usemap != null) - img.useMap = usemap; + if (srcset != null) img.srcset = srcset; + if (sizes != null) img.sizes = sizes; + if (clazz != null) img.className = clazz; + if (loading != null) img.loading = loading; + if (crossorigin != null) img.crossOrigin = crossorigin; + if (referrerPolicy != null) img.referrerPolicy = referrerPolicy; + if (width != null) img.width = width; + if (height != null) img.height = height; + if (decoding != null) img.decoding = decoding; + if (fetchPriority != null) img.fetchPriority = fetchPriority; + if (ismap != null) img.isMap = ismap; + if (usemap != null) img.useMap = usemap; img.onload = () => resolve(img); img.onerror = reject; }); } function useImage(options, asyncStateOptions = {}) { - const state = useAsyncState( - () => loadImage(toValue(options)), - void 0, - { - resetOnExecute: true, - ...asyncStateOptions - } - ); + const state = useAsyncState(() => loadImage(toValue(options)), void 0, { + resetOnExecute: true, + ...asyncStateOptions, + }); watch( () => toValue(options), () => state.execute(asyncStateOptions.delay), @@ -5828,9 +6500,9 @@ function useImage(options, asyncStateOptions = {}) { return state; } function resolveElement(el) { - if (typeof Window !== "undefined" && el instanceof Window) + if (typeof Window !== 'undefined' && el instanceof Window) return el.document.documentElement; - if (typeof Document !== "undefined" && el instanceof Document) + if (typeof Document !== 'undefined' && el instanceof Document) return el.documentElement; return el; } @@ -5845,17 +6517,17 @@ function useScroll(element, options = {}) { left: 0, right: 0, top: 0, - bottom: 0 + bottom: 0, }, eventListenerOptions = { capture: false, - passive: true + passive: true, }, - behavior = "auto", + behavior = 'auto', window: window2 = defaultWindow, onError = (e) => { console.error(e); - } + }, } = options; const internalX = shallowRef(0); const internalY = shallowRef(0); @@ -5865,7 +6537,7 @@ function useScroll(element, options = {}) { }, set(x2) { scrollTo(x2, void 0); - } + }, }); const y = computed({ get() { @@ -5873,42 +6545,45 @@ function useScroll(element, options = {}) { }, set(y2) { scrollTo(void 0, y2); - } + }, }); function scrollTo(_x, _y) { var _a, _b, _c, _d; - if (!window2) - return; + if (!window2) return; const _element = toValue(element); - if (!_element) - return; - (_c = _element instanceof Document ? window2.document.body : _element) == null ? void 0 : _c.scrollTo({ - top: (_a = toValue(_y)) != null ? _a : y.value, - left: (_b = toValue(_x)) != null ? _b : x.value, - behavior: toValue(behavior) - }); - const scrollContainer = ((_d = _element == null ? void 0 : _element.document) == null ? void 0 : _d.documentElement) || (_element == null ? void 0 : _element.documentElement) || _element; - if (x != null) - internalX.value = scrollContainer.scrollLeft; - if (y != null) - internalY.value = scrollContainer.scrollTop; + if (!_element) return; + (_c = _element instanceof Document ? window2.document.body : _element) == + null + ? void 0 + : _c.scrollTo({ + top: (_a = toValue(_y)) != null ? _a : y.value, + left: (_b = toValue(_x)) != null ? _b : x.value, + behavior: toValue(behavior), + }); + const scrollContainer = + ((_d = _element == null ? void 0 : _element.document) == null + ? void 0 + : _d.documentElement) || + (_element == null ? void 0 : _element.documentElement) || + _element; + if (x != null) internalX.value = scrollContainer.scrollLeft; + if (y != null) internalY.value = scrollContainer.scrollTop; } const isScrolling = shallowRef(false); const arrivedState = reactive({ left: true, right: false, top: true, - bottom: false + bottom: false, }); const directions = reactive({ left: false, right: false, top: false, - bottom: false + bottom: false, }); const onScrollEnd = (e) => { - if (!isScrolling.value) - return; + if (!isScrolling.value) return; isScrolling.value = false; directions.left = false; directions.right = false; @@ -5919,17 +6594,24 @@ function useScroll(element, options = {}) { const onScrollEndDebounced = useDebounceFn(onScrollEnd, throttle + idle); const setArrivedState = (target) => { var _a; - if (!window2) - return; - const el = ((_a = target == null ? void 0 : target.document) == null ? void 0 : _a.documentElement) || (target == null ? void 0 : target.documentElement) || unrefElement(target); + if (!window2) return; + const el = + ((_a = target == null ? void 0 : target.document) == null + ? void 0 + : _a.documentElement) || + (target == null ? void 0 : target.documentElement) || + unrefElement(target); const { display, flexDirection, direction } = getComputedStyle(el); - const directionMultipler = direction === "rtl" ? -1 : 1; + const directionMultipler = direction === 'rtl' ? -1 : 1; const scrollLeft = el.scrollLeft; directions.left = scrollLeft < internalX.value; directions.right = scrollLeft > internalX.value; - const left = Math.abs(scrollLeft * directionMultipler) <= (offset.left || 0); - const right = Math.abs(scrollLeft * directionMultipler) + el.clientWidth >= el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS; - if (display === "flex" && flexDirection === "row-reverse") { + const left = + Math.abs(scrollLeft * directionMultipler) <= (offset.left || 0); + const right = + Math.abs(scrollLeft * directionMultipler) + el.clientWidth >= + el.scrollWidth - (offset.right || 0) - ARRIVED_STATE_THRESHOLD_PIXELS; + if (display === 'flex' && flexDirection === 'row-reverse') { arrivedState.left = right; arrivedState.right = left; } else { @@ -5943,8 +6625,10 @@ function useScroll(element, options = {}) { directions.top = scrollTop < internalY.value; directions.bottom = scrollTop > internalY.value; const top = Math.abs(scrollTop) <= (offset.top || 0); - const bottom = Math.abs(scrollTop) + el.clientHeight >= el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS; - if (display === "flex" && flexDirection === "column-reverse") { + const bottom = + Math.abs(scrollTop) + el.clientHeight >= + el.scrollHeight - (offset.bottom || 0) - ARRIVED_STATE_THRESHOLD_PIXELS; + if (display === 'flex' && flexDirection === 'column-reverse') { arrivedState.top = bottom; arrivedState.bottom = top; } else { @@ -5955,8 +6639,7 @@ function useScroll(element, options = {}) { }; const onScrollHandler = (e) => { var _a; - if (!window2) - return; + if (!window2) return; const eventTarget = (_a = e.target.documentElement) != null ? _a : e.target; setArrivedState(eventTarget); isScrolling.value = true; @@ -5965,26 +6648,22 @@ function useScroll(element, options = {}) { }; useEventListener( element, - "scroll", - throttle ? useThrottleFn(onScrollHandler, throttle, true, false) : onScrollHandler, + 'scroll', + throttle + ? useThrottleFn(onScrollHandler, throttle, true, false) + : onScrollHandler, eventListenerOptions ); tryOnMounted(() => { try { const _element = toValue(element); - if (!_element) - return; + if (!_element) return; setArrivedState(_element); } catch (e) { onError(e); } }); - useEventListener( - element, - "scrollend", - onScrollEnd, - eventListenerOptions - ); + useEventListener(element, 'scrollend', onScrollEnd, eventListenerOptions); return { x, y, @@ -5993,28 +6672,26 @@ function useScroll(element, options = {}) { directions, measure() { const _element = toValue(element); - if (window2 && _element) - setArrivedState(_element); - } + if (window2 && _element) setArrivedState(_element); + }, }; } function useInfiniteScroll(element, onLoadMore, options = {}) { var _a; const { - direction = "bottom", + direction = 'bottom', interval = 100, - canLoadMore = () => true + canLoadMore = () => true, } = options; - const state = reactive(useScroll( - element, - { + const state = reactive( + useScroll(element, { ...options, offset: { [direction]: (_a = options.distance) != null ? _a : 0, - ...options.offset - } - } - )); + ...options.offset, + }, + }) + ); const promise = ref(); const isLoading = computed(() => !!promise.value); const observedElement = computed(() => { @@ -6023,15 +6700,23 @@ function useInfiniteScroll(element, onLoadMore, options = {}) { const isElementVisible = useElementVisibility(observedElement); function checkAndLoad() { state.measure(); - if (!observedElement.value || !isElementVisible.value || !canLoadMore(observedElement.value)) + if ( + !observedElement.value || + !isElementVisible.value || + !canLoadMore(observedElement.value) + ) return; - const { scrollHeight, clientHeight, scrollWidth, clientWidth } = observedElement.value; - const isNarrower = direction === "bottom" || direction === "top" ? scrollHeight <= clientHeight : scrollWidth <= clientWidth; + const { scrollHeight, clientHeight, scrollWidth, clientWidth } = + observedElement.value; + const isNarrower = + direction === 'bottom' || direction === 'top' + ? scrollHeight <= clientHeight + : scrollWidth <= clientWidth; if (state.arrivedState[direction] || isNarrower) { if (!promise.value) { promise.value = Promise.all([ onLoadMore(state), - new Promise((resolve) => setTimeout(resolve, interval)) + new Promise((resolve) => setTimeout(resolve, interval)), ]).finally(() => { promise.value = null; nextTick(() => checkAndLoad()); @@ -6049,40 +6734,50 @@ function useInfiniteScroll(element, onLoadMore, options = {}) { isLoading, reset() { nextTick(() => checkAndLoad()); - } + }, }; } -var defaultEvents = ["mousedown", "mouseup", "keydown", "keyup"]; +var defaultEvents = ['mousedown', 'mouseup', 'keydown', 'keyup']; function useKeyModifier(modifier, options = {}) { const { events: events2 = defaultEvents, document: document2 = defaultDocument, - initial = null + initial = null, } = options; const state = shallowRef(initial); if (document2) { events2.forEach((listenerEvent) => { - useEventListener(document2, listenerEvent, (evt) => { - if (typeof evt.getModifierState === "function") - state.value = evt.getModifierState(modifier); - }, { passive: true }); + useEventListener( + document2, + listenerEvent, + (evt) => { + if (typeof evt.getModifierState === 'function') + state.value = evt.getModifierState(modifier); + }, + { passive: true } + ); }); } return state; } function useLocalStorage(key, initialValue, options = {}) { const { window: window2 = defaultWindow } = options; - return useStorage(key, initialValue, window2 == null ? void 0 : window2.localStorage, options); + return useStorage( + key, + initialValue, + window2 == null ? void 0 : window2.localStorage, + options + ); } var DefaultMagicKeysAliasMap = { - ctrl: "control", - command: "meta", - cmd: "meta", - option: "alt", - up: "arrowup", - down: "arrowdown", - left: "arrowleft", - right: "arrowright" + ctrl: 'control', + command: 'meta', + cmd: 'meta', + option: 'alt', + up: 'arrowup', + down: 'arrowdown', + left: 'arrowleft', + right: 'arrowright', }; function useMagicKeys(options = {}) { const { @@ -6090,30 +6785,27 @@ function useMagicKeys(options = {}) { target = defaultWindow, aliasMap = DefaultMagicKeysAliasMap, passive = true, - onEventFired = noop + onEventFired = noop, } = options; const current = reactive(/* @__PURE__ */ new Set()); const obj = { toJSON() { return {}; }, - current + current, }; const refs = useReactive ? reactive(obj) : obj; const metaDeps = /* @__PURE__ */ new Set(); const usedKeys = /* @__PURE__ */ new Set(); function setRefs(key, value) { if (key in refs) { - if (useReactive) - refs[key] = value; - else - refs[key].value = value; + if (useReactive) refs[key] = value; + else refs[key].value = value; } } function reset() { current.clear(); - for (const key of usedKeys) - setRefs(key, false); + for (const key of usedKeys) setRefs(key, false); } function updateRefs(e, value) { var _a, _b; @@ -6121,62 +6813,70 @@ function useMagicKeys(options = {}) { const code = (_b = e.code) == null ? void 0 : _b.toLowerCase(); const values = [code, key].filter(Boolean); if (key) { - if (value) - current.add(key); - else - current.delete(key); + if (value) current.add(key); + else current.delete(key); } for (const key2 of values) { usedKeys.add(key2); setRefs(key2, value); } - if (key === "meta" && !value) { + if (key === 'meta' && !value) { metaDeps.forEach((key2) => { current.delete(key2); setRefs(key2, false); }); metaDeps.clear(); - } else if (typeof e.getModifierState === "function" && e.getModifierState("Meta") && value) { + } else if ( + typeof e.getModifierState === 'function' && + e.getModifierState('Meta') && + value + ) { [...current, ...values].forEach((key2) => metaDeps.add(key2)); } } - useEventListener(target, "keydown", (e) => { - updateRefs(e, true); - return onEventFired(e); - }, { passive }); - useEventListener(target, "keyup", (e) => { - updateRefs(e, false); - return onEventFired(e); - }, { passive }); - useEventListener("blur", reset, { passive }); - useEventListener("focus", reset, { passive }); - const proxy = new Proxy( - refs, - { - get(target2, prop, rec) { - if (typeof prop !== "string") - return Reflect.get(target2, prop, rec); - prop = prop.toLowerCase(); - if (prop in aliasMap) - prop = aliasMap[prop]; - if (!(prop in refs)) { - if (/[+_-]/.test(prop)) { - const keys2 = prop.split(/[+_-]/g).map((i) => i.trim()); - refs[prop] = computed(() => keys2.map((key) => toValue(proxy[key])).every(Boolean)); - } else { - refs[prop] = shallowRef(false); - } - } - const r = Reflect.get(target2, prop, rec); - return useReactive ? toValue(r) : r; - } - } + useEventListener( + target, + 'keydown', + (e) => { + updateRefs(e, true); + return onEventFired(e); + }, + { passive } ); + useEventListener( + target, + 'keyup', + (e) => { + updateRefs(e, false); + return onEventFired(e); + }, + { passive } + ); + useEventListener('blur', reset, { passive }); + useEventListener('focus', reset, { passive }); + const proxy = new Proxy(refs, { + get(target2, prop, rec) { + if (typeof prop !== 'string') return Reflect.get(target2, prop, rec); + prop = prop.toLowerCase(); + if (prop in aliasMap) prop = aliasMap[prop]; + if (!(prop in refs)) { + if (/[+_-]/.test(prop)) { + const keys2 = prop.split(/[+_-]/g).map((i) => i.trim()); + refs[prop] = computed(() => + keys2.map((key) => toValue(proxy[key])).every(Boolean) + ); + } else { + refs[prop] = shallowRef(false); + } + } + const r = Reflect.get(target2, prop, rec); + return useReactive ? toValue(r) : r; + }, + }); return proxy; } function usingElRef(source, cb) { - if (toValue(source)) - cb(toValue(source)); + if (toValue(source)) cb(toValue(source)); } function timeRangeToArray(timeRanges) { let ranges = []; @@ -6185,21 +6885,41 @@ function timeRangeToArray(timeRanges) { return ranges; } function tracksToArray(tracks) { - return Array.from(tracks).map(({ label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType }, id) => ({ id, label, kind, language, mode, activeCues, cues, inBandMetadataTrackDispatchType })); + return Array.from(tracks).map( + ( + { + label, + kind, + language, + mode, + activeCues, + cues, + inBandMetadataTrackDispatchType, + }, + id + ) => ({ + id, + label, + kind, + language, + mode, + activeCues, + cues, + inBandMetadataTrackDispatchType, + }) + ); } var defaultOptions = { - src: "", - tracks: [] + src: '', + tracks: [], }; function useMediaControls(target, options = {}) { target = toRef2(target); options = { ...defaultOptions, - ...options + ...options, }; - const { - document: document2 = defaultDocument - } = options; + const { document: document2 = defaultDocument } = options; const listenerOptions = { passive: true }; const currentTime = shallowRef(0); const duration = shallowRef(0); @@ -6215,27 +6935,27 @@ function useMediaControls(target, options = {}) { const selectedTrack = shallowRef(-1); const isPictureInPicture = shallowRef(false); const muted = shallowRef(false); - const supportsPictureInPicture = document2 && "pictureInPictureEnabled" in document2; + const supportsPictureInPicture = + document2 && 'pictureInPictureEnabled' in document2; const sourceErrorEvent = createEventHook(); const playbackErrorEvent = createEventHook(); const disableTrack = (track) => { usingElRef(target, (el) => { if (track) { - const id = typeof track === "number" ? track : track.id; - el.textTracks[id].mode = "disabled"; + const id = typeof track === 'number' ? track : track.id; + el.textTracks[id].mode = 'disabled'; } else { for (let i = 0; i < el.textTracks.length; ++i) - el.textTracks[i].mode = "disabled"; + el.textTracks[i].mode = 'disabled'; } selectedTrack.value = -1; }); }; const enableTrack = (track, disableTracks = true) => { usingElRef(target, (el) => { - const id = typeof track === "number" ? track : track.id; - if (disableTracks) - disableTrack(); - el.textTracks[id].mode = "showing"; + const id = typeof track === 'number' ? track : track.id; + if (disableTracks) disableTrack(); + el.textTracks[id].mode = 'showing'; selectedTrack.value = id; }); }; @@ -6253,195 +6973,196 @@ function useMediaControls(target, options = {}) { }); }; watchEffect(() => { - if (!document2) - return; + if (!document2) return; const el = toValue(target); - if (!el) - return; + if (!el) return; const src = toValue(options.src); let sources = []; - if (!src) - return; - if (typeof src === "string") - sources = [{ src }]; - else if (Array.isArray(src)) - sources = src; - else if (isObject(src)) - sources = [src]; - el.querySelectorAll("source").forEach((e) => { + if (!src) return; + if (typeof src === 'string') sources = [{ src }]; + else if (Array.isArray(src)) sources = src; + else if (isObject(src)) sources = [src]; + el.querySelectorAll('source').forEach((e) => { e.remove(); }); sources.forEach(({ src: src2, type, media }) => { - const source = document2.createElement("source"); - source.setAttribute("src", src2); - source.setAttribute("type", type || ""); - source.setAttribute("media", media || ""); - useEventListener(source, "error", sourceErrorEvent.trigger, listenerOptions); + const source = document2.createElement('source'); + source.setAttribute('src', src2); + source.setAttribute('type', type || ''); + source.setAttribute('media', media || ''); + useEventListener( + source, + 'error', + sourceErrorEvent.trigger, + listenerOptions + ); el.appendChild(source); }); el.load(); }); watch([target, volume], () => { const el = toValue(target); - if (!el) - return; + if (!el) return; el.volume = volume.value; }); watch([target, muted], () => { const el = toValue(target); - if (!el) - return; + if (!el) return; el.muted = muted.value; }); watch([target, rate], () => { const el = toValue(target); - if (!el) - return; + if (!el) return; el.playbackRate = rate.value; }); watchEffect(() => { - if (!document2) - return; + if (!document2) return; const textTracks = toValue(options.tracks); const el = toValue(target); - if (!textTracks || !textTracks.length || !el) - return; - el.querySelectorAll("track").forEach((e) => e.remove()); - textTracks.forEach(({ default: isDefault, kind, label, src, srcLang }, i) => { - const track = document2.createElement("track"); - track.default = isDefault || false; - track.kind = kind; - track.label = label; - track.src = src; - track.srclang = srcLang; - if (track.default) - selectedTrack.value = i; - el.appendChild(track); - }); + if (!textTracks || !textTracks.length || !el) return; + el.querySelectorAll('track').forEach((e) => e.remove()); + textTracks.forEach( + ({ default: isDefault, kind, label, src, srcLang }, i) => { + const track = document2.createElement('track'); + track.default = isDefault || false; + track.kind = kind; + track.label = label; + track.src = src; + track.srclang = srcLang; + if (track.default) selectedTrack.value = i; + el.appendChild(track); + } + ); }); - const { ignoreUpdates: ignoreCurrentTimeUpdates } = watchIgnorable(currentTime, (time) => { - const el = toValue(target); - if (!el) - return; - el.currentTime = time; - }); - const { ignoreUpdates: ignorePlayingUpdates } = watchIgnorable(playing, (isPlaying) => { - const el = toValue(target); - if (!el) - return; - if (isPlaying) { - el.play().catch((e) => { - playbackErrorEvent.trigger(e); - throw e; - }); - } else { - el.pause(); + const { ignoreUpdates: ignoreCurrentTimeUpdates } = watchIgnorable( + currentTime, + (time) => { + const el = toValue(target); + if (!el) return; + el.currentTime = time; } - }); + ); + const { ignoreUpdates: ignorePlayingUpdates } = watchIgnorable( + playing, + (isPlaying) => { + const el = toValue(target); + if (!el) return; + if (isPlaying) { + el.play().catch((e) => { + playbackErrorEvent.trigger(e); + throw e; + }); + } else { + el.pause(); + } + } + ); useEventListener( target, - "timeupdate", - () => ignoreCurrentTimeUpdates(() => currentTime.value = toValue(target).currentTime), + 'timeupdate', + () => + ignoreCurrentTimeUpdates( + () => (currentTime.value = toValue(target).currentTime) + ), listenerOptions ); useEventListener( target, - "durationchange", - () => duration.value = toValue(target).duration, + 'durationchange', + () => (duration.value = toValue(target).duration), listenerOptions ); useEventListener( target, - "progress", - () => buffered.value = timeRangeToArray(toValue(target).buffered), + 'progress', + () => (buffered.value = timeRangeToArray(toValue(target).buffered)), listenerOptions ); useEventListener( target, - "seeking", - () => seeking.value = true, + 'seeking', + () => (seeking.value = true), listenerOptions ); useEventListener( target, - "seeked", - () => seeking.value = false, + 'seeked', + () => (seeking.value = false), listenerOptions ); useEventListener( target, - ["waiting", "loadstart"], + ['waiting', 'loadstart'], () => { waiting.value = true; - ignorePlayingUpdates(() => playing.value = false); + ignorePlayingUpdates(() => (playing.value = false)); }, listenerOptions ); useEventListener( target, - "loadeddata", - () => waiting.value = false, + 'loadeddata', + () => (waiting.value = false), listenerOptions ); useEventListener( target, - "playing", + 'playing', () => { waiting.value = false; ended.value = false; - ignorePlayingUpdates(() => playing.value = true); + ignorePlayingUpdates(() => (playing.value = true)); }, listenerOptions ); useEventListener( target, - "ratechange", - () => rate.value = toValue(target).playbackRate, + 'ratechange', + () => (rate.value = toValue(target).playbackRate), listenerOptions ); useEventListener( target, - "stalled", - () => stalled.value = true, + 'stalled', + () => (stalled.value = true), listenerOptions ); useEventListener( target, - "ended", - () => ended.value = true, + 'ended', + () => (ended.value = true), listenerOptions ); useEventListener( target, - "pause", - () => ignorePlayingUpdates(() => playing.value = false), + 'pause', + () => ignorePlayingUpdates(() => (playing.value = false)), listenerOptions ); useEventListener( target, - "play", - () => ignorePlayingUpdates(() => playing.value = true), + 'play', + () => ignorePlayingUpdates(() => (playing.value = true)), listenerOptions ); useEventListener( target, - "enterpictureinpicture", - () => isPictureInPicture.value = true, + 'enterpictureinpicture', + () => (isPictureInPicture.value = true), listenerOptions ); useEventListener( target, - "leavepictureinpicture", - () => isPictureInPicture.value = false, + 'leavepictureinpicture', + () => (isPictureInPicture.value = false), listenerOptions ); useEventListener( target, - "volumechange", + 'volumechange', () => { const el = toValue(target); - if (!el) - return; + if (!el) return; volume.value = el.volume; muted.value = el.muted; }, @@ -6450,12 +7171,26 @@ function useMediaControls(target, options = {}) { const listeners = []; const stop = watch([target], () => { const el = toValue(target); - if (!el) - return; + if (!el) return; stop(); - listeners[0] = useEventListener(el.textTracks, "addtrack", () => tracks.value = tracksToArray(el.textTracks), listenerOptions); - listeners[1] = useEventListener(el.textTracks, "removetrack", () => tracks.value = tracksToArray(el.textTracks), listenerOptions); - listeners[2] = useEventListener(el.textTracks, "change", () => tracks.value = tracksToArray(el.textTracks), listenerOptions); + listeners[0] = useEventListener( + el.textTracks, + 'addtrack', + () => (tracks.value = tracksToArray(el.textTracks)), + listenerOptions + ); + listeners[1] = useEventListener( + el.textTracks, + 'removetrack', + () => (tracks.value = tracksToArray(el.textTracks)), + listenerOptions + ); + listeners[2] = useEventListener( + el.textTracks, + 'change', + () => (tracks.value = tracksToArray(el.textTracks)), + listenerOptions + ); }); tryOnScopeDispose(() => listeners.forEach((listener) => listener())); return { @@ -6482,7 +7217,7 @@ function useMediaControls(target, options = {}) { isPictureInPicture, // Events onSourceError: sourceErrorEvent.on, - onPlaybackError: playbackErrorEvent.on + onPlaybackError: playbackErrorEvent.on, }; } function useMemoize(resolver, options) { @@ -6492,7 +7227,10 @@ function useMemoize(resolver, options) { return shallowReactive(/* @__PURE__ */ new Map()); }; const cache = initCache(); - const generateKey = (...args) => (options == null ? void 0 : options.getKey) ? options.getKey(...args) : JSON.stringify(args); + const generateKey = (...args) => + (options == null ? void 0 : options.getKey) + ? options.getKey(...args) + : JSON.stringify(args); const _loadData = (key, ...args) => { cache.set(key, resolver(...args)); return cache.get(key); @@ -6506,8 +7244,7 @@ function useMemoize(resolver, options) { }; const memoized = (...args) => { const key = generateKey(...args); - if (cache.has(key)) - return cache.get(key); + if (cache.has(key)) return cache.get(key); return _loadData(key, ...args); }; memoized.load = loadData; @@ -6519,12 +7256,21 @@ function useMemoize(resolver, options) { } function useMemory(options = {}) { const memory = ref(); - const isSupported = useSupported(() => typeof performance !== "undefined" && "memory" in performance); + const isSupported = useSupported( + () => typeof performance !== 'undefined' && 'memory' in performance + ); if (isSupported.value) { const { interval = 1e3 } = options; - useIntervalFn(() => { - memory.value = performance.memory; - }, interval, { immediate: options.immediate, immediateCallback: options.immediateCallback }); + useIntervalFn( + () => { + memory.value = performance.memory; + }, + interval, + { + immediate: options.immediate, + immediateCallback: options.immediateCallback, + } + ); } return { isSupported, memory }; } @@ -6532,18 +7278,19 @@ var UseMouseBuiltinExtractors = { page: (event) => [event.pageX, event.pageY], client: (event) => [event.clientX, event.clientY], screen: (event) => [event.screenX, event.screenY], - movement: (event) => event instanceof MouseEvent ? [event.movementX, event.movementY] : null + movement: (event) => + event instanceof MouseEvent ? [event.movementX, event.movementY] : null, }; function useMouse(options = {}) { const { - type = "page", + type = 'page', touch = true, resetOnTouchEnds = false, initialValue = { x: 0, y: 0 }, window: window2 = defaultWindow, target = window2, scroll = true, - eventFilter + eventFilter, } = options; let _prevMouseEvent = null; let _prevScrollX = 0; @@ -6551,13 +7298,14 @@ function useMouse(options = {}) { const x = shallowRef(initialValue.x); const y = shallowRef(initialValue.y); const sourceType = shallowRef(null); - const extractor = typeof type === "function" ? type : UseMouseBuiltinExtractors[type]; + const extractor = + typeof type === 'function' ? type : UseMouseBuiltinExtractors[type]; const mouseHandler = (event) => { const result = extractor(event); _prevMouseEvent = event; if (result) { [x.value, y.value] = result; - sourceType.value = "mouse"; + sourceType.value = 'mouse'; } if (window2) { _prevScrollX = window2.scrollX; @@ -6569,13 +7317,12 @@ function useMouse(options = {}) { const result = extractor(event.touches[0]); if (result) { [x.value, y.value] = result; - sourceType.value = "touch"; + sourceType.value = 'touch'; } } }; const scrollHandler = () => { - if (!_prevMouseEvent || !window2) - return; + if (!_prevMouseEvent || !window2) return; const pos = extractor(_prevMouseEvent); if (_prevMouseEvent instanceof MouseEvent && pos) { x.value = pos[0] + window2.scrollX - _prevScrollX; @@ -6586,34 +7333,54 @@ function useMouse(options = {}) { x.value = initialValue.x; y.value = initialValue.y; }; - const mouseHandlerWrapper = eventFilter ? (event) => eventFilter(() => mouseHandler(event), {}) : (event) => mouseHandler(event); - const touchHandlerWrapper = eventFilter ? (event) => eventFilter(() => touchHandler(event), {}) : (event) => touchHandler(event); - const scrollHandlerWrapper = eventFilter ? () => eventFilter(() => scrollHandler(), {}) : () => scrollHandler(); + const mouseHandlerWrapper = eventFilter + ? (event) => eventFilter(() => mouseHandler(event), {}) + : (event) => mouseHandler(event); + const touchHandlerWrapper = eventFilter + ? (event) => eventFilter(() => touchHandler(event), {}) + : (event) => touchHandler(event); + const scrollHandlerWrapper = eventFilter + ? () => eventFilter(() => scrollHandler(), {}) + : () => scrollHandler(); if (target) { const listenerOptions = { passive: true }; - useEventListener(target, ["mousemove", "dragover"], mouseHandlerWrapper, listenerOptions); - if (touch && type !== "movement") { - useEventListener(target, ["touchstart", "touchmove"], touchHandlerWrapper, listenerOptions); + useEventListener( + target, + ['mousemove', 'dragover'], + mouseHandlerWrapper, + listenerOptions + ); + if (touch && type !== 'movement') { + useEventListener( + target, + ['touchstart', 'touchmove'], + touchHandlerWrapper, + listenerOptions + ); if (resetOnTouchEnds) - useEventListener(target, "touchend", reset, listenerOptions); + useEventListener(target, 'touchend', reset, listenerOptions); } - if (scroll && type === "page") - useEventListener(window2, "scroll", scrollHandlerWrapper, listenerOptions); + if (scroll && type === 'page') + useEventListener( + window2, + 'scroll', + scrollHandlerWrapper, + listenerOptions + ); } return { x, y, - sourceType + sourceType, }; } function useMouseInElement(target, options = {}) { - const { - handleOutside = true, - window: window2 = defaultWindow - } = options; - const type = options.type || "page"; + const { handleOutside = true, window: window2 = defaultWindow } = options; + const type = options.type || 'page'; const { x, y, sourceType } = useMouse(options); - const targetRef = shallowRef(target != null ? target : window2 == null ? void 0 : window2.document.body); + const targetRef = shallowRef( + target != null ? target : window2 == null ? void 0 : window2.document.body + ); const elementX = shallowRef(0); const elementY = shallowRef(0); const elementPositionX = shallowRef(0); @@ -6621,28 +7388,29 @@ function useMouseInElement(target, options = {}) { const elementHeight = shallowRef(0); const elementWidth = shallowRef(0); const isOutside = shallowRef(true); - let stop = () => { - }; + let stop = () => {}; if (window2) { stop = watch( [targetRef, x, y], () => { const el = unrefElement(targetRef); - if (!el || !(el instanceof Element)) - return; - const { - left, - top, - width, - height - } = el.getBoundingClientRect(); - elementPositionX.value = left + (type === "page" ? window2.pageXOffset : 0); - elementPositionY.value = top + (type === "page" ? window2.pageYOffset : 0); + if (!el || !(el instanceof Element)) return; + const { left, top, width, height } = el.getBoundingClientRect(); + elementPositionX.value = + left + (type === 'page' ? window2.pageXOffset : 0); + elementPositionY.value = + top + (type === 'page' ? window2.pageYOffset : 0); elementHeight.value = height; elementWidth.value = width; const elX = x.value - elementPositionX.value; const elY = y.value - elementPositionY.value; - isOutside.value = width === 0 || height === 0 || elX < 0 || elY < 0 || elX > width || elY > height; + isOutside.value = + width === 0 || + height === 0 || + elX < 0 || + elY < 0 || + elX > width || + elY > height; if (handleOutside || !isOutside.value) { elementX.value = elX; elementY.value = elY; @@ -6650,12 +7418,9 @@ function useMouseInElement(target, options = {}) { }, { immediate: true } ); - useEventListener( - document, - "mouseleave", - () => isOutside.value = true, - { passive: true } - ); + useEventListener(document, 'mouseleave', () => (isOutside.value = true), { + passive: true, + }); } return { x, @@ -6668,7 +7433,7 @@ function useMouseInElement(target, options = {}) { elementHeight, elementWidth, isOutside, - stop + stop, }; } function useMousePressed(options = {}) { @@ -6677,14 +7442,14 @@ function useMousePressed(options = {}) { drag = true, capture = false, initialValue = false, - window: window2 = defaultWindow + window: window2 = defaultWindow, } = options; const pressed = shallowRef(initialValue); const sourceType = shallowRef(null); if (!window2) { return { pressed, - sourceType + sourceType, }; } const onPressed = (srcType) => (event) => { @@ -6701,42 +7466,52 @@ function useMousePressed(options = {}) { }; const target = computed(() => unrefElement(options.target) || window2); const listenerOptions = { passive: true, capture }; - useEventListener(target, "mousedown", onPressed("mouse"), listenerOptions); - useEventListener(window2, "mouseleave", onReleased, listenerOptions); - useEventListener(window2, "mouseup", onReleased, listenerOptions); + useEventListener(target, 'mousedown', onPressed('mouse'), listenerOptions); + useEventListener(window2, 'mouseleave', onReleased, listenerOptions); + useEventListener(window2, 'mouseup', onReleased, listenerOptions); if (drag) { - useEventListener(target, "dragstart", onPressed("mouse"), listenerOptions); - useEventListener(window2, "drop", onReleased, listenerOptions); - useEventListener(window2, "dragend", onReleased, listenerOptions); + useEventListener(target, 'dragstart', onPressed('mouse'), listenerOptions); + useEventListener(window2, 'drop', onReleased, listenerOptions); + useEventListener(window2, 'dragend', onReleased, listenerOptions); } if (touch) { - useEventListener(target, "touchstart", onPressed("touch"), listenerOptions); - useEventListener(window2, "touchend", onReleased, listenerOptions); - useEventListener(window2, "touchcancel", onReleased, listenerOptions); + useEventListener(target, 'touchstart', onPressed('touch'), listenerOptions); + useEventListener(window2, 'touchend', onReleased, listenerOptions); + useEventListener(window2, 'touchcancel', onReleased, listenerOptions); } return { pressed, - sourceType + sourceType, }; } function useNavigatorLanguage(options = {}) { const { window: window2 = defaultWindow } = options; const navigator2 = window2 == null ? void 0 : window2.navigator; - const isSupported = useSupported(() => navigator2 && "language" in navigator2); - const language = shallowRef(navigator2 == null ? void 0 : navigator2.language); - useEventListener(window2, "languagechange", () => { - if (navigator2) - language.value = navigator2.language; - }, { passive: true }); + const isSupported = useSupported( + () => navigator2 && 'language' in navigator2 + ); + const language = shallowRef( + navigator2 == null ? void 0 : navigator2.language + ); + useEventListener( + window2, + 'languagechange', + () => { + if (navigator2) language.value = navigator2.language; + }, + { passive: true } + ); return { isSupported, - language + language, }; } function useNetwork(options = {}) { const { window: window2 = defaultWindow } = options; const navigator2 = window2 == null ? void 0 : window2.navigator; - const isSupported = useSupported(() => navigator2 && "connection" in navigator2); + const isSupported = useSupported( + () => navigator2 && 'connection' in navigator2 + ); const isOnline = shallowRef(true); const saveData = shallowRef(false); const offlineAt = shallowRef(void 0); @@ -6745,11 +7520,10 @@ function useNetwork(options = {}) { const downlinkMax = shallowRef(void 0); const rtt = shallowRef(void 0); const effectiveType = shallowRef(void 0); - const type = shallowRef("unknown"); + const type = shallowRef('unknown'); const connection = isSupported.value && navigator2.connection; function updateNetworkInformation() { - if (!navigator2) - return; + if (!navigator2) return; isOnline.value = navigator2.onLine; offlineAt.value = isOnline.value ? void 0 : Date.now(); onlineAt.value = isOnline.value ? Date.now() : void 0; @@ -6764,17 +7538,32 @@ function useNetwork(options = {}) { } const listenerOptions = { passive: true }; if (window2) { - useEventListener(window2, "offline", () => { - isOnline.value = false; - offlineAt.value = Date.now(); - }, listenerOptions); - useEventListener(window2, "online", () => { - isOnline.value = true; - onlineAt.value = Date.now(); - }, listenerOptions); + useEventListener( + window2, + 'offline', + () => { + isOnline.value = false; + offlineAt.value = Date.now(); + }, + listenerOptions + ); + useEventListener( + window2, + 'online', + () => { + isOnline.value = true; + onlineAt.value = Date.now(); + }, + listenerOptions + ); } if (connection) - useEventListener(connection, "change", updateNetworkInformation, listenerOptions); + useEventListener( + connection, + 'change', + updateNetworkInformation, + listenerOptions + ); updateNetworkInformation(); return { isSupported, @@ -6786,21 +7575,24 @@ function useNetwork(options = {}) { downlinkMax: readonly(downlinkMax), effectiveType: readonly(effectiveType), rtt: readonly(rtt), - type: readonly(type) + type: readonly(type), }; } function useNow(options = {}) { const { controls: exposeControls = false, - interval = "requestAnimationFrame" + interval = 'requestAnimationFrame', } = options; const now2 = ref(/* @__PURE__ */ new Date()); - const update = () => now2.value = /* @__PURE__ */ new Date(); - const controls = interval === "requestAnimationFrame" ? useRafFn(update, { immediate: true }) : useIntervalFn(update, interval, { immediate: true }); + const update = () => (now2.value = /* @__PURE__ */ new Date()); + const controls = + interval === 'requestAnimationFrame' + ? useRafFn(update, { immediate: true }) + : useIntervalFn(update, interval, { immediate: true }); if (exposeControls) { return { now: now2, - ...controls + ...controls, }; } else { return now2; @@ -6809,16 +7601,14 @@ function useNow(options = {}) { function useObjectUrl(object) { const url = shallowRef(); const release = () => { - if (url.value) - URL.revokeObjectURL(url.value); + if (url.value) URL.revokeObjectURL(url.value); url.value = void 0; }; watch( () => toValue(object), (newObject) => { release(); - if (newObject) - url.value = URL.createObjectURL(newObject); + if (newObject) url.value = URL.createObjectURL(newObject); }, { immediate: true } ); @@ -6826,16 +7616,16 @@ function useObjectUrl(object) { return readonly(url); } function useClamp(value, min, max) { - if (typeof value === "function" || isReadonly(value)) + if (typeof value === 'function' || isReadonly(value)) return computed(() => clamp(toValue(value), toValue(min), toValue(max))); const _value = ref(value); return computed({ get() { - return _value.value = clamp(_value.value, toValue(min), toValue(max)); + return (_value.value = clamp(_value.value, toValue(min), toValue(max))); }, set(value2) { _value.value = clamp(value2, toValue(min), toValue(max)); - } + }, }); } function useOffsetPagination(options) { @@ -6845,24 +7635,23 @@ function useOffsetPagination(options) { page = 1, onPageChange = noop, onPageSizeChange = noop, - onPageCountChange = noop + onPageCountChange = noop, } = options; const currentPageSize = useClamp(pageSize, 1, Number.POSITIVE_INFINITY); - const pageCount = computed(() => Math.max( - 1, - Math.ceil(toValue(total) / toValue(currentPageSize)) - )); + const pageCount = computed(() => + Math.max(1, Math.ceil(toValue(total) / toValue(currentPageSize))) + ); const currentPage = useClamp(page, 1, pageCount); const isFirstPage = computed(() => currentPage.value === 1); const isLastPage = computed(() => currentPage.value === pageCount.value); if (isRef(page)) { syncRef(page, currentPage, { - direction: isReadonly(page) ? "ltr" : "both" + direction: isReadonly(page) ? 'ltr' : 'both', }); } if (isRef(pageSize)) { syncRef(pageSize, currentPageSize, { - direction: isReadonly(pageSize) ? "ltr" : "both" + direction: isReadonly(pageSize) ? 'ltr' : 'both', }); } function prev() { @@ -6878,7 +7667,7 @@ function useOffsetPagination(options) { isFirstPage, isLastPage, prev, - next + next, }; watch(currentPage, () => { onPageChange(reactive(returnValue)); @@ -6899,41 +7688,45 @@ function usePageLeave(options = {}) { const { window: window2 = defaultWindow } = options; const isLeft = shallowRef(false); const handler = (event) => { - if (!window2) - return; + if (!window2) return; event = event || window2.event; const from = event.relatedTarget || event.toElement; isLeft.value = !from; }; if (window2) { const listenerOptions = { passive: true }; - useEventListener(window2, "mouseout", handler, listenerOptions); - useEventListener(window2.document, "mouseleave", handler, listenerOptions); - useEventListener(window2.document, "mouseenter", handler, listenerOptions); + useEventListener(window2, 'mouseout', handler, listenerOptions); + useEventListener(window2.document, 'mouseleave', handler, listenerOptions); + useEventListener(window2.document, 'mouseenter', handler, listenerOptions); } return isLeft; } function useScreenOrientation(options = {}) { - const { - window: window2 = defaultWindow - } = options; - const isSupported = useSupported(() => window2 && "screen" in window2 && "orientation" in window2.screen); + const { window: window2 = defaultWindow } = options; + const isSupported = useSupported( + () => window2 && 'screen' in window2 && 'orientation' in window2.screen + ); const screenOrientation = isSupported.value ? window2.screen.orientation : {}; const orientation = ref(screenOrientation.type); const angle = shallowRef(screenOrientation.angle || 0); if (isSupported.value) { - useEventListener(window2, "orientationchange", () => { - orientation.value = screenOrientation.type; - angle.value = screenOrientation.angle; - }, { passive: true }); + useEventListener( + window2, + 'orientationchange', + () => { + orientation.value = screenOrientation.type; + angle.value = screenOrientation.angle; + }, + { passive: true } + ); } const lockOrientation = (type) => { - if (isSupported.value && typeof screenOrientation.lock === "function") + if (isSupported.value && typeof screenOrientation.lock === 'function') return screenOrientation.lock(type); - return Promise.reject(new Error("Not supported")); + return Promise.reject(new Error('Not supported')); }; const unlockOrientation = () => { - if (isSupported.value && typeof screenOrientation.unlock === "function") + if (isSupported.value && typeof screenOrientation.unlock === 'function') screenOrientation.unlock(); }; return { @@ -6941,7 +7734,7 @@ function useScreenOrientation(options = {}) { orientation, angle, lockOrientation, - unlockOrientation + unlockOrientation, }; } function useParallax(target, options = {}) { @@ -6950,7 +7743,7 @@ function useParallax(target, options = {}) { deviceOrientationRollAdjust = (i) => i, mouseTiltAdjust = (i) => i, mouseRollAdjust = (i) => i, - window: window2 = defaultWindow + window: window2 = defaultWindow, } = options; const orientation = reactive(useDeviceOrientation({ window: window2 })); const screenOrientation = reactive(useScreenOrientation({ window: window2 })); @@ -6958,28 +7751,32 @@ function useParallax(target, options = {}) { elementX: x, elementY: y, elementWidth: width, - elementHeight: height + elementHeight: height, } = useMouseInElement(target, { handleOutside: false, window: window2 }); const source = computed(() => { - if (orientation.isSupported && (orientation.alpha != null && orientation.alpha !== 0 || orientation.gamma != null && orientation.gamma !== 0)) { - return "deviceOrientation"; + if ( + orientation.isSupported && + ((orientation.alpha != null && orientation.alpha !== 0) || + (orientation.gamma != null && orientation.gamma !== 0)) + ) { + return 'deviceOrientation'; } - return "mouse"; + return 'mouse'; }); const roll = computed(() => { - if (source.value === "deviceOrientation") { + if (source.value === 'deviceOrientation') { let value; switch (screenOrientation.orientation) { - case "landscape-primary": + case 'landscape-primary': value = orientation.gamma / 90; break; - case "landscape-secondary": + case 'landscape-secondary': value = -orientation.gamma / 90; break; - case "portrait-primary": + case 'portrait-primary': value = -orientation.beta / 90; break; - case "portrait-secondary": + case 'portrait-secondary': value = orientation.beta / 90; break; default: @@ -6992,19 +7789,19 @@ function useParallax(target, options = {}) { } }); const tilt = computed(() => { - if (source.value === "deviceOrientation") { + if (source.value === 'deviceOrientation') { let value; switch (screenOrientation.orientation) { - case "landscape-primary": + case 'landscape-primary': value = orientation.beta / 90; break; - case "landscape-secondary": + case 'landscape-secondary': value = -orientation.beta / 90; break; - case "portrait-primary": + case 'portrait-primary': value = orientation.gamma / 90; break; - case "portrait-secondary": + case 'portrait-secondary': value = -orientation.gamma / 90; break; default: @@ -7022,8 +7819,7 @@ function useParentElement(element = useCurrentElement()) { const parentElement = shallowRef(); const update = () => { const el = unrefElement(element); - if (el) - parentElement.value = el.parentElement; + if (el) parentElement.value = el.parentElement; }; tryOnMounted(update); watch(() => toValue(element), update); @@ -7035,7 +7831,9 @@ function usePerformanceObserver(options, callback) { immediate = true, ...performanceOptions } = options; - const isSupported = useSupported(() => window2 && "PerformanceObserver" in window2); + const isSupported = useSupported( + () => window2 && 'PerformanceObserver' in window2 + ); let observer; const stop = () => { observer == null ? void 0 : observer.disconnect(); @@ -7048,12 +7846,11 @@ function usePerformanceObserver(options, callback) { } }; tryOnScopeDispose(stop); - if (immediate) - start(); + if (immediate) start(); return { isSupported, start, - stop + stop, }; } var defaultState = { @@ -7066,72 +7863,99 @@ var defaultState = { width: 0, height: 0, twist: 0, - pointerType: null + pointerType: null, }; var keys = Object.keys(defaultState); function usePointer(options = {}) { - const { - target = defaultWindow - } = options; + const { target = defaultWindow } = options; const isInside = shallowRef(false); const state = ref(options.initialValue || {}); Object.assign(state.value, defaultState, state.value); const handler = (event) => { isInside.value = true; - if (options.pointerTypes && !options.pointerTypes.includes(event.pointerType)) + if ( + options.pointerTypes && + !options.pointerTypes.includes(event.pointerType) + ) return; state.value = objectPick(event, keys, false); }; if (target) { const listenerOptions = { passive: true }; - useEventListener(target, ["pointerdown", "pointermove", "pointerup"], handler, listenerOptions); - useEventListener(target, "pointerleave", () => isInside.value = false, listenerOptions); + useEventListener( + target, + ['pointerdown', 'pointermove', 'pointerup'], + handler, + listenerOptions + ); + useEventListener( + target, + 'pointerleave', + () => (isInside.value = false), + listenerOptions + ); } return { ...toRefs2(state), - isInside + isInside, }; } function usePointerLock(target, options = {}) { const { document: document2 = defaultDocument } = options; - const isSupported = useSupported(() => document2 && "pointerLockElement" in document2); + const isSupported = useSupported( + () => document2 && 'pointerLockElement' in document2 + ); const element = shallowRef(); const triggerElement = shallowRef(); let targetElement; if (isSupported.value) { const listenerOptions = { passive: true }; - useEventListener(document2, "pointerlockchange", () => { - var _a; - const currentElement = (_a = document2.pointerLockElement) != null ? _a : element.value; - if (targetElement && currentElement === targetElement) { - element.value = document2.pointerLockElement; - if (!element.value) - targetElement = triggerElement.value = null; - } - }, listenerOptions); - useEventListener(document2, "pointerlockerror", () => { - var _a; - const currentElement = (_a = document2.pointerLockElement) != null ? _a : element.value; - if (targetElement && currentElement === targetElement) { - const action = document2.pointerLockElement ? "release" : "acquire"; - throw new Error(`Failed to ${action} pointer lock.`); - } - }, listenerOptions); + useEventListener( + document2, + 'pointerlockchange', + () => { + var _a; + const currentElement = + (_a = document2.pointerLockElement) != null ? _a : element.value; + if (targetElement && currentElement === targetElement) { + element.value = document2.pointerLockElement; + if (!element.value) targetElement = triggerElement.value = null; + } + }, + listenerOptions + ); + useEventListener( + document2, + 'pointerlockerror', + () => { + var _a; + const currentElement = + (_a = document2.pointerLockElement) != null ? _a : element.value; + if (targetElement && currentElement === targetElement) { + const action = document2.pointerLockElement ? 'release' : 'acquire'; + throw new Error(`Failed to ${action} pointer lock.`); + } + }, + listenerOptions + ); } async function lock(e) { var _a; if (!isSupported.value) - throw new Error("Pointer Lock API is not supported by your browser."); + throw new Error('Pointer Lock API is not supported by your browser.'); triggerElement.value = e instanceof Event ? e.currentTarget : null; - targetElement = e instanceof Event ? (_a = unrefElement(target)) != null ? _a : triggerElement.value : unrefElement(e); - if (!targetElement) - throw new Error("Target element undefined."); + targetElement = + e instanceof Event + ? (_a = unrefElement(target)) != null + ? _a + : triggerElement.value + : unrefElement(e); + if (!targetElement) throw new Error('Target element undefined.'); targetElement.requestPointerLock(); return await until(element).toBe(targetElement); } async function unlock() { - if (!element.value) - return false; + if (!element.value) return false; document2.exitPointerLock(); await until(element).toBeNull(); return true; @@ -7141,7 +7965,7 @@ function usePointerLock(target, options = {}) { element, triggerElement, lock, - unlock + unlock, }; } function usePointerSwipe(target, options = {}) { @@ -7151,7 +7975,7 @@ function usePointerSwipe(target, options = {}) { onSwipe, onSwipeEnd, onSwipeStart, - disableTextSelect = false + disableTextSelect = false, } = options; const posStart = reactive({ x: 0, y: 0 }); const updatePosStart = (x, y) => { @@ -7166,65 +7990,94 @@ function usePointerSwipe(target, options = {}) { const distanceX = computed(() => posStart.x - posEnd.x); const distanceY = computed(() => posStart.y - posEnd.y); const { max, abs } = Math; - const isThresholdExceeded = computed(() => max(abs(distanceX.value), abs(distanceY.value)) >= threshold); + const isThresholdExceeded = computed( + () => max(abs(distanceX.value), abs(distanceY.value)) >= threshold + ); const isSwiping = shallowRef(false); const isPointerDown = shallowRef(false); const direction = computed(() => { - if (!isThresholdExceeded.value) - return "none"; + if (!isThresholdExceeded.value) return 'none'; if (abs(distanceX.value) > abs(distanceY.value)) { - return distanceX.value > 0 ? "left" : "right"; + return distanceX.value > 0 ? 'left' : 'right'; } else { - return distanceY.value > 0 ? "up" : "down"; + return distanceY.value > 0 ? 'up' : 'down'; } }); const eventIsAllowed = (e) => { var _a, _b, _c; const isReleasingButton = e.buttons === 0; const isPrimaryButton = e.buttons === 1; - return (_c = (_b = (_a = options.pointerTypes) == null ? void 0 : _a.includes(e.pointerType)) != null ? _b : isReleasingButton || isPrimaryButton) != null ? _c : true; + return (_c = + (_b = + (_a = options.pointerTypes) == null + ? void 0 + : _a.includes(e.pointerType)) != null + ? _b + : isReleasingButton || isPrimaryButton) != null + ? _c + : true; }; const listenerOptions = { passive: true }; const stops = [ - useEventListener(target, "pointerdown", (e) => { - if (!eventIsAllowed(e)) - return; - isPointerDown.value = true; - const eventTarget = e.target; - eventTarget == null ? void 0 : eventTarget.setPointerCapture(e.pointerId); - const { clientX: x, clientY: y } = e; - updatePosStart(x, y); - updatePosEnd(x, y); - onSwipeStart == null ? void 0 : onSwipeStart(e); - }, listenerOptions), - useEventListener(target, "pointermove", (e) => { - if (!eventIsAllowed(e)) - return; - if (!isPointerDown.value) - return; - const { clientX: x, clientY: y } = e; - updatePosEnd(x, y); - if (!isSwiping.value && isThresholdExceeded.value) - isSwiping.value = true; - if (isSwiping.value) - onSwipe == null ? void 0 : onSwipe(e); - }, listenerOptions), - useEventListener(target, "pointerup", (e) => { - if (!eventIsAllowed(e)) - return; - if (isSwiping.value) - onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value); - isPointerDown.value = false; - isSwiping.value = false; - }, listenerOptions) + useEventListener( + target, + 'pointerdown', + (e) => { + if (!eventIsAllowed(e)) return; + isPointerDown.value = true; + const eventTarget = e.target; + eventTarget == null + ? void 0 + : eventTarget.setPointerCapture(e.pointerId); + const { clientX: x, clientY: y } = e; + updatePosStart(x, y); + updatePosEnd(x, y); + onSwipeStart == null ? void 0 : onSwipeStart(e); + }, + listenerOptions + ), + useEventListener( + target, + 'pointermove', + (e) => { + if (!eventIsAllowed(e)) return; + if (!isPointerDown.value) return; + const { clientX: x, clientY: y } = e; + updatePosEnd(x, y); + if (!isSwiping.value && isThresholdExceeded.value) + isSwiping.value = true; + if (isSwiping.value) onSwipe == null ? void 0 : onSwipe(e); + }, + listenerOptions + ), + useEventListener( + target, + 'pointerup', + (e) => { + if (!eventIsAllowed(e)) return; + if (isSwiping.value) + onSwipeEnd == null ? void 0 : onSwipeEnd(e, direction.value); + isPointerDown.value = false; + isSwiping.value = false; + }, + listenerOptions + ), ]; tryOnMounted(() => { var _a, _b, _c, _d, _e, _f, _g, _h; - (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null ? void 0 : _b.setProperty("touch-action", "none"); + (_b = (_a = targetRef.value) == null ? void 0 : _a.style) == null + ? void 0 + : _b.setProperty('touch-action', 'none'); if (disableTextSelect) { - (_d = (_c = targetRef.value) == null ? void 0 : _c.style) == null ? void 0 : _d.setProperty("-webkit-user-select", "none"); - (_f = (_e = targetRef.value) == null ? void 0 : _e.style) == null ? void 0 : _f.setProperty("-ms-user-select", "none"); - (_h = (_g = targetRef.value) == null ? void 0 : _g.style) == null ? void 0 : _h.setProperty("user-select", "none"); + (_d = (_c = targetRef.value) == null ? void 0 : _c.style) == null + ? void 0 + : _d.setProperty('-webkit-user-select', 'none'); + (_f = (_e = targetRef.value) == null ? void 0 : _e.style) == null + ? void 0 + : _f.setProperty('-ms-user-select', 'none'); + (_h = (_g = targetRef.value) == null ? void 0 : _g.style) == null + ? void 0 + : _h.setProperty('user-select', 'none'); } }); const stop = () => stops.forEach((s) => s()); @@ -7235,59 +8088,59 @@ function usePointerSwipe(target, options = {}) { posEnd: readonly(posEnd), distanceX, distanceY, - stop + stop, }; } function usePreferredColorScheme(options) { - const isLight = useMediaQuery("(prefers-color-scheme: light)", options); - const isDark = useMediaQuery("(prefers-color-scheme: dark)", options); + const isLight = useMediaQuery('(prefers-color-scheme: light)', options); + const isDark = useMediaQuery('(prefers-color-scheme: dark)', options); return computed(() => { - if (isDark.value) - return "dark"; - if (isLight.value) - return "light"; - return "no-preference"; + if (isDark.value) return 'dark'; + if (isLight.value) return 'light'; + return 'no-preference'; }); } function usePreferredContrast(options) { - const isMore = useMediaQuery("(prefers-contrast: more)", options); - const isLess = useMediaQuery("(prefers-contrast: less)", options); - const isCustom = useMediaQuery("(prefers-contrast: custom)", options); + const isMore = useMediaQuery('(prefers-contrast: more)', options); + const isLess = useMediaQuery('(prefers-contrast: less)', options); + const isCustom = useMediaQuery('(prefers-contrast: custom)', options); return computed(() => { - if (isMore.value) - return "more"; - if (isLess.value) - return "less"; - if (isCustom.value) - return "custom"; - return "no-preference"; + if (isMore.value) return 'more'; + if (isLess.value) return 'less'; + if (isCustom.value) return 'custom'; + return 'no-preference'; }); } function usePreferredLanguages(options = {}) { const { window: window2 = defaultWindow } = options; - if (!window2) - return ref(["en"]); + if (!window2) return ref(['en']); const navigator2 = window2.navigator; const value = ref(navigator2.languages); - useEventListener(window2, "languagechange", () => { - value.value = navigator2.languages; - }, { passive: true }); + useEventListener( + window2, + 'languagechange', + () => { + value.value = navigator2.languages; + }, + { passive: true } + ); return value; } function usePreferredReducedMotion(options) { - const isReduced = useMediaQuery("(prefers-reduced-motion: reduce)", options); + const isReduced = useMediaQuery('(prefers-reduced-motion: reduce)', options); return computed(() => { - if (isReduced.value) - return "reduce"; - return "no-preference"; + if (isReduced.value) return 'reduce'; + return 'no-preference'; }); } function usePreferredReducedTransparency(options) { - const isReduced = useMediaQuery("(prefers-reduced-transparency: reduce)", options); + const isReduced = useMediaQuery( + '(prefers-reduced-transparency: reduce)', + options + ); return computed(() => { - if (isReduced.value) - return "reduce"; - return "no-preference"; + if (isReduced.value) return 'reduce'; + return 'no-preference'; }); } function usePrevious(value, initialValue) { @@ -7297,30 +8150,30 @@ function usePrevious(value, initialValue) { (_, oldValue) => { previous.value = oldValue; }, - { flush: "sync" } + { flush: 'sync' } ); return readonly(previous); } -var topVarName = "--vueuse-safe-area-top"; -var rightVarName = "--vueuse-safe-area-right"; -var bottomVarName = "--vueuse-safe-area-bottom"; -var leftVarName = "--vueuse-safe-area-left"; +var topVarName = '--vueuse-safe-area-top'; +var rightVarName = '--vueuse-safe-area-right'; +var bottomVarName = '--vueuse-safe-area-bottom'; +var leftVarName = '--vueuse-safe-area-left'; function useScreenSafeArea() { - const top = shallowRef(""); - const right = shallowRef(""); - const bottom = shallowRef(""); - const left = shallowRef(""); + const top = shallowRef(''); + const right = shallowRef(''); + const bottom = shallowRef(''); + const left = shallowRef(''); if (isClient) { const topCssVar = useCssVar(topVarName); const rightCssVar = useCssVar(rightVarName); const bottomCssVar = useCssVar(bottomVarName); const leftCssVar = useCssVar(leftVarName); - topCssVar.value = "env(safe-area-inset-top, 0px)"; - rightCssVar.value = "env(safe-area-inset-right, 0px)"; - bottomCssVar.value = "env(safe-area-inset-bottom, 0px)"; - leftCssVar.value = "env(safe-area-inset-left, 0px)"; + topCssVar.value = 'env(safe-area-inset-top, 0px)'; + rightCssVar.value = 'env(safe-area-inset-right, 0px)'; + bottomCssVar.value = 'env(safe-area-inset-bottom, 0px)'; + leftCssVar.value = 'env(safe-area-inset-left, 0px)'; update(); - useEventListener("resize", useDebounceFn(update), { passive: true }); + useEventListener('resize', useDebounceFn(update), { passive: true }); } function update() { top.value = getValue(topVarName); @@ -7333,7 +8186,7 @@ function useScreenSafeArea() { right, bottom, left, - update + update, }; } function getValue(position) { @@ -7343,149 +8196,145 @@ function useScriptTag(src, onLoaded = noop, options = {}) { const { immediate = true, manual = false, - type = "text/javascript", + type = 'text/javascript', async = true, crossOrigin, referrerPolicy, noModule, defer, document: document2 = defaultDocument, - attrs = {} + attrs = {}, } = options; const scriptTag = shallowRef(null); let _promise = null; - const loadScript = (waitForScriptLoad) => new Promise((resolve, reject) => { - const resolveWithElement = (el2) => { - scriptTag.value = el2; - resolve(el2); - return el2; - }; - if (!document2) { - resolve(false); - return; - } - let shouldAppend = false; - let el = document2.querySelector(`script[src="${toValue(src)}"]`); - if (!el) { - el = document2.createElement("script"); - el.type = type; - el.async = async; - el.src = toValue(src); - if (defer) - el.defer = defer; - if (crossOrigin) - el.crossOrigin = crossOrigin; - if (noModule) - el.noModule = noModule; - if (referrerPolicy) - el.referrerPolicy = referrerPolicy; - Object.entries(attrs).forEach(([name, value]) => el == null ? void 0 : el.setAttribute(name, value)); - shouldAppend = true; - } else if (el.hasAttribute("data-loaded")) { - resolveWithElement(el); - } - const listenerOptions = { - passive: true - }; - useEventListener(el, "error", (event) => reject(event), listenerOptions); - useEventListener(el, "abort", (event) => reject(event), listenerOptions); - useEventListener(el, "load", () => { - el.setAttribute("data-loaded", "true"); - onLoaded(el); - resolveWithElement(el); - }, listenerOptions); - if (shouldAppend) - el = document2.head.appendChild(el); - if (!waitForScriptLoad) - resolveWithElement(el); - }); + const loadScript = (waitForScriptLoad) => + new Promise((resolve, reject) => { + const resolveWithElement = (el2) => { + scriptTag.value = el2; + resolve(el2); + return el2; + }; + if (!document2) { + resolve(false); + return; + } + let shouldAppend = false; + let el = document2.querySelector(`script[src="${toValue(src)}"]`); + if (!el) { + el = document2.createElement('script'); + el.type = type; + el.async = async; + el.src = toValue(src); + if (defer) el.defer = defer; + if (crossOrigin) el.crossOrigin = crossOrigin; + if (noModule) el.noModule = noModule; + if (referrerPolicy) el.referrerPolicy = referrerPolicy; + Object.entries(attrs).forEach(([name, value]) => + el == null ? void 0 : el.setAttribute(name, value) + ); + shouldAppend = true; + } else if (el.hasAttribute('data-loaded')) { + resolveWithElement(el); + } + const listenerOptions = { + passive: true, + }; + useEventListener(el, 'error', (event) => reject(event), listenerOptions); + useEventListener(el, 'abort', (event) => reject(event), listenerOptions); + useEventListener( + el, + 'load', + () => { + el.setAttribute('data-loaded', 'true'); + onLoaded(el); + resolveWithElement(el); + }, + listenerOptions + ); + if (shouldAppend) el = document2.head.appendChild(el); + if (!waitForScriptLoad) resolveWithElement(el); + }); const load = (waitForScriptLoad = true) => { - if (!_promise) - _promise = loadScript(waitForScriptLoad); + if (!_promise) _promise = loadScript(waitForScriptLoad); return _promise; }; const unload = () => { - if (!document2) - return; + if (!document2) return; _promise = null; - if (scriptTag.value) - scriptTag.value = null; + if (scriptTag.value) scriptTag.value = null; const el = document2.querySelector(`script[src="${toValue(src)}"]`); - if (el) - document2.head.removeChild(el); + if (el) document2.head.removeChild(el); }; - if (immediate && !manual) - tryOnMounted(load); - if (!manual) - tryOnUnmounted(unload); + if (immediate && !manual) tryOnMounted(load); + if (!manual) tryOnUnmounted(unload); return { scriptTag, load, unload }; } function checkOverflowScroll(ele) { const style = window.getComputedStyle(ele); - if (style.overflowX === "scroll" || style.overflowY === "scroll" || style.overflowX === "auto" && ele.clientWidth < ele.scrollWidth || style.overflowY === "auto" && ele.clientHeight < ele.scrollHeight) { + if ( + style.overflowX === 'scroll' || + style.overflowY === 'scroll' || + (style.overflowX === 'auto' && ele.clientWidth < ele.scrollWidth) || + (style.overflowY === 'auto' && ele.clientHeight < ele.scrollHeight) + ) { return true; } else { const parent = ele.parentNode; - if (!parent || parent.tagName === "BODY") - return false; + if (!parent || parent.tagName === 'BODY') return false; return checkOverflowScroll(parent); } } function preventDefault(rawEvent) { const e = rawEvent || window.event; const _target = e.target; - if (checkOverflowScroll(_target)) - return false; - if (e.touches.length > 1) - return true; - if (e.preventDefault) - e.preventDefault(); + if (checkOverflowScroll(_target)) return false; + if (e.touches.length > 1) return true; + if (e.preventDefault) e.preventDefault(); return false; } var elInitialOverflow = /* @__PURE__ */ new WeakMap(); function useScrollLock(element, initialState = false) { const isLocked = shallowRef(initialState); let stopTouchMoveListener = null; - let initialOverflow = ""; - watch(toRef2(element), (el) => { - const target = resolveElement(toValue(el)); - if (target) { - const ele = target; - if (!elInitialOverflow.get(ele)) - elInitialOverflow.set(ele, ele.style.overflow); - if (ele.style.overflow !== "hidden") - initialOverflow = ele.style.overflow; - if (ele.style.overflow === "hidden") - return isLocked.value = true; - if (isLocked.value) - return ele.style.overflow = "hidden"; + let initialOverflow = ''; + watch( + toRef2(element), + (el) => { + const target = resolveElement(toValue(el)); + if (target) { + const ele = target; + if (!elInitialOverflow.get(ele)) + elInitialOverflow.set(ele, ele.style.overflow); + if (ele.style.overflow !== 'hidden') + initialOverflow = ele.style.overflow; + if (ele.style.overflow === 'hidden') return (isLocked.value = true); + if (isLocked.value) return (ele.style.overflow = 'hidden'); + } + }, + { + immediate: true, } - }, { - immediate: true - }); + ); const lock = () => { const el = resolveElement(toValue(element)); - if (!el || isLocked.value) - return; + if (!el || isLocked.value) return; if (isIOS) { stopTouchMoveListener = useEventListener( el, - "touchmove", + 'touchmove', (e) => { preventDefault(e); }, { passive: false } ); } - el.style.overflow = "hidden"; + el.style.overflow = 'hidden'; isLocked.value = true; }; const unlock = () => { const el = resolveElement(toValue(element)); - if (!el || !isLocked.value) - return; - if (isIOS) - stopTouchMoveListener == null ? void 0 : stopTouchMoveListener(); + if (!el || !isLocked.value) return; + if (isIOS) stopTouchMoveListener == null ? void 0 : stopTouchMoveListener(); el.style.overflow = initialOverflow; elInitialOverflow.delete(el); isLocked.value = false; @@ -7496,36 +8345,41 @@ function useScrollLock(element, initialState = false) { return isLocked.value; }, set(v) { - if (v) - lock(); + if (v) lock(); else unlock(); - } + }, }); } function useSessionStorage(key, initialValue, options = {}) { const { window: window2 = defaultWindow } = options; - return useStorage(key, initialValue, window2 == null ? void 0 : window2.sessionStorage, options); + return useStorage( + key, + initialValue, + window2 == null ? void 0 : window2.sessionStorage, + options + ); } function useShare(shareOptions = {}, options = {}) { const { navigator: navigator2 = defaultNavigator } = options; const _navigator = navigator2; - const isSupported = useSupported(() => _navigator && "canShare" in _navigator); + const isSupported = useSupported( + () => _navigator && 'canShare' in _navigator + ); const share = async (overrideOptions = {}) => { if (isSupported.value) { const data = { ...toValue(shareOptions), - ...toValue(overrideOptions) + ...toValue(overrideOptions), }; let granted = true; if (data.files && _navigator.canShare) granted = _navigator.canShare({ files: data.files }); - if (granted) - return _navigator.share(data); + if (granted) return _navigator.share(data); } }; return { isSupported, - share + share, }; } var defaultSortFn = (source, compareFn) => source.sort(compareFn); @@ -7536,7 +8390,7 @@ function useSorted(...args) { let compareFn = defaultCompare; let options = {}; if (args.length === 2) { - if (typeof args[1] === "object") { + if (typeof args[1] === 'object') { options = args[1]; compareFn = (_a = options.compareFn) != null ? _a : defaultCompare; } else { @@ -7546,18 +8400,12 @@ function useSorted(...args) { compareFn = (_c = args[1]) != null ? _c : defaultCompare; options = (_d = args[2]) != null ? _d : {}; } - const { - dirty = false, - sortFn = defaultSortFn - } = options; - if (!dirty) - return computed(() => sortFn([...toValue(source)], compareFn)); + const { dirty = false, sortFn = defaultSortFn } = options; + if (!dirty) return computed(() => sortFn([...toValue(source)], compareFn)); watchEffect(() => { const result = sortFn(toValue(source), compareFn); - if (isRef(source)) - source.value = result; - else - source.splice(0, source.length, ...result); + if (isRef(source)) source.value = result; + else source.splice(0, source.length, ...result); }); return source; } @@ -7566,12 +8414,12 @@ function useSpeechRecognition(options = {}) { interimResults = true, continuous = true, maxAlternatives = 1, - window: window2 = defaultWindow + window: window2 = defaultWindow, } = options; - const lang = toRef2(options.lang || "en-US"); + const lang = toRef2(options.lang || 'en-US'); const isListening = shallowRef(false); const isFinal = shallowRef(false); - const result = shallowRef(""); + const result = shallowRef(''); const error = shallowRef(void 0); let recognition; const start = () => { @@ -7587,7 +8435,8 @@ function useSpeechRecognition(options = {}) { stop(); } }; - const SpeechRecognition = window2 && (window2.SpeechRecognition || window2.webkitSpeechRecognition); + const SpeechRecognition = + window2 && (window2.SpeechRecognition || window2.webkitSpeechRecognition); const isSupported = useSupported(() => SpeechRecognition); if (isSupported.value) { recognition = new SpeechRecognition(); @@ -7600,8 +8449,7 @@ function useSpeechRecognition(options = {}) { isFinal.value = false; }; watch(lang, (lang2) => { - if (recognition && !isListening.value) - recognition.lang = lang2; + if (recognition && !isListening.value) recognition.lang = lang2; }); recognition.onresult = (event) => { const currentResult = event.results[event.resultIndex]; @@ -7618,12 +8466,9 @@ function useSpeechRecognition(options = {}) { recognition.lang = toValue(lang); }; watch(isListening, (newValue, oldValue) => { - if (newValue === oldValue) - return; - if (newValue) - recognition.start(); - else - recognition.stop(); + if (newValue === oldValue) return; + if (newValue) recognition.start(); + else recognition.stop(); }); } tryOnScopeDispose(() => { @@ -7638,7 +8483,7 @@ function useSpeechRecognition(options = {}) { error, toggle, start, - stop + stop, }; } function useSpeechSynthesis(text, options = {}) { @@ -7646,14 +8491,14 @@ function useSpeechSynthesis(text, options = {}) { pitch = 1, rate = 1, volume = 1, - window: window2 = defaultWindow + window: window2 = defaultWindow, } = options; const synth = window2 && window2.speechSynthesis; const isSupported = useSupported(() => synth); const isPlaying = shallowRef(false); - const status = shallowRef("init"); - const spokenText = toRef2(text || ""); - const lang = toRef2(options.lang || "en-US"); + const status = shallowRef('init'); + const spokenText = toRef2(text || ''); + const lang = toRef2(options.lang || 'en-US'); const error = shallowRef(void 0); const toggle = (value = !isPlaying.value) => { isPlaying.value = value; @@ -7666,19 +8511,19 @@ function useSpeechSynthesis(text, options = {}) { utterance2.volume = volume; utterance2.onstart = () => { isPlaying.value = true; - status.value = "play"; + status.value = 'play'; }; utterance2.onpause = () => { isPlaying.value = false; - status.value = "pause"; + status.value = 'pause'; }; utterance2.onresume = () => { isPlaying.value = true; - status.value = "play"; + status.value = 'play'; }; utterance2.onend = () => { isPlaying.value = false; - status.value = "end"; + status.value = 'end'; }; utterance2.onerror = (event) => { error.value = event; @@ -7686,15 +8531,14 @@ function useSpeechSynthesis(text, options = {}) { }; const utterance = computed(() => { isPlaying.value = false; - status.value = "init"; + status.value = 'init'; const newUtterance = new SpeechSynthesisUtterance(spokenText.value); bindEventsForUtterance(newUtterance); return newUtterance; }); const speak = () => { synth.cancel(); - if (utterance) - synth.speak(utterance.value); + if (utterance) synth.speak(utterance.value); }; const stop = () => { synth.cancel(); @@ -7703,8 +8547,7 @@ function useSpeechSynthesis(text, options = {}) { if (isSupported.value) { bindEventsForUtterance(utterance.value); watch(lang, (lang2) => { - if (utterance.value && !isPlaying.value) - utterance.value.lang = lang2; + if (utterance.value && !isPlaying.value) utterance.value.lang = lang2; }); if (options.voice) { watch(options.voice, () => { @@ -7712,10 +8555,8 @@ function useSpeechSynthesis(text, options = {}) { }); } watch(isPlaying, () => { - if (isPlaying.value) - synth.resume(); - else - synth.pause(); + if (isPlaying.value) synth.resume(); + else synth.pause(); }); } tryOnScopeDispose(() => { @@ -7729,26 +8570,30 @@ function useSpeechSynthesis(text, options = {}) { error, stop, toggle, - speak + speak, }; } function useStepper(steps, initialStep) { const stepsRef = ref(steps); - const stepNames = computed(() => Array.isArray(stepsRef.value) ? stepsRef.value : Object.keys(stepsRef.value)); - const index = ref(stepNames.value.indexOf(initialStep != null ? initialStep : stepNames.value[0])); + const stepNames = computed(() => + Array.isArray(stepsRef.value) ? stepsRef.value : Object.keys(stepsRef.value) + ); + const index = ref( + stepNames.value.indexOf( + initialStep != null ? initialStep : stepNames.value[0] + ) + ); const current = computed(() => at(index.value)); const isFirst = computed(() => index.value === 0); const isLast = computed(() => index.value === stepNames.value.length - 1); const next = computed(() => stepNames.value[index.value + 1]); const previous = computed(() => stepNames.value[index.value - 1]); function at(index2) { - if (Array.isArray(stepsRef.value)) - return stepsRef.value[index2]; + if (Array.isArray(stepsRef.value)) return stepsRef.value[index2]; return stepsRef.value[stepNames.value[index2]]; } function get2(step) { - if (!stepNames.value.includes(step)) - return; + if (!stepNames.value.includes(step)) return; return at(stepNames.value.indexOf(step)); } function goTo(step) { @@ -7756,18 +8601,15 @@ function useStepper(steps, initialStep) { index.value = stepNames.value.indexOf(step); } function goToNext() { - if (isLast.value) - return; + if (isLast.value) return; index.value++; } function goToPrevious() { - if (isFirst.value) - return; + if (isFirst.value) return; index.value--; } function goBackTo(step) { - if (isAfter(step)) - goTo(step); + if (isAfter(step)) goTo(step); } function isNext(step) { return stepNames.value.indexOf(step) === index.value + 1; @@ -7803,13 +8645,13 @@ function useStepper(steps, initialStep) { isPrevious, isCurrent, isBefore, - isAfter + isAfter, }; } function useStorageAsync(key, initialValue, storage, options = {}) { var _a; const { - flush = "pre", + flush = 'pre', deep = true, listenToStorageChanges = true, writeDefaults = true, @@ -7819,15 +8661,16 @@ function useStorageAsync(key, initialValue, storage, options = {}) { eventFilter, onError = (e) => { console.error(e); - } + }, } = options; const rawInit = toValue(initialValue); const type = guessSerializerType(rawInit); const data = (shallow ? shallowRef : ref)(toValue(initialValue)); - const serializer = (_a = options.serializer) != null ? _a : StorageSerializers[type]; + const serializer = + (_a = options.serializer) != null ? _a : StorageSerializers[type]; if (!storage) { try { - storage = getSSRHandler("getDefaultStorageAsync", () => { + storage = getSSRHandler('getDefaultStorageAsync', () => { var _a2; return (_a2 = defaultWindow) == null ? void 0 : _a2.localStorage; })(); @@ -7836,8 +8679,7 @@ function useStorageAsync(key, initialValue, storage, options = {}) { } } async function read(event) { - if (!storage || event && event.key !== key) - return; + if (!storage || (event && event.key !== key)) return; try { const rawValue = event ? event.newValue : await storage.getItem(key); if (rawValue == null) { @@ -7846,9 +8688,9 @@ function useStorageAsync(key, initialValue, storage, options = {}) { await storage.setItem(key, await serializer.write(rawInit)); } else if (mergeDefaults) { const value = await serializer.read(rawValue); - if (typeof mergeDefaults === "function") + if (typeof mergeDefaults === 'function') data.value = mergeDefaults(value, rawInit); - else if (type === "object" && !Array.isArray(value)) + else if (type === 'object' && !Array.isArray(value)) data.value = { ...rawInit, ...value }; else data.value = value; } else { @@ -7860,16 +8702,19 @@ function useStorageAsync(key, initialValue, storage, options = {}) { } read(); if (window2 && listenToStorageChanges) - useEventListener(window2, "storage", (e) => Promise.resolve().then(() => read(e)), { passive: true }); + useEventListener( + window2, + 'storage', + (e) => Promise.resolve().then(() => read(e)), + { passive: true } + ); if (storage) { watchWithFilter( data, async () => { try { - if (data.value == null) - await storage.removeItem(key); - else - await storage.setItem(key, await serializer.write(data.value)); + if (data.value == null) await storage.removeItem(key); + else await storage.setItem(key, await serializer.write(data.value)); } catch (e) { onError(e); } @@ -7877,7 +8722,7 @@ function useStorageAsync(key, initialValue, storage, options = {}) { { flush, deep, - eventFilter + eventFilter, } ); } @@ -7890,23 +8735,19 @@ function useStyleTag(css, options = {}) { document: document2 = defaultDocument, immediate = true, manual = false, - id = `vueuse_styletag_${++_id}` + id = `vueuse_styletag_${++_id}`, } = options; const cssRef = shallowRef(css); - let stop = () => { - }; + let stop = () => {}; const load = () => { - if (!document2) - return; - const el = document2.getElementById(id) || document2.createElement("style"); + if (!document2) return; + const el = document2.getElementById(id) || document2.createElement('style'); if (!el.isConnected) { el.id = id; - if (options.media) - el.media = options.media; + if (options.media) el.media = options.media; document2.head.appendChild(el); } - if (isLoaded.value) - return; + if (isLoaded.value) return; stop = watch( cssRef, (value) => { @@ -7917,22 +8758,19 @@ function useStyleTag(css, options = {}) { isLoaded.value = true; }; const unload = () => { - if (!document2 || !isLoaded.value) - return; + if (!document2 || !isLoaded.value) return; stop(); document2.head.removeChild(document2.getElementById(id)); isLoaded.value = false; }; - if (immediate && !manual) - tryOnMounted(load); - if (!manual) - tryOnScopeDispose(unload); + if (immediate && !manual) tryOnMounted(load); + if (!manual) tryOnScopeDispose(unload); return { id, css: cssRef, unload, load, - isLoaded: readonly(isLoaded) + isLoaded: readonly(isLoaded), }; } function useSwipe(target, options = {}) { @@ -7941,25 +8779,29 @@ function useSwipe(target, options = {}) { onSwipe, onSwipeEnd, onSwipeStart, - passive = true + passive = true, } = options; const coordsStart = reactive({ x: 0, y: 0 }); const coordsEnd = reactive({ x: 0, y: 0 }); const diffX = computed(() => coordsStart.x - coordsEnd.x); const diffY = computed(() => coordsStart.y - coordsEnd.y); const { max, abs } = Math; - const isThresholdExceeded = computed(() => max(abs(diffX.value), abs(diffY.value)) >= threshold); + const isThresholdExceeded = computed( + () => max(abs(diffX.value), abs(diffY.value)) >= threshold + ); const isSwiping = shallowRef(false); const direction = computed(() => { - if (!isThresholdExceeded.value) - return "none"; + if (!isThresholdExceeded.value) return 'none'; if (abs(diffX.value) > abs(diffY.value)) { - return diffX.value > 0 ? "left" : "right"; + return diffX.value > 0 ? 'left' : 'right'; } else { - return diffY.value > 0 ? "up" : "down"; + return diffY.value > 0 ? 'up' : 'down'; } }); - const getTouchEventCoords = (e) => [e.touches[0].clientX, e.touches[0].clientY]; + const getTouchEventCoords = (e) => [ + e.touches[0].clientX, + e.touches[0].clientY, + ]; const updateCoordsStart = (x, y) => { coordsStart.x = x; coordsStart.y = y; @@ -7975,27 +8817,43 @@ function useSwipe(target, options = {}) { isSwiping.value = false; }; const stops = [ - useEventListener(target, "touchstart", (e) => { - if (e.touches.length !== 1) - return; - const [x, y] = getTouchEventCoords(e); - updateCoordsStart(x, y); - updateCoordsEnd(x, y); - onSwipeStart == null ? void 0 : onSwipeStart(e); - }, listenerOptions), - useEventListener(target, "touchmove", (e) => { - if (e.touches.length !== 1) - return; - const [x, y] = getTouchEventCoords(e); - updateCoordsEnd(x, y); - if (listenerOptions.capture && !listenerOptions.passive && Math.abs(diffX.value) > Math.abs(diffY.value)) - e.preventDefault(); - if (!isSwiping.value && isThresholdExceeded.value) - isSwiping.value = true; - if (isSwiping.value) - onSwipe == null ? void 0 : onSwipe(e); - }, listenerOptions), - useEventListener(target, ["touchend", "touchcancel"], onTouchEnd, listenerOptions) + useEventListener( + target, + 'touchstart', + (e) => { + if (e.touches.length !== 1) return; + const [x, y] = getTouchEventCoords(e); + updateCoordsStart(x, y); + updateCoordsEnd(x, y); + onSwipeStart == null ? void 0 : onSwipeStart(e); + }, + listenerOptions + ), + useEventListener( + target, + 'touchmove', + (e) => { + if (e.touches.length !== 1) return; + const [x, y] = getTouchEventCoords(e); + updateCoordsEnd(x, y); + if ( + listenerOptions.capture && + !listenerOptions.passive && + Math.abs(diffX.value) > Math.abs(diffY.value) + ) + e.preventDefault(); + if (!isSwiping.value && isThresholdExceeded.value) + isSwiping.value = true; + if (isSwiping.value) onSwipe == null ? void 0 : onSwipe(e); + }, + listenerOptions + ), + useEventListener( + target, + ['touchend', 'touchcancel'], + onTouchEnd, + listenerOptions + ), ]; const stop = () => stops.forEach((s) => s()); return { @@ -8007,14 +8865,13 @@ function useSwipe(target, options = {}) { lengthY: diffY, stop, // TODO: Remove in the next major version - isPassiveEventSupported: true + isPassiveEventSupported: true, }; } function useTemplateRefsList() { const refs = ref([]); refs.value.set = (el) => { - if (el) - refs.value.push(el); + if (el) refs.value.push(el); }; onBeforeUpdate(() => { refs.value.length = 0; @@ -8024,20 +8881,26 @@ function useTemplateRefsList() { function useTextDirection(options = {}) { const { document: document2 = defaultDocument, - selector = "html", + selector = 'html', observe = false, - initialValue = "ltr" + initialValue = 'ltr', } = options; function getValue2() { var _a, _b; - return (_b = (_a = document2 == null ? void 0 : document2.querySelector(selector)) == null ? void 0 : _a.getAttribute("dir")) != null ? _b : initialValue; + return (_b = + (_a = document2 == null ? void 0 : document2.querySelector(selector)) == + null + ? void 0 + : _a.getAttribute('dir')) != null + ? _b + : initialValue; } const dir = ref(getValue2()); - tryOnMounted(() => dir.value = getValue2()); + tryOnMounted(() => (dir.value = getValue2())); if (observe && document2) { useMutationObserver( document2.querySelector(selector), - () => dir.value = getValue2(), + () => (dir.value = getValue2()), { attributes: true } ); } @@ -8048,13 +8911,16 @@ function useTextDirection(options = {}) { set(v) { var _a, _b; dir.value = v; - if (!document2) - return; + if (!document2) return; if (dir.value) - (_a = document2.querySelector(selector)) == null ? void 0 : _a.setAttribute("dir", dir.value); + (_a = document2.querySelector(selector)) == null + ? void 0 + : _a.setAttribute('dir', dir.value); else - (_b = document2.querySelector(selector)) == null ? void 0 : _b.removeAttribute("dir"); - } + (_b = document2.querySelector(selector)) == null + ? void 0 + : _b.removeAttribute('dir'); + }, }); } function getRangesFromSelection(selection) { @@ -8063,32 +8929,38 @@ function getRangesFromSelection(selection) { return Array.from({ length: rangeCount }, (_, i) => selection.getRangeAt(i)); } function useTextSelection(options = {}) { - const { - window: window2 = defaultWindow - } = options; + const { window: window2 = defaultWindow } = options; const selection = ref(null); const text = computed(() => { var _a, _b; - return (_b = (_a = selection.value) == null ? void 0 : _a.toString()) != null ? _b : ""; + return (_b = (_a = selection.value) == null ? void 0 : _a.toString()) != + null + ? _b + : ''; }); - const ranges = computed(() => selection.value ? getRangesFromSelection(selection.value) : []); - const rects = computed(() => ranges.value.map((range) => range.getBoundingClientRect())); + const ranges = computed(() => + selection.value ? getRangesFromSelection(selection.value) : [] + ); + const rects = computed(() => + ranges.value.map((range) => range.getBoundingClientRect()) + ); function onSelectionChange() { selection.value = null; - if (window2) - selection.value = window2.getSelection(); + if (window2) selection.value = window2.getSelection(); } if (window2) - useEventListener(window2.document, "selectionchange", onSelectionChange, { passive: true }); + useEventListener(window2.document, 'selectionchange', onSelectionChange, { + passive: true, + }); return { text, rects, ranges, - selection + selection, }; } function tryRequestAnimationFrame(window2 = defaultWindow, fn) { - if (window2 && typeof window2.requestAnimationFrame === "function") { + if (window2 && typeof window2.requestAnimationFrame === 'function') { window2.requestAnimationFrame(fn); } else { fn(); @@ -8098,32 +8970,37 @@ function useTextareaAutosize(options = {}) { var _a, _b; const { window: window2 = defaultWindow } = options; const textarea = toRef2(options == null ? void 0 : options.element); - const input = toRef2((_a = options == null ? void 0 : options.input) != null ? _a : ""); - const styleProp = (_b = options == null ? void 0 : options.styleProp) != null ? _b : "height"; + const input = toRef2( + (_a = options == null ? void 0 : options.input) != null ? _a : '' + ); + const styleProp = + (_b = options == null ? void 0 : options.styleProp) != null ? _b : 'height'; const textareaScrollHeight = shallowRef(1); const textareaOldWidth = shallowRef(0); function triggerResize() { var _a2; - if (!textarea.value) - return; - let height = ""; - textarea.value.style[styleProp] = "1px"; - textareaScrollHeight.value = (_a2 = textarea.value) == null ? void 0 : _a2.scrollHeight; - const _styleTarget = toValue(options == null ? void 0 : options.styleTarget); + if (!textarea.value) return; + let height = ''; + textarea.value.style[styleProp] = '1px'; + textareaScrollHeight.value = + (_a2 = textarea.value) == null ? void 0 : _a2.scrollHeight; + const _styleTarget = toValue( + options == null ? void 0 : options.styleTarget + ); if (_styleTarget) _styleTarget.style[styleProp] = `${textareaScrollHeight.value}px`; - else - height = `${textareaScrollHeight.value}px`; + else height = `${textareaScrollHeight.value}px`; textarea.value.style[styleProp] = height; } watch([input, textarea], () => nextTick(triggerResize), { immediate: true }); watch(textareaScrollHeight, () => { var _a2; - return (_a2 = options == null ? void 0 : options.onResize) == null ? void 0 : _a2.call(options); + return (_a2 = options == null ? void 0 : options.onResize) == null + ? void 0 + : _a2.call(options); }); useResizeObserver(textarea, ([{ contentRect }]) => { - if (textareaOldWidth.value === contentRect.width) - return; + if (textareaOldWidth.value === contentRect.width) return; tryRequestAnimationFrame(window2, () => { textareaOldWidth.value = contentRect.width; triggerResize(); @@ -8134,7 +9011,7 @@ function useTextareaAutosize(options = {}) { return { textarea, input, - triggerResize + triggerResize, }; } function useThrottledRefHistory(source, options = {}) { @@ -8142,45 +9019,63 @@ function useThrottledRefHistory(source, options = {}) { const filter = throttleFilter(throttle, trailing); const history = useRefHistory(source, { ...options, eventFilter: filter }); return { - ...history + ...history, }; } var DEFAULT_UNITS = [ - { max: 6e4, value: 1e3, name: "second" }, - { max: 276e4, value: 6e4, name: "minute" }, - { max: 72e6, value: 36e5, name: "hour" }, - { max: 5184e5, value: 864e5, name: "day" }, - { max: 24192e5, value: 6048e5, name: "week" }, - { max: 28512e6, value: 2592e6, name: "month" }, - { max: Number.POSITIVE_INFINITY, value: 31536e6, name: "year" } + { max: 6e4, value: 1e3, name: 'second' }, + { max: 276e4, value: 6e4, name: 'minute' }, + { max: 72e6, value: 36e5, name: 'hour' }, + { max: 5184e5, value: 864e5, name: 'day' }, + { max: 24192e5, value: 6048e5, name: 'week' }, + { max: 28512e6, value: 2592e6, name: 'month' }, + { max: Number.POSITIVE_INFINITY, value: 31536e6, name: 'year' }, ]; var DEFAULT_MESSAGES = { - justNow: "just now", - past: (n) => n.match(/\d/) ? `${n} ago` : n, - future: (n) => n.match(/\d/) ? `in ${n}` : n, - month: (n, past) => n === 1 ? past ? "last month" : "next month" : `${n} month${n > 1 ? "s" : ""}`, - year: (n, past) => n === 1 ? past ? "last year" : "next year" : `${n} year${n > 1 ? "s" : ""}`, - day: (n, past) => n === 1 ? past ? "yesterday" : "tomorrow" : `${n} day${n > 1 ? "s" : ""}`, - week: (n, past) => n === 1 ? past ? "last week" : "next week" : `${n} week${n > 1 ? "s" : ""}`, - hour: (n) => `${n} hour${n > 1 ? "s" : ""}`, - minute: (n) => `${n} minute${n > 1 ? "s" : ""}`, - second: (n) => `${n} second${n > 1 ? "s" : ""}`, - invalid: "" + justNow: 'just now', + past: (n) => (n.match(/\d/) ? `${n} ago` : n), + future: (n) => (n.match(/\d/) ? `in ${n}` : n), + month: (n, past) => + n === 1 + ? past + ? 'last month' + : 'next month' + : `${n} month${n > 1 ? 's' : ''}`, + year: (n, past) => + n === 1 + ? past + ? 'last year' + : 'next year' + : `${n} year${n > 1 ? 's' : ''}`, + day: (n, past) => + n === 1 ? (past ? 'yesterday' : 'tomorrow') : `${n} day${n > 1 ? 's' : ''}`, + week: (n, past) => + n === 1 + ? past + ? 'last week' + : 'next week' + : `${n} week${n > 1 ? 's' : ''}`, + hour: (n) => `${n} hour${n > 1 ? 's' : ''}`, + minute: (n) => `${n} minute${n > 1 ? 's' : ''}`, + second: (n) => `${n} second${n > 1 ? 's' : ''}`, + invalid: '', }; function DEFAULT_FORMATTER(date) { return date.toISOString().slice(0, 10); } function useTimeAgo(time, options = {}) { - const { - controls: exposeControls = false, - updateInterval = 3e4 - } = options; - const { now: now2, ...controls } = useNow({ interval: updateInterval, controls: true }); - const timeAgo = computed(() => formatTimeAgo(new Date(toValue(time)), options, toValue(now2))); + const { controls: exposeControls = false, updateInterval = 3e4 } = options; + const { now: now2, ...controls } = useNow({ + interval: updateInterval, + controls: true, + }); + const timeAgo = computed(() => + formatTimeAgo(new Date(toValue(time)), options, toValue(now2)) + ); if (exposeControls) { return { timeAgo, - ...controls + ...controls, }; } else { return timeAgo; @@ -8194,9 +9089,10 @@ function formatTimeAgo(from, options = {}, now2 = Date.now()) { fullDateFormatter = DEFAULT_FORMATTER, units = DEFAULT_UNITS, showSecond = false, - rounding = "round" + rounding = 'round', } = options; - const roundFn = typeof rounding === "number" ? (n) => +n.toFixed(rounding) : Math[rounding]; + const roundFn = + typeof rounding === 'number' ? (n) => +n.toFixed(rounding) : Math[rounding]; const diff = +now2 - +from; const absDiff = Math.abs(diff); function getValue2(diff2, unit) { @@ -8206,63 +9102,53 @@ function formatTimeAgo(from, options = {}, now2 = Date.now()) { const val = getValue2(diff2, unit); const past = diff2 > 0; const str = applyFormat(unit.name, val, past); - return applyFormat(past ? "past" : "future", str, past); + return applyFormat(past ? 'past' : 'future', str, past); } function applyFormat(name, val, isPast) { const formatter = messages[name]; - if (typeof formatter === "function") - return formatter(val, isPast); - return formatter.replace("{0}", val.toString()); + if (typeof formatter === 'function') return formatter(val, isPast); + return formatter.replace('{0}', val.toString()); } - if (absDiff < 6e4 && !showSecond) - return messages.justNow; - if (typeof max === "number" && absDiff > max) + if (absDiff < 6e4 && !showSecond) return messages.justNow; + if (typeof max === 'number' && absDiff > max) return fullDateFormatter(new Date(from)); - if (typeof max === "string") { - const unitMax = (_a = units.find((i) => i.name === max)) == null ? void 0 : _a.max; - if (unitMax && absDiff > unitMax) - return fullDateFormatter(new Date(from)); + if (typeof max === 'string') { + const unitMax = + (_a = units.find((i) => i.name === max)) == null ? void 0 : _a.max; + if (unitMax && absDiff > unitMax) return fullDateFormatter(new Date(from)); } for (const [idx, unit] of units.entries()) { const val = getValue2(diff, unit); - if (val <= 0 && units[idx - 1]) - return format(diff, units[idx - 1]); - if (absDiff < unit.max) - return format(diff, unit); + if (val <= 0 && units[idx - 1]) return format(diff, units[idx - 1]); + if (absDiff < unit.max) return format(diff, unit); } return messages.invalid; } function useTimeoutPoll(fn, interval, options = {}) { - const { - immediate = true, - immediateCallback = false - } = options; + const { immediate = true, immediateCallback = false } = options; const { start } = useTimeoutFn(loop, interval, { immediate }); const isActive = shallowRef(false); async function loop() { - if (!isActive.value) - return; + if (!isActive.value) return; await fn(); start(); } function resume() { if (!isActive.value) { isActive.value = true; - if (immediateCallback) - fn(); + if (immediateCallback) fn(); start(); } } function pause() { isActive.value = false; } - if (immediate && isClient) - resume(); + if (immediate && isClient) resume(); tryOnScopeDispose(pause); return { isActive, pause, - resume + resume, }; } function useTimestamp(options = {}) { @@ -8270,20 +9156,25 @@ function useTimestamp(options = {}) { controls: exposeControls = false, offset = 0, immediate = true, - interval = "requestAnimationFrame", - callback + interval = 'requestAnimationFrame', + callback, } = options; const ts = shallowRef(timestamp() + offset); - const update = () => ts.value = timestamp() + offset; - const cb = callback ? () => { - update(); - callback(ts.value); - } : update; - const controls = interval === "requestAnimationFrame" ? useRafFn(cb, { immediate }) : useIntervalFn(cb, interval, { immediate }); + const update = () => (ts.value = timestamp() + offset); + const cb = callback + ? () => { + update(); + callback(ts.value); + } + : update; + const controls = + interval === 'requestAnimationFrame' + ? useRafFn(cb, { immediate }) + : useIntervalFn(cb, interval, { immediate }); if (exposeControls) { return { timestamp: ts, - ...controls + ...controls, }; } else { return ts; @@ -8291,30 +9182,39 @@ function useTimestamp(options = {}) { } function useTitle(newTitle = null, options = {}) { var _a, _b, _c; - const { - document: document2 = defaultDocument, - restoreOnUnmount = (t) => t - } = options; - const originalTitle = (_a = document2 == null ? void 0 : document2.title) != null ? _a : ""; - const title = toRef2((_b = newTitle != null ? newTitle : document2 == null ? void 0 : document2.title) != null ? _b : null); - const isReadonly2 = !!(newTitle && typeof newTitle === "function"); + const { document: document2 = defaultDocument, restoreOnUnmount = (t) => t } = + options; + const originalTitle = + (_a = document2 == null ? void 0 : document2.title) != null ? _a : ''; + const title = toRef2( + (_b = + newTitle != null + ? newTitle + : document2 == null + ? void 0 + : document2.title) != null + ? _b + : null + ); + const isReadonly2 = !!(newTitle && typeof newTitle === 'function'); function format(t) { - if (!("titleTemplate" in options)) - return t; - const template = options.titleTemplate || "%s"; - return typeof template === "function" ? template(t) : toValue(template).replace(/%s/g, t); + if (!('titleTemplate' in options)) return t; + const template = options.titleTemplate || '%s'; + return typeof template === 'function' + ? template(t) + : toValue(template).replace(/%s/g, t); } watch( title, (newValue, oldValue) => { if (newValue !== oldValue && document2) - document2.title = format(newValue != null ? newValue : ""); + document2.title = format(newValue != null ? newValue : ''); }, { immediate: true } ); if (options.observe && !options.titleTemplate && document2 && !isReadonly2) { useMutationObserver( - (_c = document2.head) == null ? void 0 : _c.querySelector("title"), + (_c = document2.head) == null ? void 0 : _c.querySelector('title'), () => { if (document2 && document2.title !== title.value) title.value = format(document2.title); @@ -8324,9 +9224,8 @@ function useTitle(newTitle = null, options = {}) { } tryOnScopeDispose(() => { if (restoreOnUnmount) { - const restoredTitle = restoreOnUnmount(originalTitle, title.value || ""); - if (restoredTitle != null && document2) - document2.title = restoredTitle; + const restoredTitle = restoreOnUnmount(originalTitle, title.value || ''); + if (restoredTitle != null && document2) document2.title = restoredTitle; } }); return title; @@ -8355,33 +9254,38 @@ var _TransitionPresets = { easeInOutCirc: [0.85, 0, 0.15, 1], easeInBack: [0.36, 0, 0.66, -0.56], easeOutBack: [0.34, 1.56, 0.64, 1], - easeInOutBack: [0.68, -0.6, 0.32, 1.6] + easeInOutBack: [0.68, -0.6, 0.32, 1.6], }; -var TransitionPresets = Object.assign({}, { linear: identity }, _TransitionPresets); +var TransitionPresets = Object.assign( + {}, + { linear: identity }, + _TransitionPresets +); function createEasingFunction([p0, p1, p2, p3]) { const a = (a1, a2) => 1 - 3 * a2 + 3 * a1; const b = (a1, a2) => 3 * a2 - 6 * a1; const c = (a1) => 3 * a1; - const calcBezier = (t, a1, a2) => ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; - const getSlope = (t, a1, a2) => 3 * a(a1, a2) * t * t + 2 * b(a1, a2) * t + c(a1); + const calcBezier = (t, a1, a2) => + ((a(a1, a2) * t + b(a1, a2)) * t + c(a1)) * t; + const getSlope = (t, a1, a2) => + 3 * a(a1, a2) * t * t + 2 * b(a1, a2) * t + c(a1); const getTforX = (x) => { let aGuessT = x; for (let i = 0; i < 4; ++i) { const currentSlope = getSlope(aGuessT, p0, p2); - if (currentSlope === 0) - return aGuessT; + if (currentSlope === 0) return aGuessT; const currentX = calcBezier(aGuessT, p0, p2) - x; aGuessT -= currentX / currentSlope; } return aGuessT; }; - return (x) => p0 === p1 && p2 === p3 ? x : calcBezier(getTforX(x), p1, p3); + return (x) => (p0 === p1 && p2 === p3 ? x : calcBezier(getTforX(x), p1, p3)); } function lerp(a, b, alpha) { return a + alpha * (b - a); } function toVec(t) { - return (typeof t === "number" ? [t] : t) || []; + return (typeof t === 'number' ? [t] : t) || []; } function executeTransition(source, from, to, options = {}) { var _a, _b; @@ -8392,8 +9296,14 @@ function executeTransition(source, from, to, options = {}) { const duration = (_a = toValue(options.duration)) != null ? _a : 1e3; const startedAt = Date.now(); const endAt = Date.now() + duration; - const trans = typeof options.transition === "function" ? options.transition : (_b = toValue(options.transition)) != null ? _b : identity; - const ease = typeof trans === "function" ? trans : createEasingFunction(trans); + const trans = + typeof options.transition === 'function' + ? options.transition + : (_b = toValue(options.transition)) != null + ? _b + : identity; + const ease = + typeof trans === 'function' ? trans : createEasingFunction(trans); return new Promise((resolve) => { source.value = fromVal; const tick = () => { @@ -8408,10 +9318,13 @@ function executeTransition(source, from, to, options = {}) { if (Array.isArray(source.value)) source.value = arr.map((n, i) => { var _a3, _b2; - return lerp((_a3 = v1[i]) != null ? _a3 : 0, (_b2 = v2[i]) != null ? _b2 : 0, alpha); + return lerp( + (_a3 = v1[i]) != null ? _a3 : 0, + (_b2 = v2[i]) != null ? _b2 : 0, + alpha + ); }); - else if (typeof source.value === "number") - source.value = arr[0]; + else if (typeof source.value === 'number') source.value = arr[0]; if (now2 < endAt) { requestAnimationFrame(tick); } else { @@ -8426,74 +9339,82 @@ function useTransition(source, options = {}) { let currentId = 0; const sourceVal = () => { const v = toValue(source); - return typeof v === "number" ? v : v.map(toValue); + return typeof v === 'number' ? v : v.map(toValue); }; const outputRef = ref(sourceVal()); - watch(sourceVal, async (to) => { - var _a, _b; - if (toValue(options.disabled)) - return; - const id = ++currentId; - if (options.delay) - await promiseTimeout(toValue(options.delay)); - if (id !== currentId) - return; - const toVal = Array.isArray(to) ? to.map(toValue) : toValue(to); - (_a = options.onStarted) == null ? void 0 : _a.call(options); - await executeTransition(outputRef, outputRef.value, toVal, { - ...options, - abort: () => { - var _a2; - return id !== currentId || ((_a2 = options.abort) == null ? void 0 : _a2.call(options)); + watch( + sourceVal, + async (to) => { + var _a, _b; + if (toValue(options.disabled)) return; + const id = ++currentId; + if (options.delay) await promiseTimeout(toValue(options.delay)); + if (id !== currentId) return; + const toVal = Array.isArray(to) ? to.map(toValue) : toValue(to); + (_a = options.onStarted) == null ? void 0 : _a.call(options); + await executeTransition(outputRef, outputRef.value, toVal, { + ...options, + abort: () => { + var _a2; + return ( + id !== currentId || + ((_a2 = options.abort) == null ? void 0 : _a2.call(options)) + ); + }, + }); + (_b = options.onFinished) == null ? void 0 : _b.call(options); + }, + { deep: true } + ); + watch( + () => toValue(options.disabled), + (disabled) => { + if (disabled) { + currentId++; + outputRef.value = sourceVal(); } - }); - (_b = options.onFinished) == null ? void 0 : _b.call(options); - }, { deep: true }); - watch(() => toValue(options.disabled), (disabled) => { - if (disabled) { - currentId++; - outputRef.value = sourceVal(); } - }); + ); tryOnScopeDispose(() => { currentId++; }); - return computed(() => toValue(options.disabled) ? sourceVal() : outputRef.value); + return computed(() => + toValue(options.disabled) ? sourceVal() : outputRef.value + ); } -function useUrlSearchParams(mode = "history", options = {}) { +function useUrlSearchParams(mode = 'history', options = {}) { const { initialValue = {}, removeNullishValues = true, removeFalsyValues = false, write: enableWrite = true, - writeMode = "replace", - window: window2 = defaultWindow + writeMode = 'replace', + window: window2 = defaultWindow, } = options; - if (!window2) - return reactive(initialValue); + if (!window2) return reactive(initialValue); const state = reactive({}); function getRawParams() { - if (mode === "history") { - return window2.location.search || ""; - } else if (mode === "hash") { - const hash = window2.location.hash || ""; - const index = hash.indexOf("?"); - return index > 0 ? hash.slice(index) : ""; + if (mode === 'history') { + return window2.location.search || ''; + } else if (mode === 'hash') { + const hash = window2.location.hash || ''; + const index = hash.indexOf('?'); + return index > 0 ? hash.slice(index) : ''; } else { - return (window2.location.hash || "").replace(/^#/, ""); + return (window2.location.hash || '').replace(/^#/, ''); } } function constructQuery(params) { const stringified = params.toString(); - if (mode === "history") - return `${stringified ? `?${stringified}` : ""}${window2.location.hash || ""}`; - if (mode === "hash-params") - return `${window2.location.search || ""}${stringified ? `#${stringified}` : ""}`; - const hash = window2.location.hash || "#"; - const index = hash.indexOf("?"); + if (mode === 'history') + return `${stringified ? `?${stringified}` : ''}${window2.location.hash || ''}`; + if (mode === 'hash-params') + return `${window2.location.search || ''}${stringified ? `#${stringified}` : ''}`; + const hash = window2.location.hash || '#'; + const index = hash.indexOf('?'); if (index > 0) - return `${window2.location.search || ""}${hash.slice(0, index)}${stringified ? `?${stringified}` : ""}`; - return `${window2.location.search || ""}${hash}${stringified ? `?${stringified}` : ""}`; + return `${window2.location.search || ''}${hash.slice(0, index)}${stringified ? `?${stringified}` : ''}`; + return `${window2.location.search || ''}${hash}${stringified ? `?${stringified}` : ''}`; } function read() { return new URLSearchParams(getRawParams()); @@ -8502,7 +9423,8 @@ function useUrlSearchParams(mode = "history", options = {}) { const unusedKeys = new Set(Object.keys(state)); for (const key of params.keys()) { const paramsForKey = params.getAll(key); - state[key] = paramsForKey.length > 1 ? paramsForKey : params.get(key) || ""; + state[key] = + paramsForKey.length > 1 ? paramsForKey : params.get(key) || ''; unusedKeys.delete(key); } Array.from(unusedKeys).forEach((key) => delete state[key]); @@ -8510,17 +9432,14 @@ function useUrlSearchParams(mode = "history", options = {}) { const { pause, resume } = watchPausable( state, () => { - const params = new URLSearchParams(""); + const params = new URLSearchParams(''); Object.keys(state).forEach((key) => { const mapEntry = state[key]; if (Array.isArray(mapEntry)) mapEntry.forEach((value) => params.append(key, value)); - else if (removeNullishValues && mapEntry == null) - params.delete(key); - else if (removeFalsyValues && !mapEntry) - params.delete(key); - else - params.set(key, mapEntry); + else if (removeNullishValues && mapEntry == null) params.delete(key); + else if (removeFalsyValues && !mapEntry) params.delete(key); + else params.set(key, mapEntry); }); write(params, false); }, @@ -8528,9 +9447,8 @@ function useUrlSearchParams(mode = "history", options = {}) { ); function write(params, shouldUpdate) { pause(); - if (shouldUpdate) - updateState(params); - if (writeMode === "replace") { + if (shouldUpdate) updateState(params); + if (writeMode === 'replace') { window2.history.replaceState( window2.history.state, window2.document.title, @@ -8546,19 +9464,16 @@ function useUrlSearchParams(mode = "history", options = {}) { resume(); } function onChanged() { - if (!enableWrite) - return; + if (!enableWrite) return; write(read(), true); } const listenerOptions = { passive: true }; - useEventListener(window2, "popstate", onChanged, listenerOptions); - if (mode !== "history") - useEventListener(window2, "hashchange", onChanged, listenerOptions); + useEventListener(window2, 'popstate', onChanged, listenerOptions); + if (mode !== 'history') + useEventListener(window2, 'hashchange', onChanged, listenerOptions); const initial = read(); - if (initial.keys().next().value) - updateState(initial); - else - Object.assign(state, initialValue); + if (initial.keys().next().value) updateState(initial); + else Object.assign(state, initialValue); return state; } function useUserMedia(options = {}) { @@ -8569,35 +9484,36 @@ function useUserMedia(options = {}) { const { navigator: navigator2 = defaultNavigator } = options; const isSupported = useSupported(() => { var _a2; - return (_a2 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null ? void 0 : _a2.getUserMedia; + return (_a2 = navigator2 == null ? void 0 : navigator2.mediaDevices) == null + ? void 0 + : _a2.getUserMedia; }); const stream = shallowRef(); function getDeviceOptions(type) { switch (type) { - case "video": { - if (constraints.value) - return constraints.value.video || false; + case 'video': { + if (constraints.value) return constraints.value.video || false; break; } - case "audio": { - if (constraints.value) - return constraints.value.audio || false; + case 'audio': { + if (constraints.value) return constraints.value.audio || false; break; } } } async function _start() { - if (!isSupported.value || stream.value) - return; + if (!isSupported.value || stream.value) return; stream.value = await navigator2.mediaDevices.getUserMedia({ - video: getDeviceOptions("video"), - audio: getDeviceOptions("audio") + video: getDeviceOptions('video'), + audio: getDeviceOptions('audio'), }); return stream.value; } function _stop() { var _a2; - (_a2 = stream.value) == null ? void 0 : _a2.getTracks().forEach((t) => t.stop()); + (_a2 = stream.value) == null + ? void 0 + : _a2.getTracks().forEach((t) => t.stop()); stream.value = void 0; } function stop() { @@ -8606,8 +9522,7 @@ function useUserMedia(options = {}) { } async function start() { await _start(); - if (stream.value) - enabled.value = true; + if (stream.value) enabled.value = true; return stream.value; } async function restart() { @@ -8617,8 +9532,7 @@ function useUserMedia(options = {}) { watch( enabled, (v) => { - if (v) - _start(); + if (v) _start(); else _stop(); }, { immediate: true } @@ -8626,8 +9540,7 @@ function useUserMedia(options = {}) { watch( constraints, () => { - if (autoSwitch.value && stream.value) - restart(); + if (autoSwitch.value && stream.value) restart(); }, { immediate: true } ); @@ -8642,7 +9555,7 @@ function useUserMedia(options = {}) { restart, constraints, enabled, - autoSwitch + autoSwitch, }; } function useVModel(props, key, emit, options = {}) { @@ -8653,21 +9566,29 @@ function useVModel(props, key, emit, options = {}) { eventName, deep = false, defaultValue, - shouldEmit + shouldEmit, } = options; const vm = getCurrentInstance(); - const _emit = emit || (vm == null ? void 0 : vm.emit) || ((_a = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a.bind(vm)) || ((_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$emit) == null ? void 0 : _c.bind(vm == null ? void 0 : vm.proxy)); + const _emit = + emit || + (vm == null ? void 0 : vm.emit) || + ((_a = vm == null ? void 0 : vm.$emit) == null ? void 0 : _a.bind(vm)) || + ((_c = (_b = vm == null ? void 0 : vm.proxy) == null ? void 0 : _b.$emit) == + null + ? void 0 + : _c.bind(vm == null ? void 0 : vm.proxy)); let event = eventName; if (!key) { - key = "modelValue"; + key = 'modelValue'; } event = event || `update:${key.toString()}`; - const cloneFn = (val) => !clone ? val : typeof clone === "function" ? clone(val) : cloneFnJSON(val); - const getValue2 = () => isDef(props[key]) ? cloneFn(props[key]) : defaultValue; + const cloneFn = (val) => + !clone ? val : typeof clone === 'function' ? clone(val) : cloneFnJSON(val); + const getValue2 = () => + isDef(props[key]) ? cloneFn(props[key]) : defaultValue; const triggerEmit = (value) => { if (shouldEmit) { - if (shouldEmit(value)) - _emit(event, value); + if (shouldEmit(value)) _emit(event, value); } else { _emit(event, value); } @@ -8682,15 +9603,14 @@ function useVModel(props, key, emit, options = {}) { if (!isUpdating) { isUpdating = true; proxy.value = cloneFn(v); - nextTick(() => isUpdating = false); + nextTick(() => (isUpdating = false)); } } ); watch( proxy, (v) => { - if (!isUpdating && (v !== props[key] || deep)) - triggerEmit(v); + if (!isUpdating && (v !== props[key] || deep)) triggerEmit(v); }, { deep } ); @@ -8702,19 +9622,14 @@ function useVModel(props, key, emit, options = {}) { }, set(value) { triggerEmit(value); - } + }, }); } } function useVModels(props, emit, options = {}) { const ret = {}; for (const key in props) { - ret[key] = useVModel( - props, - key, - emit, - options - ); + ret[key] = useVModel(props, key, emit, options); } return ret; } @@ -8722,40 +9637,46 @@ function useVibrate(options) { const { pattern = [], interval = 0, - navigator: navigator2 = defaultNavigator + navigator: navigator2 = defaultNavigator, } = options || {}; - const isSupported = useSupported(() => typeof navigator2 !== "undefined" && "vibrate" in navigator2); + const isSupported = useSupported( + () => typeof navigator2 !== 'undefined' && 'vibrate' in navigator2 + ); const patternRef = toRef2(pattern); let intervalControls; const vibrate = (pattern2 = patternRef.value) => { - if (isSupported.value) - navigator2.vibrate(pattern2); + if (isSupported.value) navigator2.vibrate(pattern2); }; const stop = () => { - if (isSupported.value) - navigator2.vibrate(0); + if (isSupported.value) navigator2.vibrate(0); intervalControls == null ? void 0 : intervalControls.pause(); }; if (interval > 0) { - intervalControls = useIntervalFn( - vibrate, - interval, - { - immediate: false, - immediateCallback: false - } - ); + intervalControls = useIntervalFn(vibrate, interval, { + immediate: false, + immediateCallback: false, + }); } return { isSupported, pattern, intervalControls, vibrate, - stop + stop, }; } function useVirtualList(list, options) { - const { containerStyle, wrapperProps, scrollTo, calculateRange, currentList, containerRef } = "itemHeight" in options ? useVerticalVirtualList(options, list) : useHorizontalVirtualList(options, list); + const { + containerStyle, + wrapperProps, + scrollTo, + calculateRange, + currentList, + containerRef, + } = + 'itemHeight' in options + ? useVerticalVirtualList(options, list) + : useHorizontalVirtualList(options, list); return { list: currentList, scrollTo, @@ -8764,9 +9685,9 @@ function useVirtualList(list, options) { onScroll: () => { calculateRange(); }, - style: containerStyle + style: containerStyle, }, - wrapperProps + wrapperProps, }; } function useVirtualListResources(list) { @@ -8779,7 +9700,7 @@ function useVirtualListResources(list) { } function createGetViewCapacity(state, source, itemSize) { return (containerSize) => { - if (typeof itemSize === "number") + if (typeof itemSize === 'number') return Math.ceil(containerSize / itemSize); const { start = 0 } = state.value; let sum = 0; @@ -8788,15 +9709,14 @@ function createGetViewCapacity(state, source, itemSize) { const size = itemSize(i); sum += size; capacity = i; - if (sum > containerSize) - break; + if (sum > containerSize) break; } return capacity - start; }; } function createGetOffset(source, itemSize) { return (scrollDirection) => { - if (typeof itemSize === "number") + if (typeof itemSize === 'number') return Math.floor(scrollDirection / itemSize) + 1; let sum = 0; let offset = 0; @@ -8811,32 +9731,46 @@ function createGetOffset(source, itemSize) { return offset + 1; }; } -function createCalculateRange(type, overscan, getOffset, getViewCapacity, { containerRef, state, currentList, source }) { +function createCalculateRange( + type, + overscan, + getOffset, + getViewCapacity, + { containerRef, state, currentList, source } +) { return () => { const element = containerRef.value; if (element) { - const offset = getOffset(type === "vertical" ? element.scrollTop : element.scrollLeft); - const viewCapacity = getViewCapacity(type === "vertical" ? element.clientHeight : element.clientWidth); + const offset = getOffset( + type === 'vertical' ? element.scrollTop : element.scrollLeft + ); + const viewCapacity = getViewCapacity( + type === 'vertical' ? element.clientHeight : element.clientWidth + ); const from = offset - overscan; const to = offset + viewCapacity + overscan; state.value = { start: from < 0 ? 0 : from, - end: to > source.value.length ? source.value.length : to + end: to > source.value.length ? source.value.length : to, }; - currentList.value = source.value.slice(state.value.start, state.value.end).map((ele, index) => ({ - data: ele, - index: index + state.value.start - })); + currentList.value = source.value + .slice(state.value.start, state.value.end) + .map((ele, index) => ({ + data: ele, + index: index + state.value.start, + })); } }; } function createGetDistance(itemSize, source) { return (index) => { - if (typeof itemSize === "number") { + if (typeof itemSize === 'number') { const size2 = index * itemSize; return size2; } - const size = source.value.slice(0, index).reduce((sum, _, i) => sum + itemSize(i), 0); + const size = source.value + .slice(0, index) + .reduce((sum, _, i) => sum + itemSize(i), 0); return size; }; } @@ -8847,19 +9781,19 @@ function useWatchForSizes(size, list, containerRef, calculateRange) { } function createComputedTotalSize(itemSize, source) { return computed(() => { - if (typeof itemSize === "number") - return source.value.length * itemSize; + if (typeof itemSize === 'number') return source.value.length * itemSize; return source.value.reduce((sum, _, index) => sum + itemSize(index), 0); }); } var scrollToDictionaryForElementScrollKey = { - horizontal: "scrollLeft", - vertical: "scrollTop" + horizontal: 'scrollLeft', + vertical: 'scrollTop', }; function createScrollTo(type, calculateRange, getDistance, containerRef) { return (index) => { if (containerRef.value) { - containerRef.value[scrollToDictionaryForElementScrollKey[type]] = getDistance(index); + containerRef.value[scrollToDictionaryForElementScrollKey[type]] = + getDistance(index); calculateRange(); } }; @@ -8867,24 +9801,35 @@ function createScrollTo(type, calculateRange, getDistance, containerRef) { function useHorizontalVirtualList(options, list) { const resources = useVirtualListResources(list); const { state, source, currentList, size, containerRef } = resources; - const containerStyle = { overflowX: "auto" }; + const containerStyle = { overflowX: 'auto' }; const { itemWidth, overscan = 5 } = options; const getViewCapacity = createGetViewCapacity(state, source, itemWidth); const getOffset = createGetOffset(source, itemWidth); - const calculateRange = createCalculateRange("horizontal", overscan, getOffset, getViewCapacity, resources); + const calculateRange = createCalculateRange( + 'horizontal', + overscan, + getOffset, + getViewCapacity, + resources + ); const getDistanceLeft = createGetDistance(itemWidth, source); const offsetLeft = computed(() => getDistanceLeft(state.value.start)); const totalWidth = createComputedTotalSize(itemWidth, source); useWatchForSizes(size, list, containerRef, calculateRange); - const scrollTo = createScrollTo("horizontal", calculateRange, getDistanceLeft, containerRef); + const scrollTo = createScrollTo( + 'horizontal', + calculateRange, + getDistanceLeft, + containerRef + ); const wrapperProps = computed(() => { return { style: { - height: "100%", + height: '100%', width: `${totalWidth.value - offsetLeft.value}px`, marginLeft: `${offsetLeft.value}px`, - display: "flex" - } + display: 'flex', + }, }; }); return { @@ -8893,29 +9838,40 @@ function useHorizontalVirtualList(options, list) { wrapperProps, containerStyle, currentList, - containerRef + containerRef, }; } function useVerticalVirtualList(options, list) { const resources = useVirtualListResources(list); const { state, source, currentList, size, containerRef } = resources; - const containerStyle = { overflowY: "auto" }; + const containerStyle = { overflowY: 'auto' }; const { itemHeight, overscan = 5 } = options; const getViewCapacity = createGetViewCapacity(state, source, itemHeight); const getOffset = createGetOffset(source, itemHeight); - const calculateRange = createCalculateRange("vertical", overscan, getOffset, getViewCapacity, resources); + const calculateRange = createCalculateRange( + 'vertical', + overscan, + getOffset, + getViewCapacity, + resources + ); const getDistanceTop = createGetDistance(itemHeight, source); const offsetTop = computed(() => getDistanceTop(state.value.start)); const totalHeight = createComputedTotalSize(itemHeight, source); useWatchForSizes(size, list, containerRef, calculateRange); - const scrollTo = createScrollTo("vertical", calculateRange, getDistanceTop, containerRef); + const scrollTo = createScrollTo( + 'vertical', + calculateRange, + getDistanceTop, + containerRef + ); const wrapperProps = computed(() => { return { style: { - width: "100%", + width: '100%', height: `${totalHeight.value - offsetTop.value}px`, - marginTop: `${offsetTop.value}px` - } + marginTop: `${offsetTop.value}px`, + }, }; }); return { @@ -8924,26 +9880,42 @@ function useVerticalVirtualList(options, list) { containerStyle, wrapperProps, currentList, - containerRef + containerRef, }; } function useWakeLock(options = {}) { const { navigator: navigator2 = defaultNavigator, - document: document2 = defaultDocument + document: document2 = defaultDocument, } = options; const requestedType = shallowRef(false); const sentinel = shallowRef(null); const documentVisibility = useDocumentVisibility({ document: document2 }); - const isSupported = useSupported(() => navigator2 && "wakeLock" in navigator2); - const isActive = computed(() => !!sentinel.value && documentVisibility.value === "visible"); + const isSupported = useSupported( + () => navigator2 && 'wakeLock' in navigator2 + ); + const isActive = computed( + () => !!sentinel.value && documentVisibility.value === 'visible' + ); if (isSupported.value) { - useEventListener(sentinel, "release", () => { - var _a, _b; - requestedType.value = (_b = (_a = sentinel.value) == null ? void 0 : _a.type) != null ? _b : false; - }, { passive: true }); + useEventListener( + sentinel, + 'release', + () => { + var _a, _b; + requestedType.value = + (_b = (_a = sentinel.value) == null ? void 0 : _a.type) != null + ? _b + : false; + }, + { passive: true } + ); whenever( - () => documentVisibility.value === "visible" && (document2 == null ? void 0 : document2.visibilityState) === "visible" && requestedType.value, + () => + documentVisibility.value === 'visible' && + (document2 == null ? void 0 : document2.visibilityState) === + 'visible' && + requestedType.value, (type) => { requestedType.value = false; forceRequest(type); @@ -8953,13 +9925,13 @@ function useWakeLock(options = {}) { async function forceRequest(type) { var _a; await ((_a = sentinel.value) == null ? void 0 : _a.release()); - sentinel.value = isSupported.value ? await navigator2.wakeLock.request(type) : null; + sentinel.value = isSupported.value + ? await navigator2.wakeLock.request(type) + : null; } async function request(type) { - if (documentVisibility.value === "visible") - await forceRequest(type); - else - requestedType.value = type; + if (documentVisibility.value === 'visible') await forceRequest(type); + else requestedType.value = type; } async function release() { requestedType.value = false; @@ -8973,40 +9945,39 @@ function useWakeLock(options = {}) { isActive, request, forceRequest, - release + release, }; } function useWebNotification(options = {}) { const { window: window2 = defaultWindow, - requestPermissions: _requestForPermissions = true + requestPermissions: _requestForPermissions = true, } = options; const defaultWebNotificationOptions = options; const isSupported = useSupported(() => { - if (!window2 || !("Notification" in window2)) - return false; - if (Notification.permission === "granted") - return true; + if (!window2 || !('Notification' in window2)) return false; + if (Notification.permission === 'granted') return true; try { - const notification2 = new Notification(""); + const notification2 = new Notification(''); notification2.onshow = () => { notification2.close(); }; } catch (e) { - if (e.name === "TypeError") - return false; + if (e.name === 'TypeError') return false; } return true; }); - const permissionGranted = shallowRef(isSupported.value && "permission" in Notification && Notification.permission === "granted"); + const permissionGranted = shallowRef( + isSupported.value && + 'permission' in Notification && + Notification.permission === 'granted' + ); const notification = ref(null); const ensurePermissions = async () => { - if (!isSupported.value) - return; - if (!permissionGranted.value && Notification.permission !== "denied") { + if (!isSupported.value) return; + if (!permissionGranted.value && Notification.permission !== 'denied') { const result = await Notification.requestPermission(); - if (result === "granted") - permissionGranted.value = true; + if (result === 'granted') permissionGranted.value = true; } return permissionGranted.value; }; @@ -9015,10 +9986,13 @@ function useWebNotification(options = {}) { const { on: onError, trigger: errorTrigger } = createEventHook(); const { on: onClose, trigger: closeTrigger } = createEventHook(); const show = async (overrides) => { - if (!isSupported.value || !permissionGranted.value) - return; - const options2 = Object.assign({}, defaultWebNotificationOptions, overrides); - notification.value = new Notification(options2.title || "", options2); + if (!isSupported.value || !permissionGranted.value) return; + const options2 = Object.assign( + {}, + defaultWebNotificationOptions, + overrides + ); + notification.value = new Notification(options2.title || '', options2); notification.value.onclick = clickTrigger; notification.value.onshow = showTrigger; notification.value.onerror = errorTrigger; @@ -9026,18 +10000,16 @@ function useWebNotification(options = {}) { return notification.value; }; const close = () => { - if (notification.value) - notification.value.close(); + if (notification.value) notification.value.close(); notification.value = null; }; - if (_requestForPermissions) - tryOnMounted(ensurePermissions); + if (_requestForPermissions) tryOnMounted(ensurePermissions); tryOnScopeDispose(close); if (isSupported.value && window2) { const document2 = window2.document; - useEventListener(document2, "visibilitychange", (e) => { + useEventListener(document2, 'visibilitychange', (e) => { e.preventDefault(); - if (document2.visibilityState === "visible") { + if (document2.visibilityState === 'visible') { close(); } }); @@ -9052,13 +10024,12 @@ function useWebNotification(options = {}) { onClick, onShow, onError, - onClose + onClose, }; } -var DEFAULT_PING_MESSAGE = "ping"; +var DEFAULT_PING_MESSAGE = 'ping'; function resolveNestedOptions(options) { - if (options === true) - return {}; + if (options === true) return {}; return options; } function useWebSocket(url, options = {}) { @@ -9070,10 +10041,10 @@ function useWebSocket(url, options = {}) { immediate = true, autoConnect = true, autoClose = true, - protocols = [] + protocols = [], } = options; const data = ref(null); - const status = shallowRef("CLOSED"); + const status = shallowRef('CLOSED'); const wsRef = ref(); const urlRef = toRef2(url); let heartbeatPause; @@ -9084,9 +10055,8 @@ function useWebSocket(url, options = {}) { let retryTimeout; let pongTimeoutWait; const _sendBuffer = () => { - if (bufferedData.length && wsRef.value && status.value === "OPEN") { - for (const buffer of bufferedData) - wsRef.value.send(buffer); + if (bufferedData.length && wsRef.value && status.value === 'OPEN') { + for (const buffer of bufferedData) wsRef.value.send(buffer); bufferedData = []; } }; @@ -9102,8 +10072,7 @@ function useWebSocket(url, options = {}) { }; const close = (code = 1e3, reason) => { resetRetry(); - if (!isClient && !isWorker || !wsRef.value) - return; + if ((!isClient && !isWorker) || !wsRef.value) return; explicitlyClosed = true; resetHeartbeat(); heartbeatPause == null ? void 0 : heartbeatPause(); @@ -9111,9 +10080,8 @@ function useWebSocket(url, options = {}) { wsRef.value = void 0; }; const send = (data2, useBuffer = true) => { - if (!wsRef.value || status.value !== "OPEN") { - if (useBuffer) - bufferedData.push(data2); + if (!wsRef.value || status.value !== 'OPEN') { + if (useBuffer) bufferedData.push(data2); return false; } _sendBuffer(); @@ -9121,30 +10089,38 @@ function useWebSocket(url, options = {}) { return true; }; const _init = () => { - if (explicitlyClosed || typeof urlRef.value === "undefined") - return; + if (explicitlyClosed || typeof urlRef.value === 'undefined') return; const ws = new WebSocket(urlRef.value, protocols); wsRef.value = ws; - status.value = "CONNECTING"; + status.value = 'CONNECTING'; ws.onopen = () => { - status.value = "OPEN"; + status.value = 'OPEN'; retried = 0; onConnected == null ? void 0 : onConnected(ws); heartbeatResume == null ? void 0 : heartbeatResume(); _sendBuffer(); }; ws.onclose = (ev) => { - status.value = "CLOSED"; + status.value = 'CLOSED'; resetHeartbeat(); heartbeatPause == null ? void 0 : heartbeatPause(); onDisconnected == null ? void 0 : onDisconnected(ws, ev); - if (!explicitlyClosed && options.autoReconnect && (wsRef.value == null || ws === wsRef.value)) { + if ( + !explicitlyClosed && + options.autoReconnect && + (wsRef.value == null || ws === wsRef.value) + ) { const { retries = -1, delay = 1e3, - onFailed + onFailed, } = resolveNestedOptions(options.autoReconnect); - const checkRetires = typeof retries === "function" ? retries : () => typeof retries === "number" && (retries < 0 || retried < retries); + const checkRetires = + typeof retries === 'function' + ? retries + : () => + typeof retries === 'number' && + (retries < 0 || retried < retries); if (checkRetires(retried)) { retried += 1; retryTimeout = setTimeout(_init, delay); @@ -9159,12 +10135,9 @@ function useWebSocket(url, options = {}) { ws.onmessage = (e) => { if (options.heartbeat) { resetHeartbeat(); - const { - message = DEFAULT_PING_MESSAGE, - responseMessage = message - } = resolveNestedOptions(options.heartbeat); - if (e.data === toValue(responseMessage)) - return; + const { message = DEFAULT_PING_MESSAGE, responseMessage = message } = + resolveNestedOptions(options.heartbeat); + if (e.data === toValue(responseMessage)) return; } data.value = e.data; onMessage == null ? void 0 : onMessage(ws, e); @@ -9174,13 +10147,12 @@ function useWebSocket(url, options = {}) { const { message = DEFAULT_PING_MESSAGE, interval = 1e3, - pongTimeout = 1e3 + pongTimeout = 1e3, } = resolveNestedOptions(options.heartbeat); const { pause, resume } = useIntervalFn( () => { send(toValue(message), false); - if (pongTimeoutWait != null) - return; + if (pongTimeoutWait != null) return; pongTimeoutWait = setTimeout(() => { close(); explicitlyClosed = false; @@ -9194,97 +10166,91 @@ function useWebSocket(url, options = {}) { } if (autoClose) { if (isClient) - useEventListener("beforeunload", () => close(), { passive: true }); + useEventListener('beforeunload', () => close(), { passive: true }); tryOnScopeDispose(close); } const open = () => { - if (!isClient && !isWorker) - return; + if (!isClient && !isWorker) return; close(); explicitlyClosed = false; retried = 0; _init(); }; - if (immediate) - open(); - if (autoConnect) - watch(urlRef, open); + if (immediate) open(); + if (autoConnect) watch(urlRef, open); return { data, status, close, send, open, - ws: wsRef + ws: wsRef, }; } function useWebWorker(arg0, workerOptions, options) { - const { - window: window2 = defaultWindow - } = options != null ? options : {}; + const { window: window2 = defaultWindow } = options != null ? options : {}; const data = ref(null); const worker = shallowRef(); const post = (...args) => { - if (!worker.value) - return; + if (!worker.value) return; worker.value.postMessage(...args); }; const terminate = function terminate2() { - if (!worker.value) - return; + if (!worker.value) return; worker.value.terminate(); }; if (window2) { - if (typeof arg0 === "string") + if (typeof arg0 === 'string') worker.value = new Worker(arg0, workerOptions); - else if (typeof arg0 === "function") - worker.value = arg0(); - else - worker.value = arg0; + else if (typeof arg0 === 'function') worker.value = arg0(); + else worker.value = arg0; worker.value.onmessage = (e) => { data.value = e.data; }; tryOnScopeDispose(() => { - if (worker.value) - worker.value.terminate(); + if (worker.value) worker.value.terminate(); }); } return { data, post, terminate, - worker + worker, }; } function depsParser(deps, localDeps) { - if (deps.length === 0 && localDeps.length === 0) - return ""; + if (deps.length === 0 && localDeps.length === 0) return ''; const depsString = deps.map((dep) => `'${dep}'`).toString(); - const depsFunctionString = localDeps.filter((dep) => typeof dep === "function").map((fn) => { - const str = fn.toString(); - if (str.trim().startsWith("function")) { - return str; - } else { - const name = fn.name; - return `const ${name} = ${str}`; - } - }).join(";"); + const depsFunctionString = localDeps + .filter((dep) => typeof dep === 'function') + .map((fn) => { + const str = fn.toString(); + if (str.trim().startsWith('function')) { + return str; + } else { + const name = fn.name; + return `const ${name} = ${str}`; + } + }) + .join(';'); const importString = `importScripts(${depsString});`; - return `${depsString.trim() === "" ? "" : importString} ${depsFunctionString}`; + return `${depsString.trim() === '' ? '' : importString} ${depsFunctionString}`; } function jobRunner(userFunc) { return (e) => { const userFuncArgs = e.data[0]; - return Promise.resolve(userFunc.apply(void 0, userFuncArgs)).then((result) => { - postMessage(["SUCCESS", result]); - }).catch((error) => { - postMessage(["ERROR", error]); - }); + return Promise.resolve(userFunc.apply(void 0, userFuncArgs)) + .then((result) => { + postMessage(['SUCCESS', result]); + }) + .catch((error) => { + postMessage(['ERROR', error]); + }); }; } function createWorkerBlobUrl(fn, deps, localDeps) { const blobCode = `${depsParser(deps, localDeps)}; onmessage=(${jobRunner})(${fn})`; - const blob = new Blob([blobCode], { type: "text/javascript" }); + const blob = new Blob([blobCode], { type: 'text/javascript' }); const url = URL.createObjectURL(blob); return url; } @@ -9293,13 +10259,13 @@ function useWebWorkerFn(fn, options = {}) { dependencies = [], localDependencies = [], timeout, - window: window2 = defaultWindow + window: window2 = defaultWindow, } = options; const worker = ref(); - const workerStatus = shallowRef("PENDING"); + const workerStatus = shallowRef('PENDING'); const promise = ref({}); const timeoutId = shallowRef(); - const workerTerminate = (status = "PENDING") => { + const workerTerminate = (status = 'PENDING') => { if (worker.value && worker.value._url && window2) { worker.value.terminate(); URL.revokeObjectURL(worker.value._url); @@ -9316,49 +10282,47 @@ function useWebWorkerFn(fn, options = {}) { const newWorker = new Worker(blobUrl); newWorker._url = blobUrl; newWorker.onmessage = (e) => { - const { resolve = () => { - }, reject = () => { - } } = promise.value; + const { resolve = () => {}, reject = () => {} } = promise.value; const [status, result] = e.data; switch (status) { - case "SUCCESS": + case 'SUCCESS': resolve(result); workerTerminate(status); break; default: reject(result); - workerTerminate("ERROR"); + workerTerminate('ERROR'); break; } }; newWorker.onerror = (e) => { - const { reject = () => { - } } = promise.value; + const { reject = () => {} } = promise.value; e.preventDefault(); reject(e); - workerTerminate("ERROR"); + workerTerminate('ERROR'); }; if (timeout) { timeoutId.value = setTimeout( - () => workerTerminate("TIMEOUT_EXPIRED"), + () => workerTerminate('TIMEOUT_EXPIRED'), timeout ); } return newWorker; }; - const callWorker = (...fnArgs) => new Promise((resolve, reject) => { - var _a; - promise.value = { - resolve, - reject - }; - (_a = worker.value) == null ? void 0 : _a.postMessage([[...fnArgs]]); - workerStatus.value = "RUNNING"; - }); + const callWorker = (...fnArgs) => + new Promise((resolve, reject) => { + var _a; + promise.value = { + resolve, + reject, + }; + (_a = worker.value) == null ? void 0 : _a.postMessage([[...fnArgs]]); + workerStatus.value = 'RUNNING'; + }); const workerFn = (...fnArgs) => { - if (workerStatus.value === "RUNNING") { + if (workerStatus.value === 'RUNNING') { console.error( - "[useWebWorkerFn] You can only run one instance of the worker at a time." + '[useWebWorkerFn] You can only run one instance of the worker at a time.' ); return Promise.reject(); } @@ -9368,21 +10332,30 @@ function useWebWorkerFn(fn, options = {}) { return { workerFn, workerStatus, - workerTerminate + workerTerminate, }; } function useWindowFocus(options = {}) { const { window: window2 = defaultWindow } = options; - if (!window2) - return shallowRef(false); + if (!window2) return shallowRef(false); const focused = shallowRef(window2.document.hasFocus()); const listenerOptions = { passive: true }; - useEventListener(window2, "blur", () => { - focused.value = false; - }, listenerOptions); - useEventListener(window2, "focus", () => { - focused.value = true; - }, listenerOptions); + useEventListener( + window2, + 'blur', + () => { + focused.value = false; + }, + listenerOptions + ); + useEventListener( + window2, + 'focus', + () => { + focused.value = true; + }, + listenerOptions + ); return focused; } function useWindowScroll(options = {}) { @@ -9396,17 +10369,21 @@ function useWindowSize(options = {}) { initialHeight = Number.POSITIVE_INFINITY, listenOrientation = true, includeScrollbar = true, - type = "inner" + type = 'inner', } = options; const width = shallowRef(initialWidth); const height = shallowRef(initialHeight); const update = () => { if (window2) { - if (type === "outer") { + if (type === 'outer') { width.value = window2.outerWidth; height.value = window2.outerHeight; - } else if (type === "visual" && window2.visualViewport) { - const { width: visualViewportWidth, height: visualViewportHeight, scale } = window2.visualViewport; + } else if (type === 'visual' && window2.visualViewport) { + const { + width: visualViewportWidth, + height: visualViewportHeight, + scale, + } = window2.visualViewport; width.value = Math.round(visualViewportWidth * scale); height.value = Math.round(visualViewportHeight * scale); } else if (includeScrollbar) { @@ -9421,12 +10398,12 @@ function useWindowSize(options = {}) { update(); tryOnMounted(update); const listenerOptions = { passive: true }; - useEventListener("resize", update, listenerOptions); - if (window2 && type === "visual" && window2.visualViewport) { - useEventListener(window2.visualViewport, "resize", update, listenerOptions); + useEventListener('resize', update, listenerOptions); + if (window2 && type === 'visual' && window2.visualViewport) { + useEventListener(window2.visualViewport, 'resize', update, listenerOptions); } if (listenOrientation) { - const matches = useMediaQuery("(orientation: portrait)"); + const matches = useMediaQuery('(orientation: portrait)'); watch(matches, () => update()); } return { width, height }; @@ -9714,6 +10691,6 @@ export { useWebWorkerFn, useWindowFocus, useWindowScroll, - useWindowSize + useWindowSize, }; -//# sourceMappingURL=chunk-2CLQ7TTZ.js.map +//# sourceMappingURL=chunk-BRNHR3LR.js.map diff --git a/docs/.vitepress/cache/deps/chunk-2CLQ7TTZ.js.map b/docs/.vitepress/cache/deps/chunk-BRNHR3LR.js.map similarity index 100% rename from docs/.vitepress/cache/deps/chunk-2CLQ7TTZ.js.map rename to docs/.vitepress/cache/deps/chunk-BRNHR3LR.js.map diff --git a/docs/.vitepress/cache/deps/chunk-LE5NDSFD.js b/docs/.vitepress/cache/deps/chunk-H6MPEGKE.js similarity index 74% rename from docs/.vitepress/cache/deps/chunk-LE5NDSFD.js rename to docs/.vitepress/cache/deps/chunk-H6MPEGKE.js index 42925ac..1011890 100644 --- a/docs/.vitepress/cache/deps/chunk-LE5NDSFD.js +++ b/docs/.vitepress/cache/deps/chunk-H6MPEGKE.js @@ -1,17 +1,18 @@ // node_modules/@vue/shared/dist/shared.esm-bundler.js function makeMap(str) { const map2 = /* @__PURE__ */ Object.create(null); - for (const key of str.split(",")) map2[key] = 1; + for (const key of str.split(',')) map2[key] = 1; return (val) => val in map2; } var EMPTY_OBJ = true ? Object.freeze({}) : {}; var EMPTY_ARR = true ? Object.freeze([]) : []; -var NOOP = () => { -}; +var NOOP = () => {}; var NO = () => false; -var isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter -(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); -var isModelListener = (key) => key.startsWith("onUpdate:"); +var isOn = (key) => + key.charCodeAt(0) === 111 && + key.charCodeAt(1) === 110 && // uppercase letter + (key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97); +var isModelListener = (key) => key.startsWith('onUpdate:'); var extend = Object.assign; var remove = (arr, el) => { const i = arr.indexOf(el); @@ -22,30 +23,38 @@ var remove = (arr, el) => { var hasOwnProperty = Object.prototype.hasOwnProperty; var hasOwn = (val, key) => hasOwnProperty.call(val, key); var isArray = Array.isArray; -var isMap = (val) => toTypeString(val) === "[object Map]"; -var isSet = (val) => toTypeString(val) === "[object Set]"; -var isDate = (val) => toTypeString(val) === "[object Date]"; -var isRegExp = (val) => toTypeString(val) === "[object RegExp]"; -var isFunction = (val) => typeof val === "function"; -var isString = (val) => typeof val === "string"; -var isSymbol = (val) => typeof val === "symbol"; -var isObject = (val) => val !== null && typeof val === "object"; +var isMap = (val) => toTypeString(val) === '[object Map]'; +var isSet = (val) => toTypeString(val) === '[object Set]'; +var isDate = (val) => toTypeString(val) === '[object Date]'; +var isRegExp = (val) => toTypeString(val) === '[object RegExp]'; +var isFunction = (val) => typeof val === 'function'; +var isString = (val) => typeof val === 'string'; +var isSymbol = (val) => typeof val === 'symbol'; +var isObject = (val) => val !== null && typeof val === 'object'; var isPromise = (val) => { - return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch); + return ( + (isObject(val) || isFunction(val)) && + isFunction(val.then) && + isFunction(val.catch) + ); }; var objectToString = Object.prototype.toString; var toTypeString = (value) => objectToString.call(value); var toRawType = (value) => { return toTypeString(value).slice(8, -1); }; -var isPlainObject = (val) => toTypeString(val) === "[object Object]"; -var isIntegerKey = (key) => isString(key) && key !== "NaN" && key[0] !== "-" && "" + parseInt(key, 10) === key; +var isPlainObject = (val) => toTypeString(val) === '[object Object]'; +var isIntegerKey = (key) => + isString(key) && + key !== 'NaN' && + key[0] !== '-' && + '' + parseInt(key, 10) === key; var isReservedProp = makeMap( // the leading comma is intentional so empty string "" is also included - ",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted" + ',key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted' ); var isBuiltInDirective = makeMap( - "bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo" + 'bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo' ); var cacheStringFunction = (fn) => { const cache = /* @__PURE__ */ Object.create(null); @@ -55,24 +64,20 @@ var cacheStringFunction = (fn) => { }; }; var camelizeRE = /-\w/g; -var camelize = cacheStringFunction( - (str) => { - return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase()); - } -); +var camelize = cacheStringFunction((str) => { + return str.replace(camelizeRE, (c) => c.slice(1).toUpperCase()); +}); var hyphenateRE = /\B([A-Z])/g; -var hyphenate = cacheStringFunction( - (str) => str.replace(hyphenateRE, "-$1").toLowerCase() +var hyphenate = cacheStringFunction((str) => + str.replace(hyphenateRE, '-$1').toLowerCase() ); var capitalize = cacheStringFunction((str) => { return str.charAt(0).toUpperCase() + str.slice(1); }); -var toHandlerKey = cacheStringFunction( - (str) => { - const s = str ? `on${capitalize(str)}` : ``; - return s; - } -); +var toHandlerKey = cacheStringFunction((str) => { + const s = str ? `on${capitalize(str)}` : ``; + return s; +}); var hasChanged = (value, oldValue) => !Object.is(value, oldValue); var invokeArrayFns = (fns, ...arg) => { for (let i = 0; i < fns.length; i++) { @@ -84,7 +89,7 @@ var def = (obj, key, value, writable = false) => { configurable: true, enumerable: false, writable, - value + value, }); }; var looseToNumber = (val) => { @@ -97,16 +102,31 @@ var toNumber = (val) => { }; var _globalThis; var getGlobalThis = () => { - return _globalThis || (_globalThis = typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}); + return ( + _globalThis || + (_globalThis = + typeof globalThis !== 'undefined' + ? globalThis + : typeof self !== 'undefined' + ? self + : typeof window !== 'undefined' + ? window + : typeof global !== 'undefined' + ? global + : {}) + ); }; -var GLOBALS_ALLOWED = "Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol"; +var GLOBALS_ALLOWED = + 'Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol'; var isGloballyAllowed = makeMap(GLOBALS_ALLOWED); function normalizeStyle(value) { if (isArray(value)) { const res = {}; for (let i = 0; i < value.length; i++) { const item = value[i]; - const normalized = isString(item) ? parseStringStyle(item) : normalizeStyle(item); + const normalized = isString(item) + ? parseStringStyle(item) + : normalizeStyle(item); if (normalized) { for (const key in normalized) { res[key] = normalized[key]; @@ -123,21 +143,24 @@ var propertyDelimiterRE = /:([^]+)/; var styleCommentRE = /\/\*[^]*?\*\//g; function parseStringStyle(cssText) { const ret = {}; - cssText.replace(styleCommentRE, "").split(listDelimiterRE).forEach((item) => { - if (item) { - const tmp = item.split(propertyDelimiterRE); - tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); - } - }); + cssText + .replace(styleCommentRE, '') + .split(listDelimiterRE) + .forEach((item) => { + if (item) { + const tmp = item.split(propertyDelimiterRE); + tmp.length > 1 && (ret[tmp[0].trim()] = tmp[1].trim()); + } + }); return ret; } function stringifyStyle(styles) { - if (!styles) return ""; + if (!styles) return ''; if (isString(styles)) return styles; - let ret = ""; + let ret = ''; for (const key in styles) { const value = styles[key]; - if (isString(value) || typeof value === "number") { + if (isString(value) || typeof value === 'number') { const normalizedKey = key.startsWith(`--`) ? key : hyphenate(key); ret += `${normalizedKey}:${value};`; } @@ -145,20 +168,20 @@ function stringifyStyle(styles) { return ret; } function normalizeClass(value) { - let res = ""; + let res = ''; if (isString(value)) { res = value; } else if (isArray(value)) { for (let i = 0; i < value.length; i++) { const normalized = normalizeClass(value[i]); if (normalized) { - res += normalized + " "; + res += normalized + ' '; } } } else if (isObject(value)) { for (const name in value) { if (value[name]) { - res += name + " "; + res += name + ' '; } } } @@ -175,10 +198,14 @@ function normalizeProps(props) { } return props; } -var HTML_TAGS = "html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"; -var SVG_TAGS = "svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"; -var MATH_TAGS = "annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"; -var VOID_TAGS = "area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"; +var HTML_TAGS = + 'html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot'; +var SVG_TAGS = + 'svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view'; +var MATH_TAGS = + 'annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics'; +var VOID_TAGS = + 'area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr'; var isHTMLTag = makeMap(HTML_TAGS); var isSVGTag = makeMap(SVG_TAGS); var isMathMLTag = makeMap(MATH_TAGS); @@ -186,10 +213,11 @@ var isVoidTag = makeMap(VOID_TAGS); var specialBooleanAttrs = `itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly`; var isSpecialBooleanAttr = makeMap(specialBooleanAttrs); var isBooleanAttr = makeMap( - specialBooleanAttrs + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` + specialBooleanAttrs + + `,async,autofocus,autoplay,controls,default,defer,disabled,hidden,inert,loop,open,required,reversed,scoped,seamless,checked,muted,multiple,selected` ); function includeBooleanAttr(value) { - return !!value || value === ""; + return !!value || value === ''; } var isKnownHtmlAttr = makeMap( `accept,accept-charset,accesskey,action,align,allow,alt,async,autocapitalize,autocomplete,autofocus,autoplay,background,bgcolor,border,buffered,capture,challenge,charset,checked,cite,class,code,codebase,color,cols,colspan,content,contenteditable,contextmenu,controls,coords,crossorigin,csp,data,datetime,decoding,default,defer,dir,dirname,disabled,download,draggable,dropzone,enctype,enterkeyhint,for,form,formaction,formenctype,formmethod,formnovalidate,formtarget,headers,height,hidden,high,href,hreflang,http-equiv,icon,id,importance,inert,integrity,ismap,itemprop,keytype,kind,label,lang,language,loading,list,loop,low,manifest,max,maxlength,minlength,media,min,multiple,muted,name,novalidate,open,optimum,pattern,ping,placeholder,poster,preload,radiogroup,readonly,referrerpolicy,rel,required,reversed,rows,rowspan,sandbox,scope,scoped,selected,shape,size,sizes,slot,span,spellcheck,src,srcdoc,srclang,srcset,start,step,style,summary,tabindex,target,title,translate,type,usemap,value,width,wrap` @@ -205,13 +233,12 @@ function isRenderableAttrValue(value) { return false; } const type = typeof value; - return type === "string" || type === "number" || type === "boolean"; + return type === 'string' || type === 'number' || type === 'boolean'; } var cssVarNameEscapeSymbolsRE = /[ !"#$%&'()*+,./:;<=>?@[\\\]^`{|}~]/g; function getEscapedCssVarName(key, doubleEscape) { - return key.replace( - cssVarNameEscapeSymbolsRE, - (s) => doubleEscape ? s === '"' ? '\\\\\\"' : `\\\\${s}` : `\\${s}` + return key.replace(cssVarNameEscapeSymbolsRE, (s) => + doubleEscape ? (s === '"' ? '\\\\\\"' : `\\\\${s}`) : `\\${s}` ); } function looseCompareArrays(a, b) { @@ -253,7 +280,11 @@ function looseEqual(a, b) { for (const key in a) { const aHasKey = a.hasOwnProperty(key); const bHasKey = b.hasOwnProperty(key); - if (aHasKey && !bHasKey || !aHasKey && bHasKey || !looseEqual(a[key], b[key])) { + if ( + (aHasKey && !bHasKey) || + (!aHasKey && bHasKey) || + !looseEqual(a[key], b[key]) + ) { return false; } } @@ -264,10 +295,20 @@ function looseIndexOf(arr, val) { return arr.findIndex((item) => looseEqual(item, val)); } var isRef = (val) => { - return !!(val && val["__v_isRef"] === true); + return !!(val && val['__v_isRef'] === true); }; var toDisplayString = (val) => { - return isString(val) ? val : val == null ? "" : isArray(val) || isObject(val) && (val.toString === objectToString || !isFunction(val.toString)) ? isRef(val) ? toDisplayString(val.value) : JSON.stringify(val, replacer, 2) : String(val); + return isString(val) + ? val + : val == null + ? '' + : isArray(val) || + (isObject(val) && + (val.toString === objectToString || !isFunction(val.toString))) + ? isRef(val) + ? toDisplayString(val.value) + : JSON.stringify(val, replacer, 2) + : String(val); }; var replacer = (_key, val) => { if (isRef(val)) { @@ -276,15 +317,15 @@ var replacer = (_key, val) => { return { [`Map(${val.size})`]: [...val.entries()].reduce( (entries, [key, val2], i) => { - entries[stringifySymbol(key, i) + " =>"] = val2; + entries[stringifySymbol(key, i) + ' =>'] = val2; return entries; }, {} - ) + ), }; } else if (isSet(val)) { return { - [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)) + [`Set(${val.size})`]: [...val.values()].map((v) => stringifySymbol(v)), }; } else if (isSymbol(val)) { return stringifySymbol(val); @@ -293,7 +334,7 @@ var replacer = (_key, val) => { } return val; }; -var stringifySymbol = (v, i = "") => { +var stringifySymbol = (v, i = '') => { var _a; return ( // Symbol.description in es2019+ so we need to cast here to pass @@ -303,15 +344,15 @@ var stringifySymbol = (v, i = "") => { }; function normalizeCssVarValue(value) { if (value == null) { - return "initial"; + return 'initial'; } - if (typeof value === "string") { - return value === "" ? " " : value; + if (typeof value === 'string') { + return value === '' ? ' ' : value; } - if (typeof value !== "number" || !Number.isFinite(value)) { + if (typeof value !== 'number' || !Number.isFinite(value)) { if (true) { console.warn( - "[Vue warn] Invalid value used for CSS binding. Expected a string or a finite number but received:", + '[Vue warn] Invalid value used for CSS binding. Expected a string or a finite number but received:', value ); } @@ -325,6 +366,7 @@ function warn(msg, ...args) { } var activeEffectScope; var EffectScope = class { + // TODO isolatedDeclarations "__v_skip" constructor(detached = false) { this.detached = detached; this._active = true; @@ -332,11 +374,13 @@ var EffectScope = class { this.effects = []; this.cleanups = []; this._isPaused = false; + this.__v_skip = true; this.parent = activeEffectScope; if (!detached && activeEffectScope) { - this.index = (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( - this - ) - 1; + this.index = + (activeEffectScope.scopes || (activeEffectScope.scopes = [])).push( + this + ) - 1; } } get active() { @@ -506,7 +550,7 @@ var ReactiveEffect = class { } finally { if (activeSub !== this) { warn( - "Active effect was not restored correctly - this is likely a Vue internal bug." + 'Active effect was not restored correctly - this is likely a Vue internal bug.' ); } cleanupDeps(this); @@ -587,7 +631,6 @@ function endBatch() { e.flags &= -9; if (e.flags & 1) { try { - ; e.trigger(); } catch (err) { if (!error) error = err; @@ -627,7 +670,12 @@ function cleanupDeps(sub) { } function isDirty(sub) { for (let link = sub.deps; link; link = link.nextDep) { - if (link.dep.version !== link.version || link.dep.computed && (refreshComputed(link.dep.computed) || link.dep.version !== link.version)) { + if ( + link.dep.version !== link.version || + (link.dep.computed && + (refreshComputed(link.dep.computed) || + link.dep.version !== link.version)) + ) { return true; } } @@ -645,7 +693,11 @@ function refreshComputed(computed3) { return; } computed3.globalVersion = globalVersion; - if (!computed3.isSSR && computed3.flags & 128 && (!computed3.deps && !computed3._dirty || !isDirty(computed3))) { + if ( + !computed3.isSSR && + computed3.flags & 128 && + ((!computed3.deps && !computed3._dirty) || !isDirty(computed3)) + ) { return; } computed3.flags |= 2; @@ -759,7 +811,12 @@ var Link = class { this.sub = sub; this.dep = dep; this.version = dep.version; - this.nextDep = this.prevDep = this.nextSub = this.prevSub = this.prevActiveLink = void 0; + this.nextDep = + this.prevDep = + this.nextSub = + this.prevSub = + this.prevActiveLink = + void 0; } }; var Dep = class { @@ -813,7 +870,7 @@ var Dep = class { activeSub.onTrack( extend( { - effect: activeSub + effect: activeSub, }, debugInfo ) @@ -835,7 +892,7 @@ var Dep = class { head.sub.onTrigger( extend( { - effect: head.sub + effect: head.sub, }, debugInfo ) @@ -845,7 +902,6 @@ var Dep = class { } for (let link = this.subs; link; link = link.prevSub) { if (link.sub.notify()) { - ; link.sub.dep.notify(); } } @@ -876,24 +932,18 @@ function addSub(link) { } } var targetMap = /* @__PURE__ */ new WeakMap(); -var ITERATE_KEY = Symbol( - true ? "Object iterate" : "" -); -var MAP_KEY_ITERATE_KEY = Symbol( - true ? "Map keys iterate" : "" -); -var ARRAY_ITERATE_KEY = Symbol( - true ? "Array iterate" : "" -); +var ITERATE_KEY = Symbol(true ? 'Object iterate' : ''); +var MAP_KEY_ITERATE_KEY = Symbol(true ? 'Map keys iterate' : ''); +var ARRAY_ITERATE_KEY = Symbol(true ? 'Array iterate' : ''); function track(target, type, key) { if (shouldTrack && activeSub) { let depsMap = targetMap.get(target); if (!depsMap) { - targetMap.set(target, depsMap = /* @__PURE__ */ new Map()); + targetMap.set(target, (depsMap = /* @__PURE__ */ new Map())); } let dep = depsMap.get(key); if (!dep) { - depsMap.set(key, dep = new Dep()); + depsMap.set(key, (dep = new Dep())); dep.map = depsMap; dep.key = key; } @@ -901,7 +951,7 @@ function track(target, type, key) { dep.track({ target, type, - key + key, }); } else { dep.track(); @@ -923,7 +973,7 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { key, newValue, oldValue, - oldTarget + oldTarget, }); } else { dep.trigger(); @@ -931,15 +981,19 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { } }; startBatch(); - if (type === "clear") { + if (type === 'clear') { depsMap.forEach(run); } else { const targetIsArray = isArray(target); const isArrayIndex = targetIsArray && isIntegerKey(key); - if (targetIsArray && key === "length") { + if (targetIsArray && key === 'length') { const newLength = Number(newValue); depsMap.forEach((dep, key2) => { - if (key2 === "length" || key2 === ARRAY_ITERATE_KEY || !isSymbol(key2) && key2 >= newLength) { + if ( + key2 === 'length' || + key2 === ARRAY_ITERATE_KEY || + (!isSymbol(key2) && key2 >= newLength) + ) { run(dep); } }); @@ -951,17 +1005,17 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { run(depsMap.get(ARRAY_ITERATE_KEY)); } switch (type) { - case "add": + case 'add': if (!targetIsArray) { run(depsMap.get(ITERATE_KEY)); if (isMap(target)) { run(depsMap.get(MAP_KEY_ITERATE_KEY)); } } else if (isArrayIndex) { - run(depsMap.get("length")); + run(depsMap.get('length')); } break; - case "delete": + case 'delete': if (!targetIsArray) { run(depsMap.get(ITERATE_KEY)); if (isMap(target)) { @@ -969,7 +1023,7 @@ function trigger(target, type, key, newValue, oldValue, oldTarget) { } } break; - case "set": + case 'set': if (isMap(target)) { run(depsMap.get(ITERATE_KEY)); } @@ -986,11 +1040,11 @@ function getDepFromReactive(object, key) { function reactiveReadArray(array) { const raw = toRaw(array); if (raw === array) return raw; - track(raw, "iterate", ARRAY_ITERATE_KEY); + track(raw, 'iterate', ARRAY_ITERATE_KEY); return isShallow(array) ? raw : raw.map(toReactive); } function shallowReadArray(arr) { - track(arr = toRaw(arr), "iterate", ARRAY_ITERATE_KEY); + track((arr = toRaw(arr)), 'iterate', ARRAY_ITERATE_KEY); return arr; } function toWrapped(target, item) { @@ -1006,22 +1060,22 @@ var arrayInstrumentations = { }, concat(...args) { return reactiveReadArray(this).concat( - ...args.map((x) => isArray(x) ? reactiveReadArray(x) : x) + ...args.map((x) => (isArray(x) ? reactiveReadArray(x) : x)) ); }, entries() { - return iterator(this, "entries", (value) => { + return iterator(this, 'entries', (value) => { value[1] = toWrapped(this, value[1]); return value; }); }, every(fn, thisArg) { - return apply(this, "every", fn, thisArg, void 0, arguments); + return apply(this, 'every', fn, thisArg, void 0, arguments); }, filter(fn, thisArg) { return apply( this, - "filter", + 'filter', fn, thisArg, (v) => v.map((item) => toWrapped(this, item)), @@ -1031,7 +1085,7 @@ var arrayInstrumentations = { find(fn, thisArg) { return apply( this, - "find", + 'find', fn, thisArg, (item) => toWrapped(this, item), @@ -1039,12 +1093,12 @@ var arrayInstrumentations = { ); }, findIndex(fn, thisArg) { - return apply(this, "findIndex", fn, thisArg, void 0, arguments); + return apply(this, 'findIndex', fn, thisArg, void 0, arguments); }, findLast(fn, thisArg) { return apply( this, - "findLast", + 'findLast', fn, thisArg, (item) => toWrapped(this, item), @@ -1052,49 +1106,49 @@ var arrayInstrumentations = { ); }, findLastIndex(fn, thisArg) { - return apply(this, "findLastIndex", fn, thisArg, void 0, arguments); + return apply(this, 'findLastIndex', fn, thisArg, void 0, arguments); }, // flat, flatMap could benefit from ARRAY_ITERATE but are not straight-forward to implement forEach(fn, thisArg) { - return apply(this, "forEach", fn, thisArg, void 0, arguments); + return apply(this, 'forEach', fn, thisArg, void 0, arguments); }, includes(...args) { - return searchProxy(this, "includes", args); + return searchProxy(this, 'includes', args); }, indexOf(...args) { - return searchProxy(this, "indexOf", args); + return searchProxy(this, 'indexOf', args); }, join(separator) { return reactiveReadArray(this).join(separator); }, // keys() iterator only reads `length`, no optimization required lastIndexOf(...args) { - return searchProxy(this, "lastIndexOf", args); + return searchProxy(this, 'lastIndexOf', args); }, map(fn, thisArg) { - return apply(this, "map", fn, thisArg, void 0, arguments); + return apply(this, 'map', fn, thisArg, void 0, arguments); }, pop() { - return noTracking(this, "pop"); + return noTracking(this, 'pop'); }, push(...args) { - return noTracking(this, "push", args); + return noTracking(this, 'push', args); }, reduce(fn, ...args) { - return reduce(this, "reduce", fn, args); + return reduce(this, 'reduce', fn, args); }, reduceRight(fn, ...args) { - return reduce(this, "reduceRight", fn, args); + return reduce(this, 'reduceRight', fn, args); }, shift() { - return noTracking(this, "shift"); + return noTracking(this, 'shift'); }, // slice could use ARRAY_ITERATE but also seems to beg for range tracking some(fn, thisArg) { - return apply(this, "some", fn, thisArg, void 0, arguments); + return apply(this, 'some', fn, thisArg, void 0, arguments); }, splice(...args) { - return noTracking(this, "splice", args); + return noTracking(this, 'splice', args); }, toReversed() { return reactiveReadArray(this).toReversed(); @@ -1106,11 +1160,11 @@ var arrayInstrumentations = { return reactiveReadArray(this).toSpliced(...args); }, unshift(...args) { - return noTracking(this, "unshift", args); + return noTracking(this, 'unshift', args); }, values() { - return iterator(this, "values", (item) => toWrapped(this, item)); - } + return iterator(this, 'values', (item) => toWrapped(this, item)); + }, }; function iterator(self2, method, wrapValue) { const arr = shallowReadArray(self2); @@ -1139,11 +1193,11 @@ function apply(self2, method, fn, thisArg, wrappedRetFn, args) { let wrappedFn = fn; if (arr !== self2) { if (needsWrap) { - wrappedFn = function(item, index) { + wrappedFn = function (item, index) { return fn.call(this, toWrapped(self2, item), index, self2); }; } else if (fn.length > 2) { - wrappedFn = function(item, index) { + wrappedFn = function (item, index) { return fn.call(this, item, index, self2); }; } @@ -1156,11 +1210,11 @@ function reduce(self2, method, fn, args) { let wrappedFn = fn; if (arr !== self2) { if (!isShallow(self2)) { - wrappedFn = function(acc, item, index) { + wrappedFn = function (acc, item, index) { return fn.call(this, acc, toWrapped(self2, item), index, self2); }; } else if (fn.length > 3) { - wrappedFn = function(acc, item, index) { + wrappedFn = function (acc, item, index) { return fn.call(this, acc, item, index, self2); }; } @@ -1169,7 +1223,7 @@ function reduce(self2, method, fn, args) { } function searchProxy(self2, method, args) { const arr = toRaw(self2); - track(arr, "iterate", ARRAY_ITERATE_KEY); + track(arr, 'iterate', ARRAY_ITERATE_KEY); const res = arr[method](...args); if ((res === -1 || res === false) && isProxy(args[0])) { args[0] = toRaw(args[0]); @@ -1187,12 +1241,15 @@ function noTracking(self2, method, args = []) { } var isNonTrackableKeys = makeMap(`__proto__,__v_isRef,__isVue`); var builtInSymbols = new Set( - Object.getOwnPropertyNames(Symbol).filter((key) => key !== "arguments" && key !== "caller").map((key) => Symbol[key]).filter(isSymbol) + Object.getOwnPropertyNames(Symbol) + .filter((key) => key !== 'arguments' && key !== 'caller') + .map((key) => Symbol[key]) + .filter(isSymbol) ); function hasOwnProperty2(key) { if (!isSymbol(key)) key = String(key); const obj = toRaw(this); - track(obj, "has", key); + track(obj, 'has', key); return obj.hasOwnProperty(key); } var BaseReactiveHandler = class { @@ -1201,18 +1258,29 @@ var BaseReactiveHandler = class { this._isShallow = _isShallow; } get(target, key, receiver) { - if (key === "__v_skip") return target["__v_skip"]; - const isReadonly2 = this._isReadonly, isShallow2 = this._isShallow; - if (key === "__v_isReactive") { + if (key === '__v_skip') return target['__v_skip']; + const isReadonly2 = this._isReadonly, + isShallow2 = this._isShallow; + if (key === '__v_isReactive') { return !isReadonly2; - } else if (key === "__v_isReadonly") { + } else if (key === '__v_isReadonly') { return isReadonly2; - } else if (key === "__v_isShallow") { + } else if (key === '__v_isShallow') { return isShallow2; - } else if (key === "__v_raw") { - if (receiver === (isReadonly2 ? isShallow2 ? shallowReadonlyMap : readonlyMap : isShallow2 ? shallowReactiveMap : reactiveMap).get(target) || // receiver is not the reactive proxy, but has the same prototype - // this means the receiver is a user proxy of the reactive proxy - Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver)) { + } else if (key === '__v_raw') { + if ( + receiver === + (isReadonly2 + ? isShallow2 + ? shallowReadonlyMap + : readonlyMap + : isShallow2 + ? shallowReactiveMap + : reactiveMap + ).get(target) || // receiver is not the reactive proxy, but has the same prototype + // this means the receiver is a user proxy of the reactive proxy + Object.getPrototypeOf(target) === Object.getPrototypeOf(receiver) + ) { return target; } return; @@ -1223,7 +1291,7 @@ var BaseReactiveHandler = class { if (targetIsArray && (fn = arrayInstrumentations[key])) { return fn; } - if (key === "hasOwnProperty") { + if (key === 'hasOwnProperty') { return hasOwnProperty2; } } @@ -1239,7 +1307,7 @@ var BaseReactiveHandler = class { return res; } if (!isReadonly2) { - track(target, "get", key); + track(target, 'get', key); } if (isShallow2) { return res; @@ -1282,7 +1350,9 @@ var MutableReactiveHandler = class extends BaseReactiveHandler { } } } - const hadKey = isArrayWithIntegerKey ? Number(key) < target.length : hasOwn(target, key); + const hadKey = isArrayWithIntegerKey + ? Number(key) < target.length + : hasOwn(target, key); const result = Reflect.set( target, key, @@ -1291,9 +1361,9 @@ var MutableReactiveHandler = class extends BaseReactiveHandler { ); if (target === toRaw(receiver)) { if (!hadKey) { - trigger(target, "add", key, value); + trigger(target, 'add', key, value); } else if (hasChanged(value, oldValue)) { - trigger(target, "set", key, value, oldValue); + trigger(target, 'set', key, value, oldValue); } } return result; @@ -1303,23 +1373,19 @@ var MutableReactiveHandler = class extends BaseReactiveHandler { const oldValue = target[key]; const result = Reflect.deleteProperty(target, key); if (result && hadKey) { - trigger(target, "delete", key, void 0, oldValue); + trigger(target, 'delete', key, void 0, oldValue); } return result; } has(target, key) { const result = Reflect.has(target, key); if (!isSymbol(key) || !builtInSymbols.has(key)) { - track(target, "has", key); + track(target, 'has', key); } return result; } ownKeys(target) { - track( - target, - "iterate", - isArray(target) ? "length" : ITERATE_KEY - ); + track(target, 'iterate', isArray(target) ? 'length' : ITERATE_KEY); return Reflect.ownKeys(target); } }; @@ -1353,37 +1419,41 @@ var shallowReadonlyHandlers = new ReadonlyReactiveHandler(true); var toShallow = (value) => value; var getProto = (v) => Reflect.getPrototypeOf(v); function createIterableMethod(method, isReadonly2, isShallow2) { - return function(...args) { - const target = this["__v_raw"]; + return function (...args) { + const target = this['__v_raw']; const rawTarget = toRaw(target); const targetIsMap = isMap(rawTarget); - const isPair = method === "entries" || method === Symbol.iterator && targetIsMap; - const isKeyOnly = method === "keys" && targetIsMap; + const isPair = + method === 'entries' || (method === Symbol.iterator && targetIsMap); + const isKeyOnly = method === 'keys' && targetIsMap; const innerIterator = target[method](...args); const wrap = isShallow2 ? toShallow : isReadonly2 ? toReadonly : toReactive; - !isReadonly2 && track( - rawTarget, - "iterate", - isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY - ); - return { - // iterator protocol - next() { - const { value, done } = innerIterator.next(); - return done ? { value, done } : { - value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), - done - }; - }, - // iterable protocol - [Symbol.iterator]() { - return this; + !isReadonly2 && + track( + rawTarget, + 'iterate', + isKeyOnly ? MAP_KEY_ITERATE_KEY : ITERATE_KEY + ); + return extend( + // inheriting all iterator properties + Object.create(innerIterator), + { + // iterator protocol + next() { + const { value, done } = innerIterator.next(); + return done + ? { value, done } + : { + value: isPair ? [wrap(value[0]), wrap(value[1])] : wrap(value), + done, + }; + }, } - }; + ); }; } function createReadonlyMethod(type) { - return function(...args) { + return function (...args) { if (true) { const key = args[0] ? `on key "${args[0]}" ` : ``; warn( @@ -1391,20 +1461,20 @@ function createReadonlyMethod(type) { toRaw(this) ); } - return type === "delete" ? false : type === "clear" ? void 0 : this; + return type === 'delete' ? false : type === 'clear' ? void 0 : this; }; } function createInstrumentations(readonly2, shallow) { const instrumentations = { get(key) { - const target = this["__v_raw"]; + const target = this['__v_raw']; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (!readonly2) { if (hasChanged(key, rawKey)) { - track(rawTarget, "get", key); + track(rawTarget, 'get', key); } - track(rawTarget, "get", rawKey); + track(rawTarget, 'get', rawKey); } const { has } = getProto(rawTarget); const wrap = shallow ? toShallow : readonly2 ? toReadonly : toReactive; @@ -1417,117 +1487,114 @@ function createInstrumentations(readonly2, shallow) { } }, get size() { - const target = this["__v_raw"]; - !readonly2 && track(toRaw(target), "iterate", ITERATE_KEY); + const target = this['__v_raw']; + !readonly2 && track(toRaw(target), 'iterate', ITERATE_KEY); return target.size; }, has(key) { - const target = this["__v_raw"]; + const target = this['__v_raw']; const rawTarget = toRaw(target); const rawKey = toRaw(key); if (!readonly2) { if (hasChanged(key, rawKey)) { - track(rawTarget, "has", key); + track(rawTarget, 'has', key); } - track(rawTarget, "has", rawKey); + track(rawTarget, 'has', rawKey); } - return key === rawKey ? target.has(key) : target.has(key) || target.has(rawKey); + return key === rawKey + ? target.has(key) + : target.has(key) || target.has(rawKey); }, forEach(callback, thisArg) { const observed = this; - const target = observed["__v_raw"]; + const target = observed['__v_raw']; const rawTarget = toRaw(target); const wrap = shallow ? toShallow : readonly2 ? toReadonly : toReactive; - !readonly2 && track(rawTarget, "iterate", ITERATE_KEY); + !readonly2 && track(rawTarget, 'iterate', ITERATE_KEY); return target.forEach((value, key) => { return callback.call(thisArg, wrap(value), wrap(key), observed); }); - } + }, }; extend( instrumentations, - readonly2 ? { - add: createReadonlyMethod("add"), - set: createReadonlyMethod("set"), - delete: createReadonlyMethod("delete"), - clear: createReadonlyMethod("clear") - } : { - add(value) { - if (!shallow && !isShallow(value) && !isReadonly(value)) { - value = toRaw(value); + readonly2 + ? { + add: createReadonlyMethod('add'), + set: createReadonlyMethod('set'), + delete: createReadonlyMethod('delete'), + clear: createReadonlyMethod('clear'), } - const target = toRaw(this); - const proto = getProto(target); - const hadKey = proto.has.call(target, value); - if (!hadKey) { - target.add(value); - trigger(target, "add", value, value); + : { + add(value) { + if (!shallow && !isShallow(value) && !isReadonly(value)) { + value = toRaw(value); + } + const target = toRaw(this); + const proto = getProto(target); + const hadKey = proto.has.call(target, value); + if (!hadKey) { + target.add(value); + trigger(target, 'add', value, value); + } + return this; + }, + set(key, value) { + if (!shallow && !isShallow(value) && !isReadonly(value)) { + value = toRaw(value); + } + const target = toRaw(this); + const { has, get } = getProto(target); + let hadKey = has.call(target, key); + if (!hadKey) { + key = toRaw(key); + hadKey = has.call(target, key); + } else if (true) { + checkIdentityKeys(target, has, key); + } + const oldValue = get.call(target, key); + target.set(key, value); + if (!hadKey) { + trigger(target, 'add', key, value); + } else if (hasChanged(value, oldValue)) { + trigger(target, 'set', key, value, oldValue); + } + return this; + }, + delete(key) { + const target = toRaw(this); + const { has, get } = getProto(target); + let hadKey = has.call(target, key); + if (!hadKey) { + key = toRaw(key); + hadKey = has.call(target, key); + } else if (true) { + checkIdentityKeys(target, has, key); + } + const oldValue = get ? get.call(target, key) : void 0; + const result = target.delete(key); + if (hadKey) { + trigger(target, 'delete', key, void 0, oldValue); + } + return result; + }, + clear() { + const target = toRaw(this); + const hadItems = target.size !== 0; + const oldTarget = true + ? isMap(target) + ? new Map(target) + : new Set(target) + : void 0; + const result = target.clear(); + if (hadItems) { + trigger(target, 'clear', void 0, void 0, oldTarget); + } + return result; + }, } - return this; - }, - set(key, value) { - if (!shallow && !isShallow(value) && !isReadonly(value)) { - value = toRaw(value); - } - const target = toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = toRaw(key); - hadKey = has.call(target, key); - } else if (true) { - checkIdentityKeys(target, has, key); - } - const oldValue = get.call(target, key); - target.set(key, value); - if (!hadKey) { - trigger(target, "add", key, value); - } else if (hasChanged(value, oldValue)) { - trigger(target, "set", key, value, oldValue); - } - return this; - }, - delete(key) { - const target = toRaw(this); - const { has, get } = getProto(target); - let hadKey = has.call(target, key); - if (!hadKey) { - key = toRaw(key); - hadKey = has.call(target, key); - } else if (true) { - checkIdentityKeys(target, has, key); - } - const oldValue = get ? get.call(target, key) : void 0; - const result = target.delete(key); - if (hadKey) { - trigger(target, "delete", key, void 0, oldValue); - } - return result; - }, - clear() { - const target = toRaw(this); - const hadItems = target.size !== 0; - const oldTarget = true ? isMap(target) ? new Map(target) : new Set(target) : void 0; - const result = target.clear(); - if (hadItems) { - trigger( - target, - "clear", - void 0, - void 0, - oldTarget - ); - } - return result; - } - } ); - const iteratorMethods = [ - "keys", - "values", - "entries", - Symbol.iterator - ]; + const iteratorMethods = ['keys', 'values', 'entries', Symbol.iterator]; iteratorMethods.forEach((method) => { instrumentations[method] = createIterableMethod(method, readonly2, shallow); }); @@ -1536,31 +1603,33 @@ function createInstrumentations(readonly2, shallow) { function createInstrumentationGetter(isReadonly2, shallow) { const instrumentations = createInstrumentations(isReadonly2, shallow); return (target, key, receiver) => { - if (key === "__v_isReactive") { + if (key === '__v_isReactive') { return !isReadonly2; - } else if (key === "__v_isReadonly") { + } else if (key === '__v_isReadonly') { return isReadonly2; - } else if (key === "__v_raw") { + } else if (key === '__v_raw') { return target; } return Reflect.get( - hasOwn(instrumentations, key) && key in target ? instrumentations : target, + hasOwn(instrumentations, key) && key in target + ? instrumentations + : target, key, receiver ); }; } var mutableCollectionHandlers = { - get: createInstrumentationGetter(false, false) + get: createInstrumentationGetter(false, false), }; var shallowCollectionHandlers = { - get: createInstrumentationGetter(false, true) + get: createInstrumentationGetter(false, true), }; var readonlyCollectionHandlers = { - get: createInstrumentationGetter(true, false) + get: createInstrumentationGetter(true, false), }; var shallowReadonlyCollectionHandlers = { - get: createInstrumentationGetter(true, true) + get: createInstrumentationGetter(true, true), }; function checkIdentityKeys(target, has, key) { const rawKey = toRaw(key); @@ -1577,20 +1646,22 @@ var readonlyMap = /* @__PURE__ */ new WeakMap(); var shallowReadonlyMap = /* @__PURE__ */ new WeakMap(); function targetTypeMap(rawType) { switch (rawType) { - case "Object": - case "Array": + case 'Object': + case 'Array': return 1; - case "Map": - case "Set": - case "WeakMap": - case "WeakSet": + case 'Map': + case 'Set': + case 'WeakMap': + case 'WeakSet': return 2; default: return 0; } } function getTargetType(value) { - return value["__v_skip"] || !Object.isExtensible(value) ? 0 : targetTypeMap(toRawType(value)); + return value['__v_skip'] || !Object.isExtensible(value) + ? 0 + : targetTypeMap(toRawType(value)); } function reactive(target) { if (isReadonly(target)) { @@ -1631,18 +1702,24 @@ function shallowReadonly(target) { shallowReadonlyMap ); } -function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandlers, proxyMap) { +function createReactiveObject( + target, + isReadonly2, + baseHandlers, + collectionHandlers, + proxyMap +) { if (!isObject(target)) { if (true) { warn( - `value cannot be made ${isReadonly2 ? "readonly" : "reactive"}: ${String( + `value cannot be made ${isReadonly2 ? 'readonly' : 'reactive'}: ${String( target )}` ); } return target; } - if (target["__v_raw"] && !(isReadonly2 && target["__v_isReactive"])) { + if (target['__v_raw'] && !(isReadonly2 && target['__v_isReactive'])) { return target; } const targetType = getTargetType(target); @@ -1662,33 +1739,33 @@ function createReactiveObject(target, isReadonly2, baseHandlers, collectionHandl } function isReactive(value) { if (isReadonly(value)) { - return isReactive(value["__v_raw"]); + return isReactive(value['__v_raw']); } - return !!(value && value["__v_isReactive"]); + return !!(value && value['__v_isReactive']); } function isReadonly(value) { - return !!(value && value["__v_isReadonly"]); + return !!(value && value['__v_isReadonly']); } function isShallow(value) { - return !!(value && value["__v_isShallow"]); + return !!(value && value['__v_isShallow']); } function isProxy(value) { - return value ? !!value["__v_raw"] : false; + return value ? !!value['__v_raw'] : false; } function toRaw(observed) { - const raw = observed && observed["__v_raw"]; + const raw = observed && observed['__v_raw']; return raw ? toRaw(raw) : observed; } function markRaw(value) { - if (!hasOwn(value, "__v_skip") && Object.isExtensible(value)) { - def(value, "__v_skip", true); + if (!hasOwn(value, '__v_skip') && Object.isExtensible(value)) { + def(value, '__v_skip', true); } return value; } -var toReactive = (value) => isObject(value) ? reactive(value) : value; -var toReadonly = (value) => isObject(value) ? readonly(value) : value; +var toReactive = (value) => (isObject(value) ? reactive(value) : value); +var toReadonly = (value) => (isObject(value) ? readonly(value) : value); function isRef2(r) { - return r ? r["__v_isRef"] === true : false; + return r ? r['__v_isRef'] === true : false; } function ref(value) { return createRef(value, false); @@ -1705,18 +1782,18 @@ function createRef(rawValue, shallow) { var RefImpl = class { constructor(value, isShallow2) { this.dep = new Dep(); - this["__v_isRef"] = true; - this["__v_isShallow"] = false; + this['__v_isRef'] = true; + this['__v_isShallow'] = false; this._rawValue = isShallow2 ? value : toRaw(value); this._value = isShallow2 ? value : toReactive(value); - this["__v_isShallow"] = isShallow2; + this['__v_isShallow'] = isShallow2; } get value() { if (true) { this.dep.track({ target: this, - type: "get", - key: "value" + type: 'get', + key: 'value', }); } else { this.dep.track(); @@ -1725,7 +1802,8 @@ var RefImpl = class { } set value(newValue) { const oldValue = this._rawValue; - const useDirectValue = this["__v_isShallow"] || isShallow(newValue) || isReadonly(newValue); + const useDirectValue = + this['__v_isShallow'] || isShallow(newValue) || isReadonly(newValue); newValue = useDirectValue ? newValue : toRaw(newValue); if (hasChanged(newValue, oldValue)) { this._rawValue = newValue; @@ -1733,10 +1811,10 @@ var RefImpl = class { if (true) { this.dep.trigger({ target: this, - type: "set", - key: "value", + type: 'set', + key: 'value', newValue, - oldValue + oldValue, }); } else { this.dep.trigger(); @@ -1749,9 +1827,9 @@ function triggerRef(ref2) { if (true) { ref2.dep.trigger({ target: ref2, - type: "set", - key: "value", - newValue: ref2._value + type: 'set', + key: 'value', + newValue: ref2._value, }); } else { ref2.dep.trigger(); @@ -1765,7 +1843,8 @@ function toValue(source) { return isFunction(source) ? source() : unref(source); } var shallowUnwrapHandlers = { - get: (target, key, receiver) => key === "__v_raw" ? target : unref(Reflect.get(target, key, receiver)), + get: (target, key, receiver) => + key === '__v_raw' ? target : unref(Reflect.get(target, key, receiver)), set: (target, key, value, receiver) => { const oldValue = target[key]; if (isRef2(oldValue) && !isRef2(value)) { @@ -1774,22 +1853,24 @@ var shallowUnwrapHandlers = { } else { return Reflect.set(target, key, value, receiver); } - } + }, }; function proxyRefs(objectWithRefs) { - return isReactive(objectWithRefs) ? objectWithRefs : new Proxy(objectWithRefs, shallowUnwrapHandlers); + return isReactive(objectWithRefs) + ? objectWithRefs + : new Proxy(objectWithRefs, shallowUnwrapHandlers); } var CustomRefImpl = class { constructor(factory) { - this["__v_isRef"] = true; + this['__v_isRef'] = true; this._value = void 0; - const dep = this.dep = new Dep(); + const dep = (this.dep = new Dep()); const { get, set } = factory(dep.track.bind(dep), dep.trigger.bind(dep)); this._get = get; this._set = set; } get value() { - return this._value = this._get(); + return (this._value = this._get()); } set value(newVal) { this._set(newVal); @@ -1813,7 +1894,7 @@ var ObjectRefImpl = class { this._object = _object; this._key = _key; this._defaultValue = _defaultValue; - this["__v_isRef"] = true; + this['__v_isRef'] = true; this._value = void 0; this._raw = toRaw(_object); let shallow = true; @@ -1821,7 +1902,7 @@ var ObjectRefImpl = class { if (!isArray(_object) || !isIntegerKey(String(_key))) { do { shallow = !isProxy(obj) || isShallow(obj); - } while (shallow && (obj = obj["__v_raw"])); + } while (shallow && (obj = obj['__v_raw'])); } this._shallow = shallow; } @@ -1830,7 +1911,7 @@ var ObjectRefImpl = class { if (this._shallow) { val = unref(val); } - return this._value = val === void 0 ? this._defaultValue : val; + return (this._value = val === void 0 ? this._defaultValue : val); } set value(newVal) { if (this._shallow && isRef2(this._raw[this._key])) { @@ -1849,12 +1930,12 @@ var ObjectRefImpl = class { var GetterRefImpl = class { constructor(_getter) { this._getter = _getter; - this["__v_isRef"] = true; - this["__v_isReadonly"] = true; + this['__v_isRef'] = true; + this['__v_isReadonly'] = true; this._value = void 0; } get value() { - return this._value = this._getter(); + return (this._value = this._getter()); } }; function toRef(source, key, defaultValue) { @@ -1884,7 +1965,7 @@ var ComputedRefImpl = class { this.globalVersion = globalVersion - 1; this.next = void 0; this.effect = this; - this["__v_isReadonly"] = !setter; + this['__v_isReadonly'] = !setter; this.isSSR = isSSR; } /** @@ -1892,18 +1973,22 @@ var ComputedRefImpl = class { */ notify() { this.flags |= 16; - if (!(this.flags & 8) && // avoid infinite self recursion - activeSub !== this) { + if ( + !(this.flags & 8) && // avoid infinite self recursion + activeSub !== this + ) { batch(this, true); return true; - } else if (true) ; + } else if (true); } get value() { - const link = true ? this.dep.track({ - target: this, - type: "get", - key: "value" - }) : this.dep.track(); + const link = true + ? this.dep.track({ + target: this, + type: 'get', + key: 'value', + }) + : this.dep.track(); refreshComputed(this); if (link) { link.version = this.dep.version; @@ -1914,7 +1999,7 @@ var ComputedRefImpl = class { if (this.setter) { this.setter(newValue); } else if (true) { - warn("Write operation failed: computed value is readonly"); + warn('Write operation failed: computed value is readonly'); } } }; @@ -1935,15 +2020,15 @@ function computed(getterOrOptions, debugOptions, isSSR = false) { return cRef; } var TrackOpTypes = { - "GET": "get", - "HAS": "has", - "ITERATE": "iterate" + GET: 'get', + HAS: 'has', + ITERATE: 'iterate', }; var TriggerOpTypes = { - "SET": "set", - "ADD": "add", - "DELETE": "delete", - "CLEAR": "clear" + SET: 'set', + ADD: 'add', + DELETE: 'delete', + CLEAR: 'clear', }; var INITIAL_WATCHER_VALUE = {}; var cleanupMap = /* @__PURE__ */ new WeakMap(); @@ -1951,10 +2036,14 @@ var activeWatcher = void 0; function getCurrentWatcher() { return activeWatcher; } -function onWatcherCleanup(cleanupFn, failSilently = false, owner = activeWatcher) { +function onWatcherCleanup( + cleanupFn, + failSilently = false, + owner = activeWatcher +) { if (owner) { let cleanups = cleanupMap.get(owner); - if (!cleanups) cleanupMap.set(owner, cleanups = []); + if (!cleanups) cleanupMap.set(owner, (cleanups = [])); cleanups.push(cleanupFn); } else if (!failSilently) { warn( @@ -1992,17 +2081,18 @@ function watch(source, cb, options = EMPTY_OBJ) { } else if (isArray(source)) { isMultiSource = true; forceTrigger = source.some((s) => isReactive(s) || isShallow(s)); - getter = () => source.map((s) => { - if (isRef2(s)) { - return s.value; - } else if (isReactive(s)) { - return reactiveGetter(s); - } else if (isFunction(s)) { - return call ? call(s, 2) : s(); - } else { - warnInvalidSource(s); - } - }); + getter = () => + source.map((s) => { + if (isRef2(s)) { + return s.value; + } else if (isReactive(s)) { + return reactiveGetter(s); + } else if (isFunction(s)) { + return call ? call(s, 2) : s(); + } else { + warnInvalidSource(s); + } + }); } else if (isFunction(source)) { if (cb) { getter = call ? () => call(source, 2) : source; @@ -2048,14 +2138,22 @@ function watch(source, cb, options = EMPTY_OBJ) { watchHandle(); }; } - let oldValue = isMultiSource ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) : INITIAL_WATCHER_VALUE; + let oldValue = isMultiSource + ? new Array(source.length).fill(INITIAL_WATCHER_VALUE) + : INITIAL_WATCHER_VALUE; const job = (immediateFirstRun) => { - if (!(effect2.flags & 1) || !effect2.dirty && !immediateFirstRun) { + if (!(effect2.flags & 1) || (!effect2.dirty && !immediateFirstRun)) { return; } if (cb) { const newValue = effect2.run(); - if (deep || forceTrigger || (isMultiSource ? newValue.some((v, i) => hasChanged(v, oldValue[i])) : hasChanged(newValue, oldValue))) { + if ( + deep || + forceTrigger || + (isMultiSource + ? newValue.some((v, i) => hasChanged(v, oldValue[i])) + : hasChanged(newValue, oldValue)) + ) { if (cleanup) { cleanup(); } @@ -2065,14 +2163,18 @@ function watch(source, cb, options = EMPTY_OBJ) { const args = [ newValue, // pass undefined as the old value when it's changed for the first time - oldValue === INITIAL_WATCHER_VALUE ? void 0 : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE ? [] : oldValue, - boundCleanup + oldValue === INITIAL_WATCHER_VALUE + ? void 0 + : isMultiSource && oldValue[0] === INITIAL_WATCHER_VALUE + ? [] + : oldValue, + boundCleanup, ]; oldValue = newValue; - call ? call(cb, 3, args) : ( - // @ts-expect-error - cb(...args) - ); + call + ? call(cb, 3, args) + : // @ts-expect-error + cb(...args); } finally { activeWatcher = currentWatcher; } @@ -2119,7 +2221,7 @@ function watch(source, cb, options = EMPTY_OBJ) { return watchHandle; } function traverse(value, depth = Infinity, seen) { - if (depth <= 0 || !isObject(value) || value["__v_skip"]) { + if (depth <= 0 || !isObject(value) || value['__v_skip']) { return value; } seen = seen || /* @__PURE__ */ new Map(); @@ -2168,29 +2270,35 @@ function warn$1(msg, ...args) { const appWarnHandler = instance && instance.appContext.config.warnHandler; const trace = getComponentTrace(); if (appWarnHandler) { - callWithErrorHandling( - appWarnHandler, - instance, - 11, - [ - // eslint-disable-next-line no-restricted-syntax - msg + args.map((a) => { - var _a, _b; - return (_b = (_a = a.toString) == null ? void 0 : _a.call(a)) != null ? _b : JSON.stringify(a); - }).join(""), - instance && instance.proxy, - trace.map( - ({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>` - ).join("\n"), - trace - ] - ); + callWithErrorHandling(appWarnHandler, instance, 11, [ + // eslint-disable-next-line no-restricted-syntax + msg + + args + .map((a) => { + var _a, _b; + return (_b = (_a = a.toString) == null ? void 0 : _a.call(a)) != + null + ? _b + : JSON.stringify(a); + }) + .join(''), + instance && instance.proxy, + trace + .map(({ vnode }) => `at <${formatComponentName(instance, vnode.type)}>`) + .join('\n'), + trace, + ]); } else { const warnArgs = [`[Vue warn]: ${msg}`, ...args]; - if (trace.length && // avoid spamming console during tests - true) { - warnArgs.push(` -`, ...formatTrace(trace)); + if ( + trace.length && // avoid spamming console during tests + true + ) { + warnArgs.push( + ` +`, + ...formatTrace(trace) + ); } console.warn(...warnArgs); } @@ -2210,10 +2318,11 @@ function getComponentTrace() { } else { normalizedStack.push({ vnode: currentVNode, - recurseCount: 0 + recurseCount: 0, }); } - const parentInstance = currentVNode.component && currentVNode.component.parent; + const parentInstance = + currentVNode.component && currentVNode.component.parent; currentVNode = parentInstance && parentInstance.vnode; } return normalizedStack; @@ -2221,13 +2330,21 @@ function getComponentTrace() { function formatTrace(trace) { const logs = []; trace.forEach((entry, i) => { - logs.push(...i === 0 ? [] : [` -`], ...formatTraceEntry(entry)); + logs.push( + ...(i === 0 + ? [] + : [ + ` +`, + ]), + ...formatTraceEntry(entry) + ); }); return logs; } function formatTraceEntry({ vnode, recurseCount }) { - const postfix = recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; + const postfix = + recurseCount > 0 ? `... (${recurseCount} recursive calls)` : ``; const isRoot = vnode.component ? vnode.component.parent == null : false; const open = ` at <${formatComponentName( vnode.component, @@ -2235,7 +2352,9 @@ function formatTraceEntry({ vnode, recurseCount }) { isRoot )}`; const close = `>` + postfix; - return vnode.props ? [open, ...formatProps(vnode.props), close] : [open + close]; + return vnode.props + ? [open, ...formatProps(vnode.props), close] + : [open + close]; } function formatProps(props) { const res = []; @@ -2252,7 +2371,11 @@ function formatProp(key, value, raw) { if (isString(value)) { value = JSON.stringify(value); return raw ? value : [`${key}=${value}`]; - } else if (typeof value === "number" || typeof value === "boolean" || value == null) { + } else if ( + typeof value === 'number' || + typeof value === 'boolean' || + value == null + ) { return raw ? value : [`${key}=${value}`]; } else if (isRef2(value)) { value = formatProp(key, toRaw(value.value), true); @@ -2268,74 +2391,74 @@ function assertNumber(val, type) { if (false) return; if (val === void 0) { return; - } else if (typeof val !== "number") { + } else if (typeof val !== 'number') { warn$1(`${type} is not a valid number - got ${JSON.stringify(val)}.`); } else if (isNaN(val)) { warn$1(`${type} is NaN - the duration expression might be incorrect.`); } } var ErrorCodes = { - "SETUP_FUNCTION": 0, - "0": "SETUP_FUNCTION", - "RENDER_FUNCTION": 1, - "1": "RENDER_FUNCTION", - "NATIVE_EVENT_HANDLER": 5, - "5": "NATIVE_EVENT_HANDLER", - "COMPONENT_EVENT_HANDLER": 6, - "6": "COMPONENT_EVENT_HANDLER", - "VNODE_HOOK": 7, - "7": "VNODE_HOOK", - "DIRECTIVE_HOOK": 8, - "8": "DIRECTIVE_HOOK", - "TRANSITION_HOOK": 9, - "9": "TRANSITION_HOOK", - "APP_ERROR_HANDLER": 10, - "10": "APP_ERROR_HANDLER", - "APP_WARN_HANDLER": 11, - "11": "APP_WARN_HANDLER", - "FUNCTION_REF": 12, - "12": "FUNCTION_REF", - "ASYNC_COMPONENT_LOADER": 13, - "13": "ASYNC_COMPONENT_LOADER", - "SCHEDULER": 14, - "14": "SCHEDULER", - "COMPONENT_UPDATE": 15, - "15": "COMPONENT_UPDATE", - "APP_UNMOUNT_CLEANUP": 16, - "16": "APP_UNMOUNT_CLEANUP" + SETUP_FUNCTION: 0, + 0: 'SETUP_FUNCTION', + RENDER_FUNCTION: 1, + 1: 'RENDER_FUNCTION', + NATIVE_EVENT_HANDLER: 5, + 5: 'NATIVE_EVENT_HANDLER', + COMPONENT_EVENT_HANDLER: 6, + 6: 'COMPONENT_EVENT_HANDLER', + VNODE_HOOK: 7, + 7: 'VNODE_HOOK', + DIRECTIVE_HOOK: 8, + 8: 'DIRECTIVE_HOOK', + TRANSITION_HOOK: 9, + 9: 'TRANSITION_HOOK', + APP_ERROR_HANDLER: 10, + 10: 'APP_ERROR_HANDLER', + APP_WARN_HANDLER: 11, + 11: 'APP_WARN_HANDLER', + FUNCTION_REF: 12, + 12: 'FUNCTION_REF', + ASYNC_COMPONENT_LOADER: 13, + 13: 'ASYNC_COMPONENT_LOADER', + SCHEDULER: 14, + 14: 'SCHEDULER', + COMPONENT_UPDATE: 15, + 15: 'COMPONENT_UPDATE', + APP_UNMOUNT_CLEANUP: 16, + 16: 'APP_UNMOUNT_CLEANUP', }; var ErrorTypeStrings$1 = { - ["sp"]: "serverPrefetch hook", - ["bc"]: "beforeCreate hook", - ["c"]: "created hook", - ["bm"]: "beforeMount hook", - ["m"]: "mounted hook", - ["bu"]: "beforeUpdate hook", - ["u"]: "updated", - ["bum"]: "beforeUnmount hook", - ["um"]: "unmounted hook", - ["a"]: "activated hook", - ["da"]: "deactivated hook", - ["ec"]: "errorCaptured hook", - ["rtc"]: "renderTracked hook", - ["rtg"]: "renderTriggered hook", - [0]: "setup function", - [1]: "render function", - [2]: "watcher getter", - [3]: "watcher callback", - [4]: "watcher cleanup function", - [5]: "native event handler", - [6]: "component event handler", - [7]: "vnode hook", - [8]: "directive hook", - [9]: "transition hook", - [10]: "app errorHandler", - [11]: "app warnHandler", - [12]: "ref function", - [13]: "async component loader", - [14]: "scheduler flush", - [15]: "component update", - [16]: "app unmount cleanup function" + ['sp']: 'serverPrefetch hook', + ['bc']: 'beforeCreate hook', + ['c']: 'created hook', + ['bm']: 'beforeMount hook', + ['m']: 'mounted hook', + ['bu']: 'beforeUpdate hook', + ['u']: 'updated', + ['bum']: 'beforeUnmount hook', + ['um']: 'unmounted hook', + ['a']: 'activated hook', + ['da']: 'deactivated hook', + ['ec']: 'errorCaptured hook', + ['rtc']: 'renderTracked hook', + ['rtg']: 'renderTriggered hook', + [0]: 'setup function', + [1]: 'render function', + [2]: 'watcher getter', + [3]: 'watcher callback', + [4]: 'watcher cleanup function', + [5]: 'native event handler', + [6]: 'component event handler', + [7]: 'vnode hook', + [8]: 'directive hook', + [9]: 'transition hook', + [10]: 'app errorHandler', + [11]: 'app warnHandler', + [12]: 'ref function', + [13]: 'async component loader', + [14]: 'scheduler flush', + [15]: 'component update', + [16]: 'app unmount cleanup function', }; function callWithErrorHandling(fn, instance, type, args) { try { @@ -2368,16 +2491,21 @@ function callWithAsyncErrorHandling(fn, instance, type, args) { } function handleError(err, instance, type, throwInDev = true) { const contextVNode = instance ? instance.vnode : null; - const { errorHandler, throwUnhandledErrorInProduction } = instance && instance.appContext.config || EMPTY_OBJ; + const { errorHandler, throwUnhandledErrorInProduction } = + (instance && instance.appContext.config) || EMPTY_OBJ; if (instance) { let cur = instance.parent; const exposedInstance = instance.proxy; - const errorInfo = true ? ErrorTypeStrings$1[type] : `https://vuejs.org/error-reference/#runtime-${type}`; + const errorInfo = true + ? ErrorTypeStrings$1[type] + : `https://vuejs.org/error-reference/#runtime-${type}`; while (cur) { const errorCapturedHooks = cur.ec; if (errorCapturedHooks) { for (let i = 0; i < errorCapturedHooks.length; i++) { - if (errorCapturedHooks[i](err, exposedInstance, errorInfo) === false) { + if ( + errorCapturedHooks[i](err, exposedInstance, errorInfo) === false + ) { return; } } @@ -2389,15 +2517,27 @@ function handleError(err, instance, type, throwInDev = true) { callWithErrorHandling(errorHandler, null, 10, [ err, exposedInstance, - errorInfo + errorInfo, ]); resetTracking(); return; } } - logError(err, type, contextVNode, throwInDev, throwUnhandledErrorInProduction); + logError( + err, + type, + contextVNode, + throwInDev, + throwUnhandledErrorInProduction + ); } -function logError(err, type, contextVNode, throwInDev = true, throwInProd = false) { +function logError( + err, + type, + contextVNode, + throwInDev = true, + throwInProd = false +) { if (true) { const info = ErrorTypeStrings$1[type]; if (contextVNode) { @@ -2434,10 +2574,10 @@ function findInsertionIndex(id) { let start = flushIndex + 1; let end = queue.length; while (start < end) { - const middle = start + end >>> 1; + const middle = (start + end) >>> 1; const middleJob = queue[middle]; const middleJobId = getId(middleJob); - if (middleJobId < id || middleJobId === id && middleJob.flags & 2) { + if (middleJobId < id || (middleJobId === id && middleJob.flags & 2)) { start = middle + 1; } else { end = middle; @@ -2449,8 +2589,10 @@ function queueJob(job) { if (!(job.flags & 1)) { const jobId = getId(job); const lastJob = queue[queue.length - 1]; - if (!lastJob || // fast path when the job id is larger than the tail - !(job.flags & 2) && jobId >= getId(lastJob)) { + if ( + !lastJob || // fast path when the job id is larger than the tail + (!(job.flags & 2) && jobId >= getId(lastJob)) + ) { queue.push(job); } else { queue.splice(findInsertionIndex(jobId), 0, job); @@ -2516,7 +2658,11 @@ function flushPostFlushCbs(seen) { if (true) { seen = seen || /* @__PURE__ */ new Map(); } - for (postFlushIndex = 0; postFlushIndex < activePostFlushCbs.length; postFlushIndex++) { + for ( + postFlushIndex = 0; + postFlushIndex < activePostFlushCbs.length; + postFlushIndex++ + ) { const cb = activePostFlushCbs[postFlushIndex]; if (checkRecursiveUpdates(seen, cb)) { continue; @@ -2531,7 +2677,8 @@ function flushPostFlushCbs(seen) { postFlushIndex = 0; } } -var getId = (job) => job.id == null ? job.flags & 2 ? -1 : Infinity : job.id; +var getId = (job) => + job.id == null ? (job.flags & 2 ? -1 : Infinity) : job.id; function flushJobs(seen) { if (true) { seen = seen || /* @__PURE__ */ new Map(); @@ -2547,11 +2694,7 @@ function flushJobs(seen) { if (job.flags & 4) { job.flags &= ~1; } - callWithErrorHandling( - job, - job.i, - job.i ? 15 : 14 - ); + callWithErrorHandling(job, job.i, job.i ? 15 : 14); if (!(job.flags & 4)) { job.flags &= ~1; } @@ -2594,7 +2737,7 @@ if (true) { getGlobalThis().__VUE_HMR_RUNTIME__ = { createRecord: tryWrap(createRecord), rerender: tryWrap(rerender), - reload: tryWrap(reload) + reload: tryWrap(reload), }; } var map = /* @__PURE__ */ new Map(); @@ -2616,7 +2759,7 @@ function createRecord(id, initialDef) { } map.set(id, { initialDef: normalizeClassComponent(initialDef), - instances: /* @__PURE__ */ new Set() + instances: /* @__PURE__ */ new Set(), }); return true; } @@ -2656,7 +2799,10 @@ function reload(id, newComp) { if (oldComp !== record.initialDef) { updateComponentDef(oldComp, newComp); } - hmrDirtyComponents.set(oldComp, dirtyInstances = /* @__PURE__ */ new Set()); + hmrDirtyComponents.set( + oldComp, + (dirtyInstances = /* @__PURE__ */ new Set()) + ); } dirtyInstances.add(instance); instance.appContext.propsCache.delete(instance.type); @@ -2677,11 +2823,11 @@ function reload(id, newComp) { }); } else if (instance.appContext.reload) { instance.appContext.reload(); - } else if (typeof window !== "undefined") { + } else if (typeof window !== 'undefined') { window.location.reload(); } else { console.warn( - "[HMR] Root or manually mounted instance modified. Full reload required." + '[HMR] Root or manually mounted instance modified. Full reload required.' ); } if (instance.root.ce && instance !== instance.root) { @@ -2695,7 +2841,7 @@ function reload(id, newComp) { function updateComponentDef(oldComp, newComp) { extend(oldComp, newComp); for (const key in oldComp) { - if (key !== "__file" && !(key in newComp)) { + if (key !== '__file' && !(key in newComp)) { delete oldComp[key]; } } @@ -2733,12 +2879,15 @@ function setDevtoolsHook$1(hook, target) { // handle late devtools injection - only do this if we are in an actual // browser environment to avoid the timer handle stalling test runner exit // (#4815) - typeof window !== "undefined" && // some envs mock window but not fully + typeof window !== 'undefined' && // some envs mock window but not fully window.HTMLElement && // also exclude jsdom // eslint-disable-next-line no-restricted-syntax - !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null ? void 0 : _b.includes("jsdom")) + !((_b = (_a = window.navigator) == null ? void 0 : _a.userAgent) == null + ? void 0 + : _b.includes('jsdom')) ) { - const replay = target.__VUE_DEVTOOLS_HOOK_REPLAY__ = target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []; + const replay = (target.__VUE_DEVTOOLS_HOOK_REPLAY__ = + target.__VUE_DEVTOOLS_HOOK_REPLAY__ || []); replay.push((newHook) => { setDevtoolsHook$1(newHook, target); }); @@ -2755,31 +2904,34 @@ function setDevtoolsHook$1(hook, target) { } } function devtoolsInitApp(app, version2) { - emit$1("app:init", app, version2, { + emit$1('app:init', app, version2, { Fragment, Text, Comment, - Static + Static, }); } function devtoolsUnmountApp(app) { - emit$1("app:unmount", app); + emit$1('app:unmount', app); } var devtoolsComponentAdded = createDevtoolsComponentHook( - "component:added" + 'component:added' /* COMPONENT_ADDED */ ); var devtoolsComponentUpdated = createDevtoolsComponentHook( - "component:updated" + 'component:updated' /* COMPONENT_UPDATED */ ); var _devtoolsComponentRemoved = createDevtoolsComponentHook( - "component:removed" + 'component:removed' /* COMPONENT_REMOVED */ ); var devtoolsComponentRemoved = (component) => { - if (devtools$1 && typeof devtools$1.cleanupBuffer === "function" && // remove the component if it wasn't buffered - !devtools$1.cleanupBuffer(component)) { + if ( + devtools$1 && + typeof devtools$1.cleanupBuffer === 'function' && // remove the component if it wasn't buffered + !devtools$1.cleanupBuffer(component) + ) { _devtoolsComponentRemoved(component); } }; @@ -2795,33 +2947,34 @@ function createDevtoolsComponentHook(hook) { }; } var devtoolsPerfStart = createDevtoolsPerformanceHook( - "perf:start" + 'perf:start' /* PERFORMANCE_START */ ); var devtoolsPerfEnd = createDevtoolsPerformanceHook( - "perf:end" + 'perf:end' /* PERFORMANCE_END */ ); function createDevtoolsPerformanceHook(hook) { return (component, type, time) => { - emit$1(hook, component.appContext.app, component.uid, component, type, time); + emit$1( + hook, + component.appContext.app, + component.uid, + component, + type, + time + ); }; } function devtoolsComponentEmit(component, event, params) { - emit$1( - "component:emit", - component.appContext.app, - component, - event, - params - ); + emit$1('component:emit', component.appContext.app, component, event, params); } var currentRenderingInstance = null; var currentScopeId = null; function setCurrentRenderingInstance(instance) { const prev = currentRenderingInstance; currentRenderingInstance = instance; - currentScopeId = instance && instance.type.__scopeId || null; + currentScopeId = (instance && instance.type.__scopeId) || null; return prev; } function pushScopeId(id) { @@ -2862,7 +3015,7 @@ function withCtx(fn, ctx = currentRenderingInstance, isNonScopedSlot) { } function validateDirectiveName(name) { if (isBuiltInDirective(name)) { - warn$1("Do not use built-in directive ids as custom directive id: " + name); + warn$1('Do not use built-in directive ids as custom directive id: ' + name); } } function withDirectives(vnode, directives) { @@ -2878,7 +3031,7 @@ function withDirectives(vnode, directives) { if (isFunction(dir)) { dir = { mounted: dir, - updated: dir + updated: dir, }; } if (dir.deep) { @@ -2890,7 +3043,7 @@ function withDirectives(vnode, directives) { value, oldValue: void 0, arg, - modifiers + modifiers, }); } } @@ -2911,7 +3064,7 @@ function invokeDirectiveHook(vnode, prevVNode, instance, name) { vnode.el, binding, vnode, - prevVNode + prevVNode, ]); resetTracking(); } @@ -2925,7 +3078,8 @@ function provide(key, value) { } if (currentInstance) { let provides = currentInstance.provides; - const parentProvides = currentInstance.parent && currentInstance.parent.provides; + const parentProvides = + currentInstance.parent && currentInstance.parent.provides; if (parentProvides === provides) { provides = currentInstance.provides = Object.create(parentProvides); } @@ -2935,22 +3089,32 @@ function provide(key, value) { function inject(key, defaultValue, treatDefaultAsFactory = false) { const instance = getCurrentInstance(); if (instance || currentApp) { - let provides = currentApp ? currentApp._context.provides : instance ? instance.parent == null || instance.ce ? instance.vnode.appContext && instance.vnode.appContext.provides : instance.parent.provides : void 0; + let provides = currentApp + ? currentApp._context.provides + : instance + ? instance.parent == null || instance.ce + ? instance.vnode.appContext && instance.vnode.appContext.provides + : instance.parent.provides + : void 0; if (provides && key in provides) { return provides[key]; } else if (arguments.length > 1) { - return treatDefaultAsFactory && isFunction(defaultValue) ? defaultValue.call(instance && instance.proxy) : defaultValue; + return treatDefaultAsFactory && isFunction(defaultValue) + ? defaultValue.call(instance && instance.proxy) + : defaultValue; } else if (true) { warn$1(`injection "${String(key)}" not found.`); } } else if (true) { - warn$1(`inject() can only be used inside setup() or functional components.`); + warn$1( + `inject() can only be used inside setup() or functional components.` + ); } } function hasInjectionContext() { return !!(getCurrentInstance() || currentApp); } -var ssrContextKey = Symbol.for("v-scx"); +var ssrContextKey = Symbol.for('v-scx'); var useSSRContext = () => { { const ctx = inject(ssrContextKey); @@ -2969,14 +3133,14 @@ function watchPostEffect(effect2, options) { return doWatch( effect2, null, - true ? extend({}, options, { flush: "post" }) : { flush: "post" } + true ? extend({}, options, { flush: 'post' }) : { flush: 'post' } ); } function watchSyncEffect(effect2, options) { return doWatch( effect2, null, - true ? extend({}, options, { flush: "sync" }) : { flush: "sync" } + true ? extend({}, options, { flush: 'sync' }) : { flush: 'sync' } ); } function watch2(source, cb, options) { @@ -3008,15 +3172,14 @@ function doWatch(source, cb, options = EMPTY_OBJ) { } const baseWatchOptions = extend({}, options); if (true) baseWatchOptions.onWarn = warn$1; - const runsImmediately = cb && immediate || !cb && flush !== "post"; + const runsImmediately = (cb && immediate) || (!cb && flush !== 'post'); let ssrCleanup; if (isInSSRComponentSetup) { - if (flush === "sync") { + if (flush === 'sync') { const ctx = useSSRContext(); ssrCleanup = ctx.__watcherHandles || (ctx.__watcherHandles = []); } else if (!runsImmediately) { - const watchStopHandle = () => { - }; + const watchStopHandle = () => {}; watchStopHandle.stop = NOOP; watchStopHandle.resume = NOOP; watchStopHandle.pause = NOOP; @@ -3024,13 +3187,14 @@ function doWatch(source, cb, options = EMPTY_OBJ) { } } const instance = currentInstance; - baseWatchOptions.call = (fn, type, args) => callWithAsyncErrorHandling(fn, instance, type, args); + baseWatchOptions.call = (fn, type, args) => + callWithAsyncErrorHandling(fn, instance, type, args); let isPre = false; - if (flush === "post") { + if (flush === 'post') { baseWatchOptions.scheduler = (job) => { queuePostRenderEffect(job, instance && instance.suspense); }; - } else if (flush !== "sync") { + } else if (flush !== 'sync') { isPre = true; baseWatchOptions.scheduler = (job, isFirstRun) => { if (isFirstRun) { @@ -3064,7 +3228,11 @@ function doWatch(source, cb, options = EMPTY_OBJ) { } function instanceWatch(source, value, options) { const publicThis = this.proxy; - const getter = isString(source) ? source.includes(".") ? createPathGetter(publicThis, source) : () => publicThis[source] : source.bind(publicThis, publicThis); + const getter = isString(source) + ? source.includes('.') + ? createPathGetter(publicThis, source) + : () => publicThis[source] + : source.bind(publicThis, publicThis); let cb; if (isFunction(value)) { cb = value; @@ -3078,7 +3246,7 @@ function instanceWatch(source, value, options) { return res; } function createPathGetter(ctx, path) { - const segments = path.split("."); + const segments = path.split('.'); return () => { let cur = ctx; for (let i = 0; i < segments.length && cur; i++) { @@ -3087,12 +3255,16 @@ function createPathGetter(ctx, path) { return cur; }; } -var TeleportEndKey = Symbol("_vte"); +var TeleportEndKey = Symbol('_vte'); var isTeleport = (type) => type.__isTeleport; -var isTeleportDisabled = (props) => props && (props.disabled || props.disabled === ""); -var isTeleportDeferred = (props) => props && (props.defer || props.defer === ""); -var isTargetSVG = (target) => typeof SVGElement !== "undefined" && target instanceof SVGElement; -var isTargetMathML = (target) => typeof MathMLElement === "function" && target instanceof MathMLElement; +var isTeleportDisabled = (props) => + props && (props.disabled || props.disabled === ''); +var isTeleportDeferred = (props) => + props && (props.defer || props.defer === ''); +var isTargetSVG = (target) => + typeof SVGElement !== 'undefined' && target instanceof SVGElement; +var isTargetMathML = (target) => + typeof MathMLElement === 'function' && target instanceof MathMLElement; var resolveTarget = (props, select) => { const targetSelector = props && props.to; if (isString(targetSelector)) { @@ -3118,14 +3290,25 @@ var resolveTarget = (props, select) => { } }; var TeleportImpl = { - name: "Teleport", + name: 'Teleport', __isTeleport: true, - process(n1, n2, container, anchor, parentComponent, parentSuspense, namespace, slotScopeIds, optimized, internals) { + process( + n1, + n2, + container, + anchor, + parentComponent, + parentSuspense, + namespace, + slotScopeIds, + optimized, + internals + ) { const { mc: mountChildren, pc: patchChildren, pbc: patchBlockChildren, - o: { insert, querySelector, createText, createComment } + o: { insert, querySelector, createText, createComment }, } = internals; const disabled = isTeleportDisabled(n2.props); let { shapeFlag, children, dynamicChildren } = n2; @@ -3134,8 +3317,12 @@ var TeleportImpl = { dynamicChildren = null; } if (n1 == null) { - const placeholder = n2.el = true ? createComment("teleport start") : createText(""); - const mainAnchor = n2.anchor = true ? createComment("teleport end") : createText(""); + const placeholder = (n2.el = true + ? createComment('teleport start') + : createText('')); + const mainAnchor = (n2.anchor = true + ? createComment('teleport end') + : createText('')); insert(placeholder, container, anchor); insert(mainAnchor, container, anchor); const mount = (container2, anchor2) => { @@ -3153,16 +3340,19 @@ var TeleportImpl = { } }; const mountToTarget = () => { - const target = n2.target = resolveTarget(n2.props, querySelector); + const target = (n2.target = resolveTarget(n2.props, querySelector)); const targetAnchor = prepareAnchor(target, n2, createText, insert); if (target) { - if (namespace !== "svg" && isTargetSVG(target)) { - namespace = "svg"; - } else if (namespace !== "mathml" && isTargetMathML(target)) { - namespace = "mathml"; + if (namespace !== 'svg' && isTargetSVG(target)) { + namespace = 'svg'; + } else if (namespace !== 'mathml' && isTargetMathML(target)) { + namespace = 'mathml'; } if (parentComponent && parentComponent.isCE) { - (parentComponent.ce._teleportTargets || (parentComponent.ce._teleportTargets = /* @__PURE__ */ new Set())).add(target); + ( + parentComponent.ce._teleportTargets || + (parentComponent.ce._teleportTargets = /* @__PURE__ */ new Set()) + ).add(target); } if (!disabled) { mount(target, targetAnchor); @@ -3170,7 +3360,7 @@ var TeleportImpl = { } } else if (!disabled) { warn$1( - "Invalid Teleport target on mount:", + 'Invalid Teleport target on mount:', target, `(${typeof target})` ); @@ -3209,16 +3399,16 @@ var TeleportImpl = { } n2.el = n1.el; n2.targetStart = n1.targetStart; - const mainAnchor = n2.anchor = n1.anchor; - const target = n2.target = n1.target; - const targetAnchor = n2.targetAnchor = n1.targetAnchor; + const mainAnchor = (n2.anchor = n1.anchor); + const target = (n2.target = n1.target); + const targetAnchor = (n2.targetAnchor = n1.targetAnchor); const wasDisabled = isTeleportDisabled(n1.props); const currentContainer = wasDisabled ? container : target; const currentAnchor = wasDisabled ? mainAnchor : targetAnchor; - if (namespace === "svg" || isTargetSVG(target)) { - namespace = "svg"; - } else if (namespace === "mathml" || isTargetMathML(target)) { - namespace = "mathml"; + if (namespace === 'svg' || isTargetSVG(target)) { + namespace = 'svg'; + } else if (namespace === 'mathml' || isTargetMathML(target)) { + namespace = 'mathml'; } if (dynamicChildren) { patchBlockChildren( @@ -3246,13 +3436,7 @@ var TeleportImpl = { } if (disabled) { if (!wasDisabled) { - moveTeleport( - n2, - container, - mainAnchor, - internals, - 1 - ); + moveTeleport(n2, container, mainAnchor, internals, 1); } else { if (n2.props && n1.props && n2.props.to !== n1.props.to) { n2.props.to = n1.props.to; @@ -3260,39 +3444,33 @@ var TeleportImpl = { } } else { if ((n2.props && n2.props.to) !== (n1.props && n1.props.to)) { - const nextTarget = n2.target = resolveTarget( + const nextTarget = (n2.target = resolveTarget( n2.props, querySelector - ); + )); if (nextTarget) { - moveTeleport( - n2, - nextTarget, - null, - internals, - 0 - ); + moveTeleport(n2, nextTarget, null, internals, 0); } else if (true) { warn$1( - "Invalid Teleport target on update:", + 'Invalid Teleport target on update:', target, `(${typeof target})` ); } } else if (wasDisabled) { - moveTeleport( - n2, - target, - targetAnchor, - internals, - 1 - ); + moveTeleport(n2, target, targetAnchor, internals, 1); } } updateCssVars(n2, disabled); } }, - remove(vnode, parentComponent, parentSuspense, { um: unmount, o: { remove: hostRemove } }, doRemove) { + remove( + vnode, + parentComponent, + parentSuspense, + { um: unmount, o: { remove: hostRemove } }, + doRemove + ) { const { shapeFlag, children, @@ -3300,7 +3478,7 @@ var TeleportImpl = { targetStart, targetAnchor, target, - props + props, } = vnode; if (target) { hostRemove(targetStart); @@ -3322,9 +3500,15 @@ var TeleportImpl = { } }, move: moveTeleport, - hydrate: hydrateTeleport + hydrate: hydrateTeleport, }; -function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move }, moveType = 2) { +function moveTeleport( + vnode, + container, + parentAnchor, + { o: { insert }, m: move }, + moveType = 2 +) { if (moveType === 0) { insert(vnode.targetAnchor, container, parentAnchor); } @@ -3336,12 +3520,7 @@ function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move } if (!isReorder || isTeleportDisabled(props)) { if (shapeFlag & 16) { for (let i = 0; i < children.length; i++) { - move( - children[i], - container, - parentAnchor, - 2 - ); + move(children[i], container, parentAnchor, 2); } } } @@ -3349,10 +3528,32 @@ function moveTeleport(vnode, container, parentAnchor, { o: { insert }, m: move } insert(anchor, container, parentAnchor); } } -function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized, { - o: { nextSibling, parentNode, querySelector, insert, createText } -}, hydrateChildren) { - function hydrateDisabledTeleport(node2, vnode2, targetStart, targetAnchor) { +function hydrateTeleport( + node, + vnode, + parentComponent, + parentSuspense, + slotScopeIds, + optimized, + { o: { nextSibling, parentNode, querySelector, insert, createText } }, + hydrateChildren +) { + function hydrateAnchor(target2, targetNode) { + let targetAnchor = targetNode; + while (targetAnchor) { + if (targetAnchor && targetAnchor.nodeType === 8) { + if (targetAnchor.data === 'teleport start anchor') { + vnode.targetStart = targetAnchor; + } else if (targetAnchor.data === 'teleport anchor') { + vnode.targetAnchor = targetAnchor; + target2._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor); + break; + } + } + targetAnchor = nextSibling(targetAnchor); + } + } + function hydrateDisabledTeleport(node2, vnode2) { vnode2.anchor = hydrateChildren( nextSibling(node2), vnode2, @@ -3362,39 +3563,29 @@ function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScope slotScopeIds, optimized ); - vnode2.targetStart = targetStart; - vnode2.targetAnchor = targetAnchor; } - const target = vnode.target = resolveTarget( - vnode.props, - querySelector - ); + const target = (vnode.target = resolveTarget(vnode.props, querySelector)); const disabled = isTeleportDisabled(vnode.props); if (target) { const targetNode = target._lpa || target.firstChild; if (vnode.shapeFlag & 16) { if (disabled) { - hydrateDisabledTeleport( - node, - vnode, - targetNode, - targetNode && nextSibling(targetNode) - ); + hydrateDisabledTeleport(node, vnode); + hydrateAnchor(target, targetNode); + if (!vnode.targetAnchor) { + prepareAnchor( + target, + vnode, + createText, + insert, + // if target is the same as the main view, insert anchors before current node + // to avoid hydrating mismatch + parentNode(node) === target ? node : null + ); + } } else { vnode.anchor = nextSibling(node); - let targetAnchor = targetNode; - while (targetAnchor) { - if (targetAnchor && targetAnchor.nodeType === 8) { - if (targetAnchor.data === "teleport start anchor") { - vnode.targetStart = targetAnchor; - } else if (targetAnchor.data === "teleport anchor") { - vnode.targetAnchor = targetAnchor; - target._lpa = vnode.targetAnchor && nextSibling(vnode.targetAnchor); - break; - } - } - targetAnchor = nextSibling(targetAnchor); - } + hydrateAnchor(target, targetNode); if (!vnode.targetAnchor) { prepareAnchor(target, vnode, createText, insert); } @@ -3412,7 +3603,9 @@ function hydrateTeleport(node, vnode, parentComponent, parentSuspense, slotScope updateCssVars(vnode, disabled); } else if (disabled) { if (vnode.shapeFlag & 16) { - hydrateDisabledTeleport(node, vnode, node, nextSibling(node)); + hydrateDisabledTeleport(node, vnode); + vnode.targetStart = node; + vnode.targetAnchor = nextSibling(node); } } return vnode.anchor && nextSibling(vnode.anchor); @@ -3430,30 +3623,30 @@ function updateCssVars(vnode, isDisabled) { anchor = vnode.targetAnchor; } while (node && node !== anchor) { - if (node.nodeType === 1) node.setAttribute("data-v-owner", ctx.uid); + if (node.nodeType === 1) node.setAttribute('data-v-owner', ctx.uid); node = node.nextSibling; } ctx.ut(); } } -function prepareAnchor(target, vnode, createText, insert) { - const targetStart = vnode.targetStart = createText(""); - const targetAnchor = vnode.targetAnchor = createText(""); +function prepareAnchor(target, vnode, createText, insert, anchor = null) { + const targetStart = (vnode.targetStart = createText('')); + const targetAnchor = (vnode.targetAnchor = createText('')); targetStart[TeleportEndKey] = targetAnchor; if (target) { - insert(targetStart, target); - insert(targetAnchor, target); + insert(targetStart, target, anchor); + insert(targetAnchor, target, anchor); } return targetAnchor; } -var leaveCbKey = Symbol("_leaveCb"); -var enterCbKey = Symbol("_enterCb"); +var leaveCbKey = Symbol('_leaveCb'); +var enterCbKey = Symbol('_enterCb'); function useTransitionState() { const state = { isMounted: false, isLeaving: false, isUnmounting: false, - leavingVNodes: /* @__PURE__ */ new Map() + leavingVNodes: /* @__PURE__ */ new Map(), }; onMounted(() => { state.isMounted = true; @@ -3482,7 +3675,7 @@ var BaseTransitionPropsValidators = { onBeforeAppear: TransitionHookValidator, onAppear: TransitionHookValidator, onAfterAppear: TransitionHookValidator, - onAppearCancelled: TransitionHookValidator + onAppearCancelled: TransitionHookValidator, }; var recursiveGetSubtree = (instance) => { const subTree = instance.subTree; @@ -3495,14 +3688,20 @@ var BaseTransitionImpl = { const instance = getCurrentInstance(); const state = useTransitionState(); return () => { - const children = slots.default && getTransitionRawChildren(slots.default(), true); + const children = + slots.default && getTransitionRawChildren(slots.default(), true); if (!children || !children.length) { return; } const child = findNonCommentChild(children); const rawProps = toRaw(props); const { mode } = rawProps; - if (mode && mode !== "in-out" && mode !== "out-in" && mode !== "default") { + if ( + mode && + mode !== 'in-out' && + mode !== 'out-in' && + mode !== 'default' + ) { warn$1(`invalid mode: ${mode}`); } if (state.isLeaving) { @@ -3518,13 +3717,18 @@ var BaseTransitionImpl = { state, instance, // #11061, ensure enterHooks is fresh after clone - (hooks) => enterHooks = hooks + (hooks) => (enterHooks = hooks) ); if (innerChild.type !== Comment) { setTransitionHooks(innerChild, enterHooks); } let oldInnerChild = instance.subTree && getInnerChild$1(instance.subTree); - if (oldInnerChild && oldInnerChild.type !== Comment && !isSameVNodeType(oldInnerChild, innerChild) && recursiveGetSubtree(instance).type !== Comment) { + if ( + oldInnerChild && + oldInnerChild.type !== Comment && + !isSameVNodeType(oldInnerChild, innerChild) && + recursiveGetSubtree(instance).type !== Comment + ) { let leavingHooks = resolveTransitionHooks( oldInnerChild, rawProps, @@ -3532,7 +3736,7 @@ var BaseTransitionImpl = { instance ); setTransitionHooks(oldInnerChild, leavingHooks); - if (mode === "out-in" && innerChild.type !== Comment) { + if (mode === 'out-in' && innerChild.type !== Comment) { state.isLeaving = true; leavingHooks.afterLeave = () => { state.isLeaving = false; @@ -3543,7 +3747,7 @@ var BaseTransitionImpl = { oldInnerChild = void 0; }; return emptyPlaceholder(child); - } else if (mode === "in-out" && innerChild.type !== Comment) { + } else if (mode === 'in-out' && innerChild.type !== Comment) { leavingHooks.delayLeave = (el, earlyRemove, delayedLeave) => { const leavingVNodesCache = getLeavingNodesForType( state, @@ -3570,7 +3774,7 @@ var BaseTransitionImpl = { } return child; }; - } + }, }; function findNonCommentChild(children) { let child = children[0]; @@ -3580,7 +3784,7 @@ function findNonCommentChild(children) { if (c.type !== Comment) { if (hasFound) { warn$1( - " can only be used on a single element or component. Use for lists." + ' can only be used on a single element or component. Use for lists.' ); break; } @@ -3618,17 +3822,12 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { onBeforeAppear, onAppear, onAfterAppear, - onAppearCancelled + onAppearCancelled, } = props; const key = String(vnode.key); const leavingVNodesCache = getLeavingNodesForType(state, vnode); const callHook3 = (hook, args) => { - hook && callWithAsyncErrorHandling( - hook, - instance, - 9, - args - ); + hook && callWithAsyncErrorHandling(hook, instance, 9, args); }; const callAsyncHook = (hook, args) => { const done = args[1]; @@ -3658,12 +3857,17 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { ); } const leavingVNode = leavingVNodesCache[key]; - if (leavingVNode && isSameVNodeType(vnode, leavingVNode) && leavingVNode.el[leaveCbKey]) { + if ( + leavingVNode && + isSameVNodeType(vnode, leavingVNode) && + leavingVNode.el[leaveCbKey] + ) { leavingVNode.el[leaveCbKey](); } callHook3(hook, [el]); }, enter(el) { + if (leavingVNodesCache[key] === vnode) return; let hook = onEnter; let afterHook = onAfterEnter; let cancelHook = onEnterCancelled; @@ -3677,7 +3881,7 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { } } let called = false; - const done = el[enterCbKey] = (cancelled) => { + el[enterCbKey] = (cancelled) => { if (called) return; called = true; if (cancelled) { @@ -3690,6 +3894,7 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { } el[enterCbKey] = void 0; }; + const done = el[enterCbKey].bind(null, false); if (hook) { callAsyncHook(hook, [el, done]); } else { @@ -3709,7 +3914,7 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { } callHook3(onBeforeLeave, [el]); let called = false; - const done = el[leaveCbKey] = (cancelled) => { + el[leaveCbKey] = (cancelled) => { if (called) return; called = true; remove2(); @@ -3723,6 +3928,7 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { delete leavingVNodesCache[key2]; } }; + const done = el[leaveCbKey].bind(null, false); leavingVNodesCache[key2] = vnode; if (onLeave) { callAsyncHook(onLeave, [el, done]); @@ -3740,7 +3946,7 @@ function resolveTransitionHooks(vnode, props, state, instance, postClone) { ); if (postClone) postClone(hooks2); return hooks2; - } + }, }; return hooks; } @@ -3787,7 +3993,10 @@ function getTransitionRawChildren(children, keepComment = false, parentKey) { let keyedFragmentCount = 0; for (let i = 0; i < children.length; i++) { let child = children[i]; - const key = parentKey == null ? child.key : String(parentKey) + String(child.key != null ? child.key : i); + const key = + parentKey == null + ? child.key + : String(parentKey) + String(child.key != null ? child.key : i); if (child.type === Fragment) { if (child.patchFlag & 128) keyedFragmentCount++; ret = ret.concat( @@ -3805,40 +4014,39 @@ function getTransitionRawChildren(children, keepComment = false, parentKey) { return ret; } function defineComponent(options, extraOptions) { - return isFunction(options) ? ( - // #8236: extend call and options.name access are considered side-effects - // by Rollup, so we have to wrap it in a pure-annotated IIFE. - (() => extend({ name: options.name }, extraOptions, { setup: options }))() - ) : options; + return isFunction(options) + ? // #8236: extend call and options.name access are considered side-effects + // by Rollup, so we have to wrap it in a pure-annotated IIFE. + (() => extend({ name: options.name }, extraOptions, { setup: options }))() + : options; } function useId() { const i = getCurrentInstance(); if (i) { - return (i.appContext.config.idPrefix || "v") + "-" + i.ids[0] + i.ids[1]++; + return (i.appContext.config.idPrefix || 'v') + '-' + i.ids[0] + i.ids[1]++; } else if (true) { warn$1( `useId() is called when there is no active component instance to be associated with.` ); } - return ""; + return ''; } function markAsyncBoundary(instance) { - instance.ids = [instance.ids[0] + instance.ids[2]++ + "-", 0, 0]; + instance.ids = [instance.ids[0] + instance.ids[2]++ + '-', 0, 0]; } var knownTemplateRefs = /* @__PURE__ */ new WeakSet(); function useTemplateRef(key) { const i = getCurrentInstance(); const r = shallowRef(null); if (i) { - const refs = i.refs === EMPTY_OBJ ? i.refs = {} : i.refs; - let desc; - if ((desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable) { + const refs = i.refs === EMPTY_OBJ ? (i.refs = {}) : i.refs; + if (isTemplateRefKey(refs, key)) { warn$1(`useTemplateRef('${key}') already exists.`); } else { Object.defineProperty(refs, key, { enumerable: true, get: () => r.value, - set: (val) => r.value = val + set: (val) => (r.value = val), }); } } else if (true) { @@ -3852,11 +4060,17 @@ function useTemplateRef(key) { } return ret; } +function isTemplateRefKey(refs, key) { + let desc; + return !!( + (desc = Object.getOwnPropertyDescriptor(refs, key)) && !desc.configurable + ); +} var pendingSetRefMap = /* @__PURE__ */ new WeakMap(); function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { if (isArray(rawRef)) { - rawRef.forEach( - (r, i) => setRef( + rawRef.forEach((r, i) => + setRef( r, oldRawRef && (isArray(oldRawRef) ? oldRawRef[i] : oldRawRef), parentSuspense, @@ -3867,12 +4081,19 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { return; } if (isAsyncWrapper(vnode) && !isUnmount) { - if (vnode.shapeFlag & 512 && vnode.type.__asyncResolved && vnode.component.subTree.component) { + if ( + vnode.shapeFlag & 512 && + vnode.type.__asyncResolved && + vnode.component.subTree.component + ) { setRef(rawRef, oldRawRef, parentSuspense, vnode.component.subTree); } return; } - const refValue = vnode.shapeFlag & 4 ? getComponentPublicInstance(vnode.component) : vnode.el; + const refValue = + vnode.shapeFlag & 4 + ? getComponentPublicInstance(vnode.component) + : vnode.el; const value = isUnmount ? null : refValue; const { i: owner, r: ref2 } = rawRef; if (!owner) { @@ -3882,24 +4103,36 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { return; } const oldRef = oldRawRef && oldRawRef.r; - const refs = owner.refs === EMPTY_OBJ ? owner.refs = {} : owner.refs; + const refs = owner.refs === EMPTY_OBJ ? (owner.refs = {}) : owner.refs; const setupState = owner.setupState; const rawSetupState = toRaw(setupState); - const canSetSetupRef = setupState === EMPTY_OBJ ? NO : (key) => { - if (true) { - if (hasOwn(rawSetupState, key) && !isRef2(rawSetupState[key])) { - warn$1( - `Template ref "${key}" used on a non-ref value. It will not work in the production build.` - ); - } - if (knownTemplateRefs.has(rawSetupState[key])) { - return false; - } + const canSetSetupRef = + setupState === EMPTY_OBJ + ? NO + : (key) => { + if (true) { + if (hasOwn(rawSetupState, key) && !isRef2(rawSetupState[key])) { + warn$1( + `Template ref "${key}" used on a non-ref value. It will not work in the production build.` + ); + } + if (knownTemplateRefs.has(rawSetupState[key])) { + return false; + } + } + if (isTemplateRefKey(refs, key)) { + return false; + } + return hasOwn(rawSetupState, key); + }; + const canSetRef = (ref22, key) => { + if (knownTemplateRefs.has(ref22)) { + return false; } - return hasOwn(rawSetupState, key); - }; - const canSetRef = (ref22) => { - return !knownTemplateRefs.has(ref22); + if (key && isTemplateRefKey(refs, key)) { + return false; + } + return true; }; if (oldRef != null && oldRef !== ref2) { invalidatePendingSetRef(oldRawRef); @@ -3909,10 +4142,10 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { setupState[oldRef] = null; } } else if (isRef2(oldRef)) { - if (canSetRef(oldRef)) { + const oldRawRefAtom = oldRawRef; + if (canSetRef(oldRef, oldRawRefAtom.k)) { oldRef.value = null; } - const oldRawRefAtom = oldRawRef; if (oldRawRefAtom.k) refs[oldRawRefAtom.k] = null; } } @@ -3924,7 +4157,13 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { if (_isString || _isRef) { const doSet = () => { if (rawRef.f) { - const existing = _isString ? canSetSetupRef(ref2) ? setupState[ref2] : refs[ref2] : canSetRef(ref2) || !rawRef.k ? ref2.value : refs[rawRef.k]; + const existing = _isString + ? canSetSetupRef(ref2) + ? setupState[ref2] + : refs[ref2] + : canSetRef(ref2) || !rawRef.k + ? ref2.value + : refs[rawRef.k]; if (isUnmount) { isArray(existing) && remove(existing, refValue); } else { @@ -3936,7 +4175,7 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { } } else { const newVal = [refValue]; - if (canSetRef(ref2)) { + if (canSetRef(ref2, rawRef.k)) { ref2.value = newVal; } if (rawRef.k) refs[rawRef.k] = newVal; @@ -3951,12 +4190,12 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { setupState[ref2] = value; } } else if (_isRef) { - if (canSetRef(ref2)) { + if (canSetRef(ref2, rawRef.k)) { ref2.value = value; } if (rawRef.k) refs[rawRef.k] = value; } else if (true) { - warn$1("Invalid template ref type:", ref2, `(${typeof ref2})`); + warn$1('Invalid template ref type:', ref2, `(${typeof ref2})`); } }; if (value) { @@ -3972,7 +4211,7 @@ function setRef(rawRef, oldRawRef, parentSuspense, vnode, isUnmount = false) { doSet(); } } else if (true) { - warn$1("Invalid template ref type:", ref2, `(${typeof ref2})`); + warn$1('Invalid template ref type:', ref2, `(${typeof ref2})`); } } } @@ -3988,15 +4227,18 @@ var logMismatchError = () => { if (hasLoggedMismatchError) { return; } - console.error("Hydration completed but contains mismatches."); + console.error('Hydration completed but contains mismatches.'); hasLoggedMismatchError = true; }; -var isSVGContainer = (container) => container.namespaceURI.includes("svg") && container.tagName !== "foreignObject"; -var isMathMLContainer = (container) => container.namespaceURI.includes("MathML"); +var isSVGContainer = (container) => + container.namespaceURI.includes('svg') && + container.tagName !== 'foreignObject'; +var isMathMLContainer = (container) => + container.namespaceURI.includes('MathML'); var getContainerType = (container) => { if (container.nodeType !== 1) return void 0; - if (isSVGContainer(container)) return "svg"; - if (isMathMLContainer(container)) return "mathml"; + if (isSVGContainer(container)) return 'svg'; + if (isMathMLContainer(container)) return 'mathml'; return void 0; }; var isComment = (node) => node.nodeType === 8; @@ -4011,8 +4253,8 @@ function createHydrationFunctions(rendererInternals) { parentNode, remove: remove2, insert, - createComment - } + createComment, + }, } = rendererInternals; const hydrate2 = (vnode, container) => { if (!container.hasChildNodes()) { @@ -4028,23 +4270,31 @@ function createHydrationFunctions(rendererInternals) { flushPostFlushCbs(); container._vnode = vnode; }; - const hydrateNode = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized = false) => { + const hydrateNode = ( + node, + vnode, + parentComponent, + parentSuspense, + slotScopeIds, + optimized = false + ) => { optimized = optimized || !!vnode.dynamicChildren; - const isFragmentStart = isComment(node) && node.data === "["; - const onMismatch = () => handleMismatch( - node, - vnode, - parentComponent, - parentSuspense, - slotScopeIds, - isFragmentStart - ); + const isFragmentStart = isComment(node) && node.data === '['; + const onMismatch = () => + handleMismatch( + node, + vnode, + parentComponent, + parentSuspense, + slotScopeIds, + isFragmentStart + ); const { type, ref: ref2, shapeFlag, patchFlag } = vnode; let domType = node.nodeType; vnode.el = node; if (true) { - def(node, "__vnode", vnode, true); - def(node, "__vueParentComponent", parentComponent, true); + def(node, '__vnode', vnode, true); + def(node, '__vueParentComponent', parentComponent, true); } if (patchFlag === -2) { optimized = false; @@ -4054,8 +4304,8 @@ function createHydrationFunctions(rendererInternals) { switch (type) { case Text: if (domType !== 3) { - if (vnode.children === "") { - insert(vnode.el = createText(""), parentNode(node), node); + if (vnode.children === '') { + insert((vnode.el = createText('')), parentNode(node), node); nextNode = node; } else { nextNode = onMismatch(); @@ -4066,9 +4316,7 @@ function createHydrationFunctions(rendererInternals) { `Hydration text mismatch in`, node.parentNode, ` - - rendered on server: ${JSON.stringify( - node.data - )} + - rendered on server: ${JSON.stringify(node.data)} - expected on client: ${JSON.stringify(vnode.children)}` ); logMismatchError(); @@ -4081,7 +4329,7 @@ function createHydrationFunctions(rendererInternals) { if (isTemplateNode(node)) { nextNode = nextSibling(node); replaceNode( - vnode.el = node.content.firstChild, + (vnode.el = node.content.firstChild), node, parentComponent ); @@ -4101,7 +4349,8 @@ function createHydrationFunctions(rendererInternals) { const needToAdoptContent = !vnode.children.length; for (let i = 0; i < vnode.staticCount; i++) { if (needToAdoptContent) - vnode.children += nextNode.nodeType === 1 ? nextNode.outerHTML : nextNode.data; + vnode.children += + nextNode.nodeType === 1 ? nextNode.outerHTML : nextNode.data; if (i === vnode.staticCount - 1) { vnode.anchor = nextNode; } @@ -4128,7 +4377,11 @@ function createHydrationFunctions(rendererInternals) { break; default: if (shapeFlag & 1) { - if ((domType !== 1 || vnode.type.toLowerCase() !== node.tagName.toLowerCase()) && !isTemplateNode(node)) { + if ( + (domType !== 1 || + vnode.type.toLowerCase() !== node.tagName.toLowerCase()) && + !isTemplateNode(node) + ) { nextNode = onMismatch(); } else { nextNode = hydrateElement( @@ -4145,8 +4398,8 @@ function createHydrationFunctions(rendererInternals) { const container = parentNode(node); if (isFragmentStart) { nextNode = locateClosingAnchor(node); - } else if (isComment(node) && node.data === "teleport start") { - nextNode = locateClosingAnchor(node, node.data, "teleport end"); + } else if (isComment(node) && node.data === 'teleport start') { + nextNode = locateClosingAnchor(node, node.data, 'teleport end'); } else { nextNode = nextSibling(node); } @@ -4163,9 +4416,12 @@ function createHydrationFunctions(rendererInternals) { let subTree; if (isFragmentStart) { subTree = createVNode(Fragment); - subTree.anchor = nextNode ? nextNode.previousSibling : container.lastChild; + subTree.anchor = nextNode + ? nextNode.previousSibling + : container.lastChild; } else { - subTree = node.nodeType === 3 ? createTextVNode("") : createVNode("div"); + subTree = + node.nodeType === 3 ? createTextVNode('') : createVNode('div'); } subTree.el = node; vnode.component.subTree = subTree; @@ -4198,7 +4454,7 @@ function createHydrationFunctions(rendererInternals) { hydrateNode ); } else if (true) { - warn$1("Invalid HostVNode type:", type, `(${typeof type})`); + warn$1('Invalid HostVNode type:', type, `(${typeof type})`); } } if (ref2 != null) { @@ -4206,32 +4462,45 @@ function createHydrationFunctions(rendererInternals) { } return nextNode; }; - const hydrateElement = (el, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { + const hydrateElement = ( + el, + vnode, + parentComponent, + parentSuspense, + slotScopeIds, + optimized + ) => { optimized = optimized || !!vnode.dynamicChildren; const { type, props, patchFlag, shapeFlag, dirs, transition } = vnode; - const forcePatch = type === "input" || type === "option"; + const forcePatch = type === 'input' || type === 'option'; if (true) { if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "created"); + invokeDirectiveHook(vnode, null, parentComponent, 'created'); } let needCallTransitionHooks = false; if (isTemplateNode(el)) { - needCallTransitionHooks = needTransition( - null, - // no need check parentSuspense in hydration - transition - ) && parentComponent && parentComponent.vnode.props && parentComponent.vnode.props.appear; + needCallTransitionHooks = + needTransition( + null, + // no need check parentSuspense in hydration + transition + ) && + parentComponent && + parentComponent.vnode.props && + parentComponent.vnode.props.appear; const content = el.content.firstChild; if (needCallTransitionHooks) { - const cls = content.getAttribute("class"); + const cls = content.getAttribute('class'); if (cls) content.$cls = cls; transition.beforeEnter(content); } replaceNode(content, el, parentComponent); vnode.el = el = content; } - if (shapeFlag & 16 && // skip if element has innerHTML / textContent - !(props && (props.innerHTML || props.textContent))) { + if ( + shapeFlag & 16 && // skip if element has innerHTML / textContent + !(props && (props.innerHTML || props.textContent)) + ) { let next = hydrateChildren( el.firstChild, vnode, @@ -4243,11 +4512,13 @@ function createHydrationFunctions(rendererInternals) { ); let hasWarned2 = false; while (next) { - if (!isMismatchAllowed( - el, - 1 - /* CHILDREN */ - )) { + if ( + !isMismatchAllowed( + el, + 1 + /* CHILDREN */ + ) + ) { if (!hasWarned2) { warn$1( `Hydration children mismatch on`, @@ -4265,17 +4536,24 @@ Server rendered element contains more child nodes than client vdom.` } } else if (shapeFlag & 8) { let clientText = vnode.children; - if (clientText[0] === "\n" && (el.tagName === "PRE" || el.tagName === "TEXTAREA")) { + if ( + clientText[0] === '\n' && + (el.tagName === 'PRE' || el.tagName === 'TEXTAREA') + ) { clientText = clientText.slice(1); } const { textContent } = el; - if (textContent !== clientText && // innerHTML normalize \r\n or \r into a single \n in the DOM - textContent !== clientText.replace(/\r\n|\r/g, "\n")) { - if (!isMismatchAllowed( - el, - 0 - /* TEXT */ - )) { + if ( + textContent !== clientText && // innerHTML normalize \r\n or \r into a single \n in the DOM + textContent !== clientText.replace(/\r\n|\r/g, '\n') + ) { + if ( + !isMismatchAllowed( + el, + 0 + /* TEXT */ + ) + ) { warn$1( `Hydration text content mismatch on`, el, @@ -4290,22 +4568,30 @@ Server rendered element contains more child nodes than client vdom.` } if (props) { if (true) { - const isCustomElement = el.tagName.includes("-"); + const isCustomElement = el.tagName.includes('-'); for (const key in props) { - if (// #11189 skip if this node has directives that have created hooks - // as it could have mutated the DOM in any possible way - !(dirs && dirs.some((d) => d.dir.created)) && propHasMismatch(el, key, props[key], vnode, parentComponent)) { + if ( + // #11189 skip if this node has directives that have created hooks + // as it could have mutated the DOM in any possible way + !(dirs && dirs.some((d) => d.dir.created)) && + propHasMismatch(el, key, props[key], vnode, parentComponent) + ) { logMismatchError(); } - if (forcePatch && (key.endsWith("value") || key === "indeterminate") || isOn(key) && !isReservedProp(key) || // force hydrate v-bind with .prop modifiers - key[0] === "." || isCustomElement) { + if ( + (forcePatch && + (key.endsWith('value') || key === 'indeterminate')) || + (isOn(key) && !isReservedProp(key)) || // force hydrate v-bind with .prop modifiers + key[0] === '.' || + (isCustomElement && !isReservedProp(key)) + ) { patchProp2(el, key, null, props[key], void 0, parentComponent); } } } else if (props.onClick) { patchProp2( el, - "onClick", + 'onClick', null, props.onClick, void 0, @@ -4316,37 +4602,49 @@ Server rendered element contains more child nodes than client vdom.` } } let vnodeHooks; - if (vnodeHooks = props && props.onVnodeBeforeMount) { + if ((vnodeHooks = props && props.onVnodeBeforeMount)) { invokeVNodeHook(vnodeHooks, parentComponent, vnode); } if (dirs) { - invokeDirectiveHook(vnode, null, parentComponent, "beforeMount"); + invokeDirectiveHook(vnode, null, parentComponent, 'beforeMount'); } - if ((vnodeHooks = props && props.onVnodeMounted) || dirs || needCallTransitionHooks) { + if ( + (vnodeHooks = props && props.onVnodeMounted) || + dirs || + needCallTransitionHooks + ) { queueEffectWithSuspense(() => { vnodeHooks && invokeVNodeHook(vnodeHooks, parentComponent, vnode); needCallTransitionHooks && transition.enter(el); - dirs && invokeDirectiveHook(vnode, null, parentComponent, "mounted"); + dirs && invokeDirectiveHook(vnode, null, parentComponent, 'mounted'); }, parentSuspense); } } return el.nextSibling; }; - const hydrateChildren = (node, parentVNode, container, parentComponent, parentSuspense, slotScopeIds, optimized) => { + const hydrateChildren = ( + node, + parentVNode, + container, + parentComponent, + parentSuspense, + slotScopeIds, + optimized + ) => { optimized = optimized || !!parentVNode.dynamicChildren; const children = parentVNode.children; const l = children.length; let hasWarned2 = false; for (let i = 0; i < l; i++) { - const vnode = optimized ? children[i] : children[i] = normalizeVNode(children[i]); + const vnode = optimized + ? children[i] + : (children[i] = normalizeVNode(children[i])); const isText = vnode.type === Text; if (node) { if (isText && !optimized) { if (i + 1 < l && normalizeVNode(children[i + 1]).type === Text) { insert( - createText( - node.data.slice(vnode.children.length) - ), + createText(node.data.slice(vnode.children.length)), container, nextSibling(node) ); @@ -4362,13 +4660,15 @@ Server rendered element contains more child nodes than client vdom.` optimized ); } else if (isText && !vnode.children) { - insert(vnode.el = createText(""), container); + insert((vnode.el = createText('')), container); } else { - if (!isMismatchAllowed( - container, - 1 - /* CHILDREN */ - )) { + if ( + !isMismatchAllowed( + container, + 1 + /* CHILDREN */ + ) + ) { if (!hasWarned2) { warn$1( `Hydration children mismatch on`, @@ -4394,10 +4694,19 @@ Server rendered element contains fewer child nodes than client vdom.` } return node; }; - const hydrateFragment = (node, vnode, parentComponent, parentSuspense, slotScopeIds, optimized) => { + const hydrateFragment = ( + node, + vnode, + parentComponent, + parentSuspense, + slotScopeIds, + optimized + ) => { const { slotScopeIds: fragmentSlotScopeIds } = vnode; if (fragmentSlotScopeIds) { - slotScopeIds = slotScopeIds ? slotScopeIds.concat(fragmentSlotScopeIds) : fragmentSlotScopeIds; + slotScopeIds = slotScopeIds + ? slotScopeIds.concat(fragmentSlotScopeIds) + : fragmentSlotScopeIds; } const container = parentNode(node); const next = hydrateChildren( @@ -4409,25 +4718,38 @@ Server rendered element contains fewer child nodes than client vdom.` slotScopeIds, optimized ); - if (next && isComment(next) && next.data === "]") { - return nextSibling(vnode.anchor = next); + if (next && isComment(next) && next.data === ']') { + return nextSibling((vnode.anchor = next)); } else { logMismatchError(); - insert(vnode.anchor = createComment(`]`), container, next); + insert((vnode.anchor = createComment(`]`)), container, next); return next; } }; - const handleMismatch = (node, vnode, parentComponent, parentSuspense, slotScopeIds, isFragment) => { - if (!isMismatchAllowed( - node.parentElement, - 1 - /* CHILDREN */ - )) { + const handleMismatch = ( + node, + vnode, + parentComponent, + parentSuspense, + slotScopeIds, + isFragment + ) => { + if ( + !isMismatchAllowed( + node.parentElement, + 1 + /* CHILDREN */ + ) + ) { warn$1( `Hydration node mismatch: - rendered on server:`, node, - node.nodeType === 3 ? `(text)` : isComment(node) && node.data === "[" ? `(start of fragment)` : ``, + node.nodeType === 3 + ? `(text)` + : isComment(node) && node.data === '[' + ? `(start of fragment)` + : ``, ` - expected on client:`, vnode.type @@ -4465,7 +4787,7 @@ Server rendered element contains fewer child nodes than client vdom.` } return next; }; - const locateClosingAnchor = (node, open = "[", close = "]") => { + const locateClosingAnchor = (node, open = '[', close = ']') => { let match = 0; while (node) { node = nextSibling(node); @@ -4496,7 +4818,7 @@ Server rendered element contains fewer child nodes than client vdom.` } }; const isTemplateNode = (node) => { - return node.nodeType === 1 && node.tagName === "TEMPLATE"; + return node.nodeType === 1 && node.tagName === 'TEMPLATE'; }; return [hydrate2, hydrateNode]; } @@ -4505,27 +4827,29 @@ function propHasMismatch(el, key, clientValue, vnode, instance) { let mismatchKey; let actual; let expected; - if (key === "class") { + if (key === 'class') { if (el.$cls) { actual = el.$cls; delete el.$cls; } else { - actual = el.getAttribute("class"); + actual = el.getAttribute('class'); } expected = normalizeClass(clientValue); - if (!isSetEqual(toClassSet(actual || ""), toClassSet(expected))) { + if (!isSetEqual(toClassSet(actual || ''), toClassSet(expected))) { mismatchType = 2; mismatchKey = `class`; } - } else if (key === "style") { - actual = el.getAttribute("style") || ""; - expected = isString(clientValue) ? clientValue : stringifyStyle(normalizeStyle(clientValue)); + } else if (key === 'style') { + actual = el.getAttribute('style') || ''; + expected = isString(clientValue) + ? clientValue + : stringifyStyle(normalizeStyle(clientValue)); const actualMap = toStyleMap(actual); const expectedMap = toStyleMap(expected); if (vnode.dirs) { for (const { dir, value } of vnode.dirs) { - if (dir.name === "show" && !value) { - expectedMap.set("display", "none"); + if (dir.name === 'show' && !value) { + expectedMap.set('display', 'none'); } } } @@ -4534,9 +4858,12 @@ function propHasMismatch(el, key, clientValue, vnode, instance) { } if (!isMapEqual(actualMap, expectedMap)) { mismatchType = 3; - mismatchKey = "style"; + mismatchKey = 'style'; } - } else if (el instanceof SVGElement && isKnownSvgAttr(key) || el instanceof HTMLElement && (isBooleanAttr(key) || isKnownHtmlAttr(key))) { + } else if ( + (el instanceof SVGElement && isKnownSvgAttr(key)) || + (el instanceof HTMLElement && (isBooleanAttr(key) || isKnownHtmlAttr(key))) + ) { if (isBooleanAttr(key)) { actual = el.hasAttribute(key); expected = includeBooleanAttr(clientValue); @@ -4546,12 +4873,14 @@ function propHasMismatch(el, key, clientValue, vnode, instance) { } else { if (el.hasAttribute(key)) { actual = el.getAttribute(key); - } else if (key === "value" && el.tagName === "TEXTAREA") { + } else if (key === 'value' && el.tagName === 'TEXTAREA') { actual = el.value; } else { actual = false; } - expected = isRenderableAttrValue(clientValue) ? String(clientValue) : false; + expected = isRenderableAttrValue(clientValue) + ? String(clientValue) + : false; } if (actual !== expected) { mismatchType = 4; @@ -4559,7 +4888,8 @@ function propHasMismatch(el, key, clientValue, vnode, instance) { } } if (mismatchType != null && !isMismatchAllowed(el, mismatchType)) { - const format = (v) => v === false ? `(not rendered)` : `${mismatchKey}="${v}"`; + const format = (v) => + v === false ? `(not rendered)` : `${mismatchKey}="${v}"`; const preSegment = `Hydration ${MismatchTypeString[mismatchType]} mismatch on`; const postSegment = ` - rendered on server: ${format(actual)} @@ -4589,8 +4919,8 @@ function isSetEqual(a, b) { } function toStyleMap(str) { const styleMap = /* @__PURE__ */ new Map(); - for (const item of str.split(";")) { - let [key, value] = item.split(":"); + for (const item of str.split(';')) { + let [key, value] = item.split(':'); key = key.trim(); value = value && value.trim(); if (key && value) { @@ -4612,7 +4942,11 @@ function isMapEqual(a, b) { } function resolveCssVars(instance, vnode, expectedMap) { const root = instance.subTree; - if (instance.getCssVars && (vnode === root || root && root.type === Fragment && root.children.includes(vnode))) { + if ( + instance.getCssVars && + (vnode === root || + (root && root.type === Fragment && root.children.includes(vnode))) + ) { const cssVars = instance.getCssVars(); for (const key in cssVars) { const value = normalizeCssVarValue(cssVars[key]); @@ -4623,28 +4957,23 @@ function resolveCssVars(instance, vnode, expectedMap) { resolveCssVars(instance.parent, instance.vnode, expectedMap); } } -var allowMismatchAttr = "data-allow-mismatch"; +var allowMismatchAttr = 'data-allow-mismatch'; var MismatchTypeString = { - [ - 0 + [0]: /* TEXT */ - ]: "text", - [ - 1 + 'text', + [1]: /* CHILDREN */ - ]: "children", - [ - 2 + 'children', + [2]: /* CLASS */ - ]: "class", - [ - 3 + 'class', + [3]: /* STYLE */ - ]: "style", - [ - 4 + 'style', + [4]: /* ATTRIBUTE */ - ]: "attribute" + 'attribute', }; function isMismatchAllowed(el, allowedType) { if (allowedType === 0 || allowedType === 1) { @@ -4655,26 +4984,33 @@ function isMismatchAllowed(el, allowedType) { const allowedAttr = el && el.getAttribute(allowMismatchAttr); if (allowedAttr == null) { return false; - } else if (allowedAttr === "") { + } else if (allowedAttr === '') { return true; } else { - const list = allowedAttr.split(","); - if (allowedType === 0 && list.includes("children")) { + const list = allowedAttr.split(','); + if (allowedType === 0 && list.includes('children')) { return true; } return list.includes(MismatchTypeString[allowedType]); } } -var requestIdleCallback = getGlobalThis().requestIdleCallback || ((cb) => setTimeout(cb, 1)); -var cancelIdleCallback = getGlobalThis().cancelIdleCallback || ((id) => clearTimeout(id)); -var hydrateOnIdle = (timeout = 1e4) => (hydrate2) => { - const id = requestIdleCallback(hydrate2, { timeout }); - return () => cancelIdleCallback(id); -}; +var requestIdleCallback = + getGlobalThis().requestIdleCallback || ((cb) => setTimeout(cb, 1)); +var cancelIdleCallback = + getGlobalThis().cancelIdleCallback || ((id) => clearTimeout(id)); +var hydrateOnIdle = + (timeout = 1e4) => + (hydrate2) => { + const id = requestIdleCallback(hydrate2, { timeout }); + return () => cancelIdleCallback(id); + }; function elementIsVisibleInViewport(el) { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; - return (top > 0 && top < innerHeight || bottom > 0 && bottom < innerHeight) && (left > 0 && left < innerWidth || right > 0 && right < innerWidth); + return ( + ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && + ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) + ); } var hydrateOnVisible = (opts) => (hydrate2, forEach) => { const ob = new IntersectionObserver((entries) => { @@ -4702,38 +5038,40 @@ var hydrateOnMediaQuery = (query) => (hydrate2) => { if (mql.matches) { hydrate2(); } else { - mql.addEventListener("change", hydrate2, { once: true }); - return () => mql.removeEventListener("change", hydrate2); + mql.addEventListener('change', hydrate2, { once: true }); + return () => mql.removeEventListener('change', hydrate2); } } }; -var hydrateOnInteraction = (interactions = []) => (hydrate2, forEach) => { - if (isString(interactions)) interactions = [interactions]; - let hasHydrated = false; - const doHydrate = (e) => { - if (!hasHydrated) { - hasHydrated = true; - teardown(); - hydrate2(); - e.target.dispatchEvent(new e.constructor(e.type, e)); - } - }; - const teardown = () => { +var hydrateOnInteraction = + (interactions = []) => + (hydrate2, forEach) => { + if (isString(interactions)) interactions = [interactions]; + let hasHydrated = false; + const doHydrate = (e) => { + if (!hasHydrated) { + hasHydrated = true; + teardown(); + hydrate2(); + e.target.dispatchEvent(new e.constructor(e.type, e)); + } + }; + const teardown = () => { + forEach((el) => { + for (const i of interactions) { + el.removeEventListener(i, doHydrate); + } + }); + }; forEach((el) => { for (const i of interactions) { - el.removeEventListener(i, doHydrate); + el.addEventListener(i, doHydrate, { once: true }); } }); + return teardown; }; - forEach((el) => { - for (const i of interactions) { - el.addEventListener(i, doHydrate, { once: true }); - } - }); - return teardown; -}; function forEachElement(node, cb) { - if (isComment(node) && node.data === "[") { + if (isComment(node) && node.data === '[') { let depth = 1; let next = node.nextSibling; while (next) { @@ -4743,9 +5081,9 @@ function forEachElement(node, cb) { break; } } else if (isComment(next)) { - if (next.data === "]") { + if (next.data === ']') { if (--depth === 0) break; - } else if (next.data === "[") { + } else if (next.data === '[') { depth++; } } @@ -4769,7 +5107,7 @@ function defineAsyncComponent(source) { timeout, // undefined = never times out suspensible = true, - onError: userOnError + onError: userOnError, } = source; let pendingRequest = null; let resolvedComp; @@ -4781,42 +5119,51 @@ function defineAsyncComponent(source) { }; const load = () => { let thisRequest; - return pendingRequest || (thisRequest = pendingRequest = loader().catch((err) => { - err = err instanceof Error ? err : new Error(String(err)); - if (userOnError) { - return new Promise((resolve2, reject) => { - const userRetry = () => resolve2(retry()); - const userFail = () => reject(err); - userOnError(err, userRetry, userFail, retries + 1); - }); - } else { - throw err; - } - }).then((comp) => { - if (thisRequest !== pendingRequest && pendingRequest) { - return pendingRequest; - } - if (!comp) { - warn$1( - `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` - ); - } - if (comp && (comp.__esModule || comp[Symbol.toStringTag] === "Module")) { - comp = comp.default; - } - if (comp && !isObject(comp) && !isFunction(comp)) { - throw new Error(`Invalid async component load result: ${comp}`); - } - resolvedComp = comp; - return comp; - })); + return ( + pendingRequest || + (thisRequest = pendingRequest = + loader() + .catch((err) => { + err = err instanceof Error ? err : new Error(String(err)); + if (userOnError) { + return new Promise((resolve2, reject) => { + const userRetry = () => resolve2(retry()); + const userFail = () => reject(err); + userOnError(err, userRetry, userFail, retries + 1); + }); + } else { + throw err; + } + }) + .then((comp) => { + if (thisRequest !== pendingRequest && pendingRequest) { + return pendingRequest; + } + if (!comp) { + warn$1( + `Async component loader resolved to undefined. If you are using retry(), make sure to return its return value.` + ); + } + if ( + comp && + (comp.__esModule || comp[Symbol.toStringTag] === 'Module') + ) { + comp = comp.default; + } + if (comp && !isObject(comp) && !isFunction(comp)) { + throw new Error(`Invalid async component load result: ${comp}`); + } + resolvedComp = comp; + return comp; + })) + ); }; return defineComponent({ - name: "AsyncComponentWrapper", + name: 'AsyncComponentWrapper', __asyncLoader: load, __asyncHydrate(el, instance, hydrate2) { let patched = false; - (instance.bu || (instance.bu = [])).push(() => patched = true); + (instance.bu || (instance.bu = [])).push(() => (patched = true)); const performHydrate = () => { if (patched) { if (true) { @@ -4828,15 +5175,16 @@ function defineAsyncComponent(source) { } hydrate2(); }; - const doHydrate = hydrateStrategy ? () => { - const teardown = hydrateStrategy( - performHydrate, - (cb) => forEachElement(el, cb) - ); - if (teardown) { - (instance.bum || (instance.bum = [])).push(teardown); - } - } : performHydrate; + const doHydrate = hydrateStrategy + ? () => { + const teardown = hydrateStrategy(performHydrate, (cb) => + forEachElement(el, cb) + ); + if (teardown) { + (instance.bum || (instance.bum = [])).push(teardown); + } + } + : performHydrate; if (resolvedComp) { doHydrate(); } else { @@ -4854,22 +5202,22 @@ function defineAsyncComponent(source) { } const onError = (err) => { pendingRequest = null; - handleError( - err, - instance, - 13, - !errorComponent - ); + handleError(err, instance, 13, !errorComponent); }; - if (suspensible && instance.suspense || isInSSRComponentSetup) { - return load().then((comp) => { - return () => createInnerComp(comp, instance); - }).catch((err) => { - onError(err); - return () => errorComponent ? createVNode(errorComponent, { - error: err - }) : null; - }); + if ((suspensible && instance.suspense) || isInSSRComponentSetup) { + return load() + .then((comp) => { + return () => createInnerComp(comp, instance); + }) + .catch((err) => { + onError(err); + return () => + errorComponent + ? createVNode(errorComponent, { + error: err, + }) + : null; + }); } const loaded = ref(false); const error = ref(); @@ -4890,30 +5238,29 @@ function defineAsyncComponent(source) { } }, timeout); } - load().then(() => { - loaded.value = true; - if (instance.parent && isKeepAlive(instance.parent.vnode)) { - instance.parent.update(); - } - }).catch((err) => { - onError(err); - error.value = err; - }); + load() + .then(() => { + loaded.value = true; + if (instance.parent && isKeepAlive(instance.parent.vnode)) { + instance.parent.update(); + } + }) + .catch((err) => { + onError(err); + error.value = err; + }); return () => { if (loaded.value && resolvedComp) { return createInnerComp(resolvedComp, instance); } else if (error.value && errorComponent) { return createVNode(errorComponent, { - error: error.value + error: error.value, }); } else if (loadingComponent && !delayed.value) { - return createInnerComp( - loadingComponent, - instance - ); + return createInnerComp(loadingComponent, instance); } }; - } + }, }); } function createInnerComp(comp, parent) { @@ -4934,7 +5281,7 @@ var KeepAliveImpl = { props: { include: [String, RegExp, Array], exclude: [String, RegExp, Array], - max: [String, Number] + max: [String, Number], }, setup(props, { slots }) { const instance = getCurrentInstance(); @@ -4957,11 +5304,17 @@ var KeepAliveImpl = { p: patch, m: move, um: _unmount, - o: { createElement } - } + o: { createElement }, + }, } = sharedContext; - const storageContainer = createElement("div"); - sharedContext.activate = (vnode, container, anchor, namespace, optimized) => { + const storageContainer = createElement('div'); + sharedContext.activate = ( + vnode, + container, + anchor, + namespace, + optimized + ) => { const instance2 = vnode.component; move(vnode, container, anchor, 0, parentSuspense); patch( @@ -5042,7 +5395,7 @@ var KeepAliveImpl = { exclude && pruneCache((name) => !matches(exclude, name)); }, // prune post-render after `current` has been updated - { flush: "post", deep: true } + { flush: 'post', deep: true } ); let pendingCacheKey = null; const cacheSubtree = () => { @@ -5074,7 +5427,7 @@ var KeepAliveImpl = { return () => { pendingCacheKey = null; if (!slots.default) { - return current = null; + return (current = null); } const children = slots.default(); const rawVNode = children[0]; @@ -5084,7 +5437,10 @@ var KeepAliveImpl = { } current = null; return children; - } else if (!isVNode(rawVNode) || !(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) { + } else if ( + !isVNode(rawVNode) || + (!(rawVNode.shapeFlag & 4) && !(rawVNode.shapeFlag & 128)) + ) { current = null; return rawVNode; } @@ -5098,7 +5454,10 @@ var KeepAliveImpl = { isAsyncWrapper(vnode) ? vnode.type.__asyncResolved || {} : comp ); const { include, exclude, max } = props; - if (include && (!name || !matches(include, name)) || exclude && name && matches(exclude, name)) { + if ( + (include && (!name || !matches(include, name))) || + (exclude && name && matches(exclude, name)) + ) { vnode.shapeFlag &= -257; current = vnode; return rawVNode; @@ -5131,14 +5490,14 @@ var KeepAliveImpl = { current = vnode; return isSuspense(rawVNode.type) ? rawVNode : vnode; }; - } + }, }; var KeepAlive = KeepAliveImpl; function matches(pattern, name) { if (isArray(pattern)) { return pattern.some((p2) => matches(p2, name)); } else if (isString(pattern)) { - return pattern.split(",").includes(name); + return pattern.split(',').includes(name); } else if (isRegExp(pattern)) { pattern.lastIndex = 0; return pattern.test(name); @@ -5146,22 +5505,24 @@ function matches(pattern, name) { return false; } function onActivated(hook, target) { - registerKeepAliveHook(hook, "a", target); + registerKeepAliveHook(hook, 'a', target); } function onDeactivated(hook, target) { - registerKeepAliveHook(hook, "da", target); + registerKeepAliveHook(hook, 'da', target); } function registerKeepAliveHook(hook, type, target = currentInstance) { - const wrappedHook = hook.__wdc || (hook.__wdc = () => { - let current = target; - while (current) { - if (current.isDeactivated) { - return; + const wrappedHook = + hook.__wdc || + (hook.__wdc = () => { + let current = target; + while (current) { + if (current.isDeactivated) { + return; + } + current = current.parent; } - current = current.parent; - } - return hook(); - }); + return hook(); + }); injectHook(type, wrappedHook, target); if (target) { let current = target.parent; @@ -5195,14 +5556,16 @@ function getInnerChild(vnode) { function injectHook(type, hook, target = currentInstance, prepend = false) { if (target) { const hooks = target[type] || (target[type] = []); - const wrappedHook = hook.__weh || (hook.__weh = (...args) => { - pauseTracking(); - const reset = setCurrentInstance(target); - const res = callWithAsyncErrorHandling(hook, target, type, args); - reset(); - resetTracking(); - return res; - }); + const wrappedHook = + hook.__weh || + (hook.__weh = (...args) => { + pauseTracking(); + const reset = setCurrentInstance(target); + const res = callWithAsyncErrorHandling(hook, target, type, args); + reset(); + resetTracking(); + return res; + }); if (prepend) { hooks.unshift(wrappedHook); } else { @@ -5210,41 +5573,39 @@ function injectHook(type, hook, target = currentInstance, prepend = false) { } return wrappedHook; } else if (true) { - const apiName = toHandlerKey(ErrorTypeStrings$1[type].replace(/ hook$/, "")); + const apiName = toHandlerKey( + ErrorTypeStrings$1[type].replace(/ hook$/, '') + ); warn$1( `${apiName} is called when there is no active component instance to be associated with. Lifecycle injection APIs can only be used during execution of setup(). If you are using async setup(), make sure to register lifecycle hooks before the first await statement.` ); } } -var createHook = (lifecycle) => (hook, target = currentInstance) => { - if (!isInSSRComponentSetup || lifecycle === "sp") { - injectHook(lifecycle, (...args) => hook(...args), target); - } -}; -var onBeforeMount = createHook("bm"); -var onMounted = createHook("m"); -var onBeforeUpdate = createHook( - "bu" -); -var onUpdated = createHook("u"); -var onBeforeUnmount = createHook( - "bum" -); -var onUnmounted = createHook("um"); -var onServerPrefetch = createHook( - "sp" -); -var onRenderTriggered = createHook("rtg"); -var onRenderTracked = createHook("rtc"); +var createHook = + (lifecycle) => + (hook, target = currentInstance) => { + if (!isInSSRComponentSetup || lifecycle === 'sp') { + injectHook(lifecycle, (...args) => hook(...args), target); + } + }; +var onBeforeMount = createHook('bm'); +var onMounted = createHook('m'); +var onBeforeUpdate = createHook('bu'); +var onUpdated = createHook('u'); +var onBeforeUnmount = createHook('bum'); +var onUnmounted = createHook('um'); +var onServerPrefetch = createHook('sp'); +var onRenderTriggered = createHook('rtg'); +var onRenderTracked = createHook('rtc'); function onErrorCaptured(hook, target = currentInstance) { - injectHook("ec", hook, target); + injectHook('ec', hook, target); } -var COMPONENTS = "components"; -var DIRECTIVES = "directives"; +var COMPONENTS = 'components'; +var DIRECTIVES = 'directives'; function resolveComponent(name, maybeSelfReference) { return resolveAsset(COMPONENTS, name, true, maybeSelfReference) || name; } -var NULL_DYNAMIC_COMPONENT = Symbol.for("v-ndc"); +var NULL_DYNAMIC_COMPONENT = Symbol.for('v-ndc'); function resolveDynamicComponent(component) { if (isString(component)) { return resolveAsset(COMPONENTS, component, false) || component; @@ -5255,31 +5616,40 @@ function resolveDynamicComponent(component) { function resolveDirective(name) { return resolveAsset(DIRECTIVES, name); } -function resolveAsset(type, name, warnMissing = true, maybeSelfReference = false) { +function resolveAsset( + type, + name, + warnMissing = true, + maybeSelfReference = false +) { const instance = currentRenderingInstance || currentInstance; if (instance) { const Component = instance.type; if (type === COMPONENTS) { - const selfName = getComponentName( - Component, - false - ); - if (selfName && (selfName === name || selfName === camelize(name) || selfName === capitalize(camelize(name)))) { + const selfName = getComponentName(Component, false); + if ( + selfName && + (selfName === name || + selfName === camelize(name) || + selfName === capitalize(camelize(name))) + ) { return Component; } } - const res = ( + const res = // local registration // check instance[type] first which is resolved for options API resolve(instance[type] || Component[type], name) || // global registration - resolve(instance.appContext[type], name) - ); + resolve(instance.appContext[type], name); if (!res && maybeSelfReference) { return Component; } if (warnMissing && !res) { - const extra = type === COMPONENTS ? ` -If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` : ``; + const extra = + type === COMPONENTS + ? ` +If this is a native custom element, make sure to exclude it from component resolution via compilerOptions.isCustomElement.` + : ``; warn$1(`Failed to resolve ${type.slice(0, -1)}: ${name}${extra}`); } return res; @@ -5290,7 +5660,12 @@ If this is a native custom element, make sure to exclude it from component resol } } function resolve(registry, name) { - return registry && (registry[name] || registry[camelize(name)] || registry[capitalize(camelize(name))]); + return ( + registry && + (registry[name] || + registry[camelize(name)] || + registry[capitalize(camelize(name))]) + ); } function renderList(source, renderItem, cache, index) { let ret; @@ -5308,13 +5683,17 @@ function renderList(source, renderItem, cache, index) { ret = new Array(source.length); for (let i = 0, l = source.length; i < l; i++) { ret[i] = renderItem( - needsWrap ? isReadonlySource ? toReadonly(toReactive(source[i])) : toReactive(source[i]) : source[i], + needsWrap + ? isReadonlySource + ? toReadonly(toReactive(source[i])) + : toReactive(source[i]) + : source[i], i, void 0, cached && cached[i] ); } - } else if (typeof source === "number") { + } else if (typeof source === 'number') { if (!Number.isInteger(source)) { warn$1(`The v-for range expect an integer value but got ${source}.`); } @@ -5324,9 +5703,8 @@ function renderList(source, renderItem, cache, index) { } } else if (isObject(source)) { if (source[Symbol.iterator]) { - ret = Array.from( - source, - (item, i) => renderItem(item, i, void 0, cached && cached[i]) + ret = Array.from(source, (item, i) => + renderItem(item, i, void 0, cached && cached[i]) ); } else { const keys = Object.keys(source); @@ -5352,24 +5730,34 @@ function createSlots(slots, dynamicSlots) { slots[slot[j].name] = slot[j].fn; } } else if (slot) { - slots[slot.name] = slot.key ? (...args) => { - const res = slot.fn(...args); - if (res) res.key = slot.key; - return res; - } : slot.fn; + slots[slot.name] = slot.key + ? (...args) => { + const res = slot.fn(...args); + if (res) res.key = slot.key; + return res; + } + : slot.fn; } } return slots; } function renderSlot(slots, name, props = {}, fallback, noSlotted) { - if (currentRenderingInstance.ce || currentRenderingInstance.parent && isAsyncWrapper(currentRenderingInstance.parent) && currentRenderingInstance.parent.ce) { + if ( + currentRenderingInstance.ce || + (currentRenderingInstance.parent && + isAsyncWrapper(currentRenderingInstance.parent) && + currentRenderingInstance.parent.ce) + ) { const hasProps = Object.keys(props).length > 0; - if (name !== "default") props.name = name; - return openBlock(), createBlock( - Fragment, - null, - [createVNode("slot", props, fallback && fallback())], - hasProps ? -2 : 64 + if (name !== 'default') props.name = name; + return ( + openBlock(), + createBlock( + Fragment, + null, + [createVNode('slot', props, fallback && fallback())], + hasProps ? -2 : 64 + ) ); } let slot = slots[name]; @@ -5384,20 +5772,22 @@ function renderSlot(slots, name, props = {}, fallback, noSlotted) { } openBlock(); const validSlotContent = slot && ensureValidVNode(slot(props)); - const slotKey = props.key || // slot content array of a dynamic conditional slot may have a branch - // key attached in the `createSlots` helper, respect that - validSlotContent && validSlotContent.key; + const slotKey = + props.key || // slot content array of a dynamic conditional slot may have a branch + // key attached in the `createSlots` helper, respect that + (validSlotContent && validSlotContent.key); const rendered = createBlock( Fragment, { - key: (slotKey && !isSymbol(slotKey) ? slotKey : `_${name}`) + // #7256 force differentiate fallback content from actual content - (!validSlotContent && fallback ? "_fb" : "") + key: + (slotKey && !isSymbol(slotKey) ? slotKey : `_${name}`) + // #7256 force differentiate fallback content from actual content + (!validSlotContent && fallback ? '_fb' : ''), }, validSlotContent || (fallback ? fallback() : []), validSlotContent && slots._ === 1 ? 64 : -2 ); if (!noSlotted && rendered.scopeId) { - rendered.slotScopeIds = [rendered.scopeId + "-s"]; + rendered.slotScopeIds = [rendered.scopeId + '-s']; } if (slot && slot._c) { slot._d = true; @@ -5411,7 +5801,9 @@ function ensureValidVNode(vnodes) { if (child.type === Fragment && !ensureValidVNode(child.children)) return false; return true; - }) ? vnodes : null; + }) + ? vnodes + : null; } function toHandlers(obj, preserveCaseIfNecessary) { const ret = {}; @@ -5420,7 +5812,11 @@ function toHandlers(obj, preserveCaseIfNecessary) { return ret; } for (const key in obj) { - ret[preserveCaseIfNecessary && /[A-Z]/.test(key) ? `on:${key}` : toHandlerKey(key)] = obj[key]; + ret[ + preserveCaseIfNecessary && /[A-Z]/.test(key) + ? `on:${key}` + : toHandlerKey(key) + ] = obj[key]; } return ret; } @@ -5429,41 +5825,44 @@ var getPublicInstance = (i) => { if (isStatefulComponent(i)) return getComponentPublicInstance(i); return getPublicInstance(i.parent); }; -var publicPropertiesMap = ( +var publicPropertiesMap = // Move PURE marker to new line to workaround compiler discarding it // due to type annotation extend(/* @__PURE__ */ Object.create(null), { $: (i) => i, $el: (i) => i.vnode.el, $data: (i) => i.data, - $props: (i) => true ? shallowReadonly(i.props) : i.props, - $attrs: (i) => true ? shallowReadonly(i.attrs) : i.attrs, - $slots: (i) => true ? shallowReadonly(i.slots) : i.slots, - $refs: (i) => true ? shallowReadonly(i.refs) : i.refs, + $props: (i) => (true ? shallowReadonly(i.props) : i.props), + $attrs: (i) => (true ? shallowReadonly(i.attrs) : i.attrs), + $slots: (i) => (true ? shallowReadonly(i.slots) : i.slots), + $refs: (i) => (true ? shallowReadonly(i.refs) : i.refs), $parent: (i) => getPublicInstance(i.parent), $root: (i) => getPublicInstance(i.root), $host: (i) => i.ce, $emit: (i) => i.emit, - $options: (i) => __VUE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type, - $forceUpdate: (i) => i.f || (i.f = () => { - queueJob(i.update); - }), + $options: (i) => (__VUE_OPTIONS_API__ ? resolveMergedOptions(i) : i.type), + $forceUpdate: (i) => + i.f || + (i.f = () => { + queueJob(i.update); + }), $nextTick: (i) => i.n || (i.n = nextTick.bind(i.proxy)), - $watch: (i) => __VUE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP - }) -); -var isReservedPrefix = (key) => key === "_" || key === "$"; -var hasSetupBinding = (state, key) => state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key); + $watch: (i) => (__VUE_OPTIONS_API__ ? instanceWatch.bind(i) : NOOP), + }); +var isReservedPrefix = (key) => key === '_' || key === '$'; +var hasSetupBinding = (state, key) => + state !== EMPTY_OBJ && !state.__isScriptSetup && hasOwn(state, key); var PublicInstanceProxyHandlers = { get({ _: instance }, key) { - if (key === "__v_skip") { + if (key === '__v_skip') { return true; } - const { ctx, setupState, data, props, accessCache, type, appContext } = instance; - if (key === "__isVue") { + const { ctx, setupState, data, props, accessCache, type, appContext } = + instance; + if (key === '__isVue') { return true; } - if (key[0] !== "$") { + if (key[0] !== '$') { const n = accessCache[key]; if (n !== void 0) { switch (n) { @@ -5479,7 +5878,11 @@ var PublicInstanceProxyHandlers = { } else if (hasSetupBinding(setupState, key)) { accessCache[key] = 1; return setupState[key]; - } else if (__VUE_OPTIONS_API__ && data !== EMPTY_OBJ && hasOwn(data, key)) { + } else if ( + __VUE_OPTIONS_API__ && + data !== EMPTY_OBJ && + hasOwn(data, key) + ) { accessCache[key] = 2; return data[key]; } else if (hasOwn(props, key)) { @@ -5495,16 +5898,17 @@ var PublicInstanceProxyHandlers = { const publicGetter = publicPropertiesMap[key]; let cssModule, globalProperties; if (publicGetter) { - if (key === "$attrs") { - track(instance.attrs, "get", ""); + if (key === '$attrs') { + track(instance.attrs, 'get', ''); markAttrsAccessed(); - } else if (key === "$slots") { - track(instance, "get", key); + } else if (key === '$slots') { + track(instance, 'get', key); } return publicGetter(instance); } else if ( // css module (injected by vue-loader) - (cssModule = type.__cssModules) && (cssModule = cssModule[key]) + (cssModule = type.__cssModules) && + (cssModule = cssModule[key]) ) { return cssModule; } else if (ctx !== EMPTY_OBJ && hasOwn(ctx, key)) { @@ -5512,14 +5916,18 @@ var PublicInstanceProxyHandlers = { return ctx[key]; } else if ( // global properties - globalProperties = appContext.config.globalProperties, hasOwn(globalProperties, key) + ((globalProperties = appContext.config.globalProperties), + hasOwn(globalProperties, key)) ) { { return globalProperties[key]; } - } else if (currentRenderingInstance && (!isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading - // to infinite warning loop - key.indexOf("__v") !== 0)) { + } else if ( + currentRenderingInstance && + (!isString(key) || // #1091 avoid internal isRef/isVNode checks on component instance leading + // to infinite warning loop + key.indexOf('__v') !== 0) + ) { if (data !== EMPTY_OBJ && isReservedPrefix(key[0]) && hasOwn(data, key)) { warn$1( `Property ${JSON.stringify( @@ -5548,7 +5956,7 @@ var PublicInstanceProxyHandlers = { warn$1(`Attempting to mutate prop "${key}". Props are readonly.`); return false; } - if (key[0] === "$" && key.slice(1) in instance) { + if (key[0] === '$' && key.slice(1) in instance) { warn$1( `Attempting to mutate public property "${key}". Properties starting with $ are reserved and readonly.` ); @@ -5558,7 +5966,7 @@ var PublicInstanceProxyHandlers = { Object.defineProperty(ctx, key, { enumerable: true, configurable: true, - value + value, }); } else { ctx[key] = value; @@ -5566,20 +5974,33 @@ var PublicInstanceProxyHandlers = { } return true; }, - has({ - _: { data, setupState, accessCache, ctx, appContext, props, type } - }, key) { + has( + { _: { data, setupState, accessCache, ctx, appContext, props, type } }, + key + ) { let cssModules; - return !!(accessCache[key] || __VUE_OPTIONS_API__ && data !== EMPTY_OBJ && key[0] !== "$" && hasOwn(data, key) || hasSetupBinding(setupState, key) || hasOwn(props, key) || hasOwn(ctx, key) || hasOwn(publicPropertiesMap, key) || hasOwn(appContext.config.globalProperties, key) || (cssModules = type.__cssModules) && cssModules[key]); + return !!( + accessCache[key] || + (__VUE_OPTIONS_API__ && + data !== EMPTY_OBJ && + key[0] !== '$' && + hasOwn(data, key)) || + hasSetupBinding(setupState, key) || + hasOwn(props, key) || + hasOwn(ctx, key) || + hasOwn(publicPropertiesMap, key) || + hasOwn(appContext.config.globalProperties, key) || + ((cssModules = type.__cssModules) && cssModules[key]) + ); }, defineProperty(target, key, descriptor) { if (descriptor.get != null) { target._.accessCache[key] = 0; - } else if (hasOwn(descriptor, "value")) { + } else if (hasOwn(descriptor, 'value')) { this.set(target, key, descriptor.value, null); } return Reflect.defineProperty(target, key, descriptor); - } + }, }; if (true) { PublicInstanceProxyHandlers.ownKeys = (target) => { @@ -5589,31 +6010,35 @@ if (true) { return Reflect.ownKeys(target); }; } -var RuntimeCompiledPublicInstanceProxyHandlers = extend({}, PublicInstanceProxyHandlers, { - get(target, key) { - if (key === Symbol.unscopables) { - return; - } - return PublicInstanceProxyHandlers.get(target, key, target); - }, - has(_, key) { - const has = key[0] !== "_" && !isGloballyAllowed(key); - if (!has && PublicInstanceProxyHandlers.has(_, key)) { - warn$1( - `Property ${JSON.stringify( - key - )} should not start with _ which is a reserved prefix for Vue internals.` - ); - } - return has; +var RuntimeCompiledPublicInstanceProxyHandlers = extend( + {}, + PublicInstanceProxyHandlers, + { + get(target, key) { + if (key === Symbol.unscopables) { + return; + } + return PublicInstanceProxyHandlers.get(target, key, target); + }, + has(_, key) { + const has = key[0] !== '_' && !isGloballyAllowed(key); + if (!has && PublicInstanceProxyHandlers.has(_, key)) { + warn$1( + `Property ${JSON.stringify( + key + )} should not start with _ which is a reserved prefix for Vue internals.` + ); + } + return has; + }, } -}); +); function createDevRenderContext(instance) { const target = {}; Object.defineProperty(target, `_`, { configurable: true, enumerable: false, - get: () => instance + get: () => instance, }); Object.keys(publicPropertiesMap).forEach((key) => { Object.defineProperty(target, key, { @@ -5622,7 +6047,7 @@ function createDevRenderContext(instance) { get: () => publicPropertiesMap[key](instance), // intercepted by the proxy so no need for implementation, // but needed to prevent set errors - set: NOOP + set: NOOP, }); }); return target; @@ -5630,7 +6055,7 @@ function createDevRenderContext(instance) { function exposePropsOnRenderContext(instance) { const { ctx, - propsOptions: [propsOptions] + propsOptions: [propsOptions], } = instance; if (propsOptions) { Object.keys(propsOptions).forEach((key) => { @@ -5638,7 +6063,7 @@ function exposePropsOnRenderContext(instance) { enumerable: true, configurable: true, get: () => instance.props[key], - set: NOOP + set: NOOP, }); }); } @@ -5659,14 +6084,15 @@ function exposeSetupStateOnRenderContext(instance) { enumerable: true, configurable: true, get: () => setupState[key], - set: NOOP + set: NOOP, }); } }); } -var warnRuntimeUsage = (method) => warn$1( - `${method}() is a compiler-hint helper that is only usable inside