// ==UserScript== // @name LeetCode Toolkit // @name:zh-CN LeetCode工具箱 // @namespace https://github.com/eclipher/leetcode-toolkit // @version 2.5.6 // @author eclipher // @description Find & Save Editorial, Copy problem as Markdown or Download as Jupyter Notebook, Format on Save, Unlock IntelliSense // @description:zh-CN 复制题目为 Markdown | 下载为 Jupyter Notebook | 保存时自动格式化 | 免费自动补全 // @license MIT // @icon https://www.google.com/s2/favicons?sz=64&domain=leetcode.com // @homepage https://github.com/eclipher/leetcode-toolkit // @include /https?:\/\/leetcode\.com\/problems\/.*/ // @include /https?:\/\/leetcode\.cn\/problems\/.*/ // @include /https?:\/\/leetcode\.com\/explore\/learn\/card\/.*/ // @exclude *://leetcode.com/problems/*/post-solution/* // @exclude *://leetcode.cn/problems/*/post-solution/* // @resource editorials https://raw.githubusercontent.com/akhilkammila/leetcode-screenshotter/refs/heads/main/ReadMe.md // @connect assets.leetcode.com // @connect * // @grant GM_addStyle // @grant GM_getResourceText // @grant GM_xmlhttpRequest // @grant unsafeWindow // @downloadURL https://update.greasyfork.icu/scripts/532158/LeetCode%20Toolkit.user.js // @updateURL https://update.greasyfork.icu/scripts/532158/LeetCode%20Toolkit.meta.js // ==/UserScript== (t=>{if(typeof GM_addStyle=="function"){GM_addStyle(t);return}const a=document.createElement("style");a.textContent=t,document.head.append(a)})(' :where(html[dir=ltr]),:where([data-sonner-toaster][dir=ltr]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir=rtl]),:where([data-sonner-toaster][dir=rtl]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted=true]){transform:translateY(-8px)}@media (hover: none) and (pointer: coarse){[data-sonner-toaster][data-lifted=true]{transform:none}}:where([data-sonner-toaster][data-x-position=right]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position=left]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position=center]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position=top]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position=bottom]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled=true]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position=top]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position=bottom]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast][data-styled=true]) :where([data-description]){font-weight:400;line-height:1.4;color:#3f3f3f}:where([data-rich-colors=true][data-sonner-toast][data-styled=true]) :where([data-description]){color:inherit}:where([data-sonner-toaster][data-sonner-theme=dark]) :where([data-description]){color:#e8e8e8}:where([data-sonner-toast][data-styled=true]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast][data-styled=true]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise=true]) :where([data-icon]>svg){opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast][data-styled=true]) :where([data-icon]>*){flex-shrink:0}:where([data-sonner-toast][data-styled=true]) :where([data-icon] svg){margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast][data-styled=true]) :where([data-content]){display:flex;flex-direction:column;gap:2px}:where([data-sonner-toast][data-styled=true]) :where([data-button]){border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;font-weight:500;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast][data-styled=true]) :where([data-button]:focus-visible){box-shadow:0 0 0 2px #0006}:where([data-sonner-toast][data-styled=true]) :where([data-button]:first-of-type){margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast][data-styled=true]) :where([data-cancel]){color:var(--normal-text);background:#00000014}:where([data-sonner-toaster][data-sonner-theme=dark]) :where([data-sonner-toast][data-styled=true]) :where([data-cancel]){background:#ffffff4d}[data-sonner-toast][data-styled=true] [data-close-button]{position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);background:var(--normal-bg);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}:where([data-sonner-toast][data-styled=true]) :where([data-close-button]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-styled=true]) :where([data-disabled=true]){cursor:not-allowed}:where([data-sonner-toast][data-styled=true]) :where([data-close-button]:hover){background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping=true]):before{content:"";position:absolute;left:-100%;right:-100%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position=top][data-swiping=true]):before{bottom:50%;transform:scaleY(3) translateY(50%)}[data-sonner-toast][data-y-position=bottom][data-swiping=true]:before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping=false][data-removed=true]):before{content:"";position:absolute;top:0;right:0;bottom:0;left:0;transform:scaleY(2)}:where([data-sonner-toast][data-expanded=true]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted=true]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded=false][data-front=false]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-x-position=right]){right:0}:where([data-sonner-toast][data-x-position=left]){left:0}:where([data-sonner-toast][data-expanded=false][data-front=false][data-styled=true])>*{opacity:0}:where([data-sonner-toast][data-visible=false]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted=true][data-expanded=true]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed=true][data-front=true][data-swipe-out=false]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=true]){--y: translateY( calc(var(--lift) * var(--offset) + var(--lift) * -100%) );opacity:0}:where([data-sonner-toast][data-removed=true][data-front=false][data-swipe-out=false][data-expanded=false]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed=true][data-front=false]):before{height:calc(var(--initial-height) + 20%)}:where([data-sonner-toast][data-swiping=true]){transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}:where([data-sonner-toast][data-swiped=true]){-webkit-user-select:none;user-select:none}:where([data-sonner-toast][data-swipe-out=true][data-y-position=bottom]),:where([data-sonner-toast][data-swipe-out=true][data-y-position=top]){animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}:where([data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]){animation-name:swipe-out-left}:where([data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]){animation-name:swipe-out-right}:where([data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]){animation-name:swipe-out-up}:where([data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]){animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}:where([data-sonner-toaster][data-sonner-theme=light]){--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 87%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 93%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 84%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}:where([data-sonner-toaster][data-sonner-theme=light]) :where([data-sonner-toast][data-invert=true]){--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}:where([data-sonner-toaster][data-sonner-theme=dark]) :where([data-sonner-toast][data-invert=true]){--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}:where([data-sonner-toaster][data-sonner-theme=dark]){--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 43%, 17%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 9%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}:where([data-sonner-toaster][data-sonner-theme=dark]) :where([data-sonner-toast]) :where([data-close-button]){background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}:where([data-sonner-toaster][data-sonner-theme=dark]) :where([data-sonner-toast]) :where([data-close-button]:hover){background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}:where([data-rich-colors=true])[data-sonner-toast][data-type=success]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=success] :where([data-close-button]){background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=info]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=info] :where([data-close-button]){background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=warning]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=warning] :where([data-close-button]){background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=error]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}:where([data-rich-colors=true])[data-sonner-toast][data-type=error] :where([data-close-button]){background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}:where(.sonner-loading-wrapper){--size: 16px;height:var(--size);width:var(--size);position:absolute;top:0;right:0;bottom:0;left:0;z-index:10}:where(.sonner-loading-wrapper[data-visible=false]){transform-origin:center;animation:sonner-fade-out .2s ease forwards}:where(.sonner-spinner){position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}:where(.sonner-loading-bar){animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}:where(.sonner-loading-bar:nth-child(1)){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}:where(.sonner-loading-bar:nth-child(2)){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}:where(.sonner-loading-bar:nth-child(3)){animation-delay:-1s;transform:rotate(60deg) translate(146%)}:where(.sonner-loading-bar:nth-child(4)){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}:where(.sonner-loading-bar:nth-child(5)){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}:where(.sonner-loading-bar:nth-child(6)){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}:where(.sonner-loading-bar:nth-child(7)){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}:where(.sonner-loading-bar:nth-child(8)){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}:where(.sonner-loading-bar:nth-child(9)){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}:where(.sonner-loading-bar:nth-child(10)){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}:where(.sonner-loading-bar:nth-child(11)){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}:where(.sonner-loading-bar:nth-child(12)){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}:where(.sonner-loader){position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}:where(.sonner-loader[data-visible=false]){opacity:0;transform:scale(.8) translate(-50%,-50%)}div.svelte-4mbyk0{display:inline-flex;flex-wrap:wrap;gap:.4rem}button.svelte-ll0ynk,a.svelte-ll0ynk{color:#fff;background-color:var(--bg, #6c5ce7);box-shadow:0 3px 0 0 var(--shadow, #a29bfe);padding:5px 20px;font-size:.8rem;font-weight:500;border-radius:5px;transition:all ease .1s;display:inline-flex;align-items:center;gap:.25rem;-webkit-user-select:none;user-select:none}button.svelte-ll0ynk:active,a.svelte-ll0ynk:active{transform:translateY(3px);box-shadow:0 0 0 0 var(--shadow, #a29bfe)}button.svelte-ll0ynk:disabled,a.svelte-ll0ynk:disabled{pointer-events:none;opacity:50%} '); (function () { 'use strict'; var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null; var __defProp = Object.defineProperty; var __typeError = (msg) => { throw TypeError(msg); }; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg); var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)); var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value); var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value); var _a, _document, _subscribe, _name, _key, _toasts, _heights, _findToastIdx, _activeToasts, _site; const DEV = false; var is_array = Array.isArray; var index_of = Array.prototype.indexOf; var array_from = Array.from; var define_property = Object.defineProperty; var get_descriptor = Object.getOwnPropertyDescriptor; var get_descriptors = Object.getOwnPropertyDescriptors; var object_prototype = Object.prototype; var array_prototype = Array.prototype; var get_prototype_of = Object.getPrototypeOf; var is_extensible = Object.isExtensible; function is_function(thing) { return typeof thing === "function"; } const noop = () => { }; function run(fn) { return fn(); } function run_all(arr) { for (var i2 = 0; i2 < arr.length; i2++) { arr[i2](); } } const DERIVED = 1 << 1; const EFFECT = 1 << 2; const RENDER_EFFECT = 1 << 3; const BLOCK_EFFECT = 1 << 4; const BRANCH_EFFECT = 1 << 5; const ROOT_EFFECT = 1 << 6; const BOUNDARY_EFFECT = 1 << 7; const UNOWNED = 1 << 8; const DISCONNECTED = 1 << 9; const CLEAN = 1 << 10; const DIRTY = 1 << 11; const MAYBE_DIRTY = 1 << 12; const INERT = 1 << 13; const DESTROYED = 1 << 14; const EFFECT_RAN = 1 << 15; const EFFECT_TRANSPARENT = 1 << 16; const LEGACY_DERIVED_PROP = 1 << 17; const HEAD_EFFECT = 1 << 19; const EFFECT_HAS_DERIVED = 1 << 20; const EFFECT_IS_UPDATING = 1 << 21; const STATE_SYMBOL = Symbol("$state"); const LEGACY_PROPS = Symbol("legacy props"); const LOADING_ATTR_SYMBOL = Symbol(""); function equals(value) { return value === this.v; } function safe_not_equal(a2, b) { return a2 != a2 ? b == b : a2 !== b || a2 !== null && typeof a2 === "object" || typeof a2 === "function"; } function safe_equals(value) { return !safe_not_equal(value, this.v); } function effect_in_teardown(rune) { { throw new Error(`https://svelte.dev/e/effect_in_teardown`); } } function effect_in_unowned_derived() { { throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`); } } function effect_orphan(rune) { { throw new Error(`https://svelte.dev/e/effect_orphan`); } } function effect_update_depth_exceeded() { { throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`); } } function props_invalid_value(key) { { throw new Error(`https://svelte.dev/e/props_invalid_value`); } } function state_descriptors_fixed() { { throw new Error(`https://svelte.dev/e/state_descriptors_fixed`); } } function state_prototype_fixed() { { throw new Error(`https://svelte.dev/e/state_prototype_fixed`); } } function state_unsafe_mutation() { { throw new Error(`https://svelte.dev/e/state_unsafe_mutation`); } } let legacy_mode_flag = false; let tracing_mode_flag = false; function enable_legacy_mode_flag() { legacy_mode_flag = true; } const EACH_ITEM_REACTIVE = 1; const EACH_INDEX_REACTIVE = 1 << 1; const EACH_IS_CONTROLLED = 1 << 2; const EACH_IS_ANIMATED = 1 << 3; const EACH_ITEM_IMMUTABLE = 1 << 4; const PROPS_IS_IMMUTABLE = 1; const PROPS_IS_RUNES = 1 << 1; const PROPS_IS_UPDATED = 1 << 2; const PROPS_IS_BINDABLE = 1 << 3; const PROPS_IS_LAZY_INITIAL = 1 << 4; const TEMPLATE_FRAGMENT = 1; const TEMPLATE_USE_IMPORT_NODE = 1 << 1; const UNINITIALIZED = Symbol(); const NAMESPACE_HTML = "http://www.w3.org/1999/xhtml"; function lifecycle_outside_component(name) { { throw new Error(`https://svelte.dev/e/lifecycle_outside_component`); } } let component_context = null; function set_component_context(context) { component_context = context; } function getContext(key) { const context_map = get_or_init_context_map(); const result = ( /** @type {T} */ context_map.get(key) ); return result; } function setContext(key, context) { const context_map = get_or_init_context_map(); context_map.set(key, context); return context; } function hasContext(key) { const context_map = get_or_init_context_map(); return context_map.has(key); } function push(props, runes = false, fn) { var ctx = component_context = { p: component_context, c: null, d: false, e: null, m: false, s: props, x: null, l: null }; if (legacy_mode_flag && !runes) { component_context.l = { s: null, u: null, r1: [], r2: source(false) }; } teardown(() => { ctx.d = true; }); } function pop(component2) { const context_stack_item = component_context; if (context_stack_item !== null) { const component_effects = context_stack_item.e; if (component_effects !== null) { var previous_effect = active_effect; var previous_reaction = active_reaction; context_stack_item.e = null; try { for (var i2 = 0; i2 < component_effects.length; i2++) { var component_effect = component_effects[i2]; set_active_effect(component_effect.effect); set_active_reaction(component_effect.reaction); effect(component_effect.fn); } } finally { set_active_effect(previous_effect); set_active_reaction(previous_reaction); } } component_context = context_stack_item.p; context_stack_item.m = true; } return ( /** @type {T} */ {} ); } function is_runes() { return !legacy_mode_flag || component_context !== null && component_context.l === null; } function get_or_init_context_map(name) { if (component_context === null) { lifecycle_outside_component(); } return component_context.c ?? (component_context.c = new Map(get_parent_context(component_context) || void 0)); } function get_parent_context(component_context2) { let parent = component_context2.p; while (parent !== null) { const context_map = parent.c; if (context_map !== null) { return context_map; } parent = parent.p; } return null; } function proxy(value) { if (typeof value !== "object" || value === null || STATE_SYMBOL in value) { return value; } const prototype = get_prototype_of(value); if (prototype !== object_prototype && prototype !== array_prototype) { return value; } var sources = /* @__PURE__ */ new Map(); var is_proxied_array = is_array(value); var version = /* @__PURE__ */ state(0); var reaction = active_reaction; var with_parent = (fn) => { var previous_reaction = active_reaction; set_active_reaction(reaction); var result = fn(); set_active_reaction(previous_reaction); return result; }; if (is_proxied_array) { sources.set("length", /* @__PURE__ */ state( /** @type {any[]} */ value.length )); } return new Proxy( /** @type {any} */ value, { defineProperty(_, prop2, descriptor) { if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) { state_descriptors_fixed(); } var s = sources.get(prop2); if (s === void 0) { s = with_parent(() => /* @__PURE__ */ state(descriptor.value)); sources.set(prop2, s); } else { set( s, with_parent(() => proxy(descriptor.value)) ); } return true; }, deleteProperty(target, prop2) { var s = sources.get(prop2); if (s === void 0) { if (prop2 in target) { sources.set( prop2, with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)) ); update_version(version); } } else { if (is_proxied_array && typeof prop2 === "string") { var ls = ( /** @type {Source} */ sources.get("length") ); var n = Number(prop2); if (Number.isInteger(n) && n < ls.v) { set(ls, n); } } set(s, UNINITIALIZED); update_version(version); } return true; }, get(target, prop2, receiver) { var _a2; if (prop2 === STATE_SYMBOL) { return value; } var s = sources.get(prop2); var exists = prop2 in target; if (s === void 0 && (!exists || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable))) { s = with_parent(() => /* @__PURE__ */ state(proxy(exists ? target[prop2] : UNINITIALIZED))); sources.set(prop2, s); } if (s !== void 0) { var v2 = get(s); return v2 === UNINITIALIZED ? void 0 : v2; } return Reflect.get(target, prop2, receiver); }, getOwnPropertyDescriptor(target, prop2) { var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2); if (descriptor && "value" in descriptor) { var s = sources.get(prop2); if (s) descriptor.value = get(s); } else if (descriptor === void 0) { var source2 = sources.get(prop2); var value2 = source2 == null ? void 0 : source2.v; if (source2 !== void 0 && value2 !== UNINITIALIZED) { return { enumerable: true, configurable: true, value: value2, writable: true }; } } return descriptor; }, has(target, prop2) { var _a2; if (prop2 === STATE_SYMBOL) { return true; } var s = sources.get(prop2); var has2 = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2); if (s !== void 0 || active_effect !== null && (!has2 || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable))) { if (s === void 0) { s = with_parent(() => /* @__PURE__ */ state(has2 ? proxy(target[prop2]) : UNINITIALIZED)); sources.set(prop2, s); } var value2 = get(s); if (value2 === UNINITIALIZED) { return false; } } return has2; }, set(target, prop2, value2, receiver) { var _a2; var s = sources.get(prop2); var has2 = prop2 in target; if (is_proxied_array && prop2 === "length") { for (var i2 = value2; i2 < /** @type {Source} */ s.v; i2 += 1) { var other_s = sources.get(i2 + ""); if (other_s !== void 0) { set(other_s, UNINITIALIZED); } else if (i2 in target) { other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED)); sources.set(i2 + "", other_s); } } } if (s === void 0) { if (!has2 || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable)) { s = with_parent(() => /* @__PURE__ */ state(void 0)); set( s, with_parent(() => proxy(value2)) ); sources.set(prop2, s); } } else { has2 = s.v !== UNINITIALIZED; set( s, with_parent(() => proxy(value2)) ); } var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2); if (descriptor == null ? void 0 : descriptor.set) { descriptor.set.call(receiver, value2); } if (!has2) { if (is_proxied_array && typeof prop2 === "string") { var ls = ( /** @type {Source} */ sources.get("length") ); var n = Number(prop2); if (Number.isInteger(n) && n >= ls.v) { set(ls, n + 1); } } update_version(version); } return true; }, ownKeys(target) { get(version); var own_keys = Reflect.ownKeys(target).filter((key2) => { var source3 = sources.get(key2); return source3 === void 0 || source3.v !== UNINITIALIZED; }); for (var [key, source2] of sources) { if (source2.v !== UNINITIALIZED && !(key in target)) { own_keys.push(key); } } return own_keys; }, setPrototypeOf() { state_prototype_fixed(); } } ); } function update_version(signal, d = 1) { set(signal, signal.v + d); } // @__NO_SIDE_EFFECTS__ function derived(fn) { var flags = DERIVED | DIRTY; var parent_derived = active_reaction !== null && (active_reaction.f & DERIVED) !== 0 ? ( /** @type {Derived} */ active_reaction ) : null; if (active_effect === null || parent_derived !== null && (parent_derived.f & UNOWNED) !== 0) { flags |= UNOWNED; } else { active_effect.f |= EFFECT_HAS_DERIVED; } const signal = { ctx: component_context, deps: null, effects: null, equals, f: flags, fn, reactions: null, rv: 0, v: ( /** @type {V} */ null ), wv: 0, parent: parent_derived ?? active_effect }; return signal; } // @__NO_SIDE_EFFECTS__ function user_derived(fn) { const d = /* @__PURE__ */ derived(fn); push_reaction_value(d); return d; } // @__NO_SIDE_EFFECTS__ function derived_safe_equal(fn) { const signal = /* @__PURE__ */ derived(fn); signal.equals = safe_equals; return signal; } function destroy_derived_effects(derived2) { var effects = derived2.effects; if (effects !== null) { derived2.effects = null; for (var i2 = 0; i2 < effects.length; i2 += 1) { destroy_effect( /** @type {Effect} */ effects[i2] ); } } } function get_derived_parent_effect(derived2) { var parent = derived2.parent; while (parent !== null) { if ((parent.f & DERIVED) === 0) { return ( /** @type {Effect} */ parent ); } parent = parent.parent; } return null; } function execute_derived(derived2) { var value; var prev_active_effect = active_effect; set_active_effect(get_derived_parent_effect(derived2)); { try { destroy_derived_effects(derived2); value = update_reaction(derived2); } finally { set_active_effect(prev_active_effect); } } return value; } function update_derived(derived2) { var value = execute_derived(derived2); var status = (skip_reaction || (derived2.f & UNOWNED) !== 0) && derived2.deps !== null ? MAYBE_DIRTY : CLEAN; set_signal_status(derived2, status); if (!derived2.equals(value)) { derived2.v = value; derived2.wv = increment_write_version(); } } const old_values = /* @__PURE__ */ new Map(); function source(v2, stack) { var signal = { f: 0, // TODO ideally we could skip this altogether, but it causes type errors v: v2, reactions: null, equals, rv: 0, wv: 0 }; return signal; } // @__NO_SIDE_EFFECTS__ function state(v2, stack) { const s = source(v2); push_reaction_value(s); return s; } // @__NO_SIDE_EFFECTS__ function mutable_source(initial_value, immutable = false) { var _a2; const s = source(initial_value); if (!immutable) { s.equals = safe_equals; } if (legacy_mode_flag && component_context !== null && component_context.l !== null) { ((_a2 = component_context.l).s ?? (_a2.s = [])).push(s); } return s; } function set(source2, value, should_proxy = false) { if (active_reaction !== null && !untracking && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT)) !== 0 && !(reaction_sources == null ? void 0 : reaction_sources.includes(source2))) { state_unsafe_mutation(); } let new_value = should_proxy ? proxy(value) : value; return internal_set(source2, new_value); } function internal_set(source2, value) { if (!source2.equals(value)) { var old_value = source2.v; if (is_destroying_effect) { old_values.set(source2, value); } else { old_values.set(source2, old_value); } source2.v = value; if ((source2.f & DERIVED) !== 0) { if ((source2.f & DIRTY) !== 0) { execute_derived( /** @type {Derived} */ source2 ); } set_signal_status(source2, (source2.f & UNOWNED) === 0 ? CLEAN : MAYBE_DIRTY); } source2.wv = increment_write_version(); mark_reactions(source2, DIRTY); if (is_runes() && active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) { if (untracked_writes === null) { set_untracked_writes([source2]); } else { untracked_writes.push(source2); } } } return value; } function mark_reactions(signal, status) { var reactions = signal.reactions; if (reactions === null) return; var runes = is_runes(); var length = reactions.length; for (var i2 = 0; i2 < length; i2++) { var reaction = reactions[i2]; var flags = reaction.f; if ((flags & DIRTY) !== 0) continue; if (!runes && reaction === active_effect) continue; set_signal_status(reaction, status); if ((flags & (CLEAN | UNOWNED)) !== 0) { if ((flags & DERIVED) !== 0) { mark_reactions( /** @type {Derived} */ reaction, MAYBE_DIRTY ); } else { schedule_effect( /** @type {Effect} */ reaction ); } } } } let hydrating = false; var $window; var is_firefox; var first_child_getter; var next_sibling_getter; function init_operations() { if ($window !== void 0) { return; } $window = window; is_firefox = /Firefox/.test(navigator.userAgent); var element_prototype = Element.prototype; var node_prototype = Node.prototype; var text_prototype = Text.prototype; first_child_getter = get_descriptor(node_prototype, "firstChild").get; next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get; if (is_extensible(element_prototype)) { element_prototype.__click = void 0; element_prototype.__className = void 0; element_prototype.__attributes = null; element_prototype.__style = void 0; element_prototype.__e = void 0; } if (is_extensible(text_prototype)) { text_prototype.__t = void 0; } } function create_text(value = "") { return document.createTextNode(value); } // @__NO_SIDE_EFFECTS__ function get_first_child(node) { return first_child_getter.call(node); } // @__NO_SIDE_EFFECTS__ function get_next_sibling(node) { return next_sibling_getter.call(node); } function child(node, is_text) { { return /* @__PURE__ */ get_first_child(node); } } function first_child(fragment, is_text) { { var first = ( /** @type {DocumentFragment} */ /* @__PURE__ */ get_first_child( /** @type {Node} */ fragment ) ); if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first); return first; } } function sibling(node, count = 1, is_text = false) { let next_sibling = node; while (count--) { next_sibling = /** @type {TemplateNode} */ /* @__PURE__ */ get_next_sibling(next_sibling); } { return next_sibling; } } function clear_text_content(node) { node.textContent = ""; } function validate_effect(rune) { if (active_effect === null && active_reaction === null) { effect_orphan(); } if (active_reaction !== null && (active_reaction.f & UNOWNED) !== 0 && active_effect === null) { effect_in_unowned_derived(); } if (is_destroying_effect) { effect_in_teardown(); } } function push_effect(effect2, parent_effect) { var parent_last = parent_effect.last; if (parent_last === null) { parent_effect.last = parent_effect.first = effect2; } else { parent_last.next = effect2; effect2.prev = parent_last; parent_effect.last = effect2; } } function create_effect(type, fn, sync, push2 = true) { var parent = active_effect; var effect2 = { ctx: component_context, deps: null, nodes_start: null, nodes_end: null, f: type | DIRTY, first: null, fn, last: null, next: null, parent, prev: null, teardown: null, transitions: null, wv: 0 }; if (sync) { try { update_effect(effect2); effect2.f |= EFFECT_RAN; } catch (e2) { destroy_effect(effect2); throw e2; } } else if (fn !== null) { schedule_effect(effect2); } var inert = sync && effect2.deps === null && effect2.first === null && effect2.nodes_start === null && effect2.teardown === null && (effect2.f & (EFFECT_HAS_DERIVED | BOUNDARY_EFFECT)) === 0; if (!inert && push2) { if (parent !== null) { push_effect(effect2, parent); } if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0) { var derived2 = ( /** @type {Derived} */ active_reaction ); (derived2.effects ?? (derived2.effects = [])).push(effect2); } } return effect2; } function effect_tracking() { return active_reaction !== null && !untracking; } function teardown(fn) { const effect2 = create_effect(RENDER_EFFECT, null, false); set_signal_status(effect2, CLEAN); effect2.teardown = fn; return effect2; } function user_effect(fn) { validate_effect(); var defer = active_effect !== null && (active_effect.f & BRANCH_EFFECT) !== 0 && component_context !== null && !component_context.m; if (defer) { var context = ( /** @type {ComponentContext} */ component_context ); (context.e ?? (context.e = [])).push({ fn, effect: active_effect, reaction: active_reaction }); } else { var signal = effect(fn); return signal; } } function user_pre_effect(fn) { validate_effect(); return render_effect(fn); } function component_root(fn) { const effect2 = create_effect(ROOT_EFFECT, fn, true); return (options = {}) => { return new Promise((fulfil) => { if (options.outro) { pause_effect(effect2, () => { destroy_effect(effect2); fulfil(void 0); }); } else { destroy_effect(effect2); fulfil(void 0); } }); }; } function effect(fn) { return create_effect(EFFECT, fn, false); } function render_effect(fn) { return create_effect(RENDER_EFFECT, fn, true); } function template_effect(fn, thunks = [], d = derived) { const deriveds = thunks.map(d); const effect2 = () => fn(...deriveds.map(get)); return block(effect2); } function block(fn, flags = 0) { return create_effect(RENDER_EFFECT | BLOCK_EFFECT | flags, fn, true); } function branch(fn, push2 = true) { return create_effect(RENDER_EFFECT | BRANCH_EFFECT, fn, true, push2); } function execute_effect_teardown(effect2) { var teardown2 = effect2.teardown; if (teardown2 !== null) { const previously_destroying_effect = is_destroying_effect; const previous_reaction = active_reaction; set_is_destroying_effect(true); set_active_reaction(null); try { teardown2.call(null); } finally { set_is_destroying_effect(previously_destroying_effect); set_active_reaction(previous_reaction); } } } function destroy_effect_children(signal, remove_dom = false) { var effect2 = signal.first; signal.first = signal.last = null; while (effect2 !== null) { var next2 = effect2.next; if ((effect2.f & ROOT_EFFECT) !== 0) { effect2.parent = null; } else { destroy_effect(effect2, remove_dom); } effect2 = next2; } } function destroy_block_effect_children(signal) { var effect2 = signal.first; while (effect2 !== null) { var next2 = effect2.next; if ((effect2.f & BRANCH_EFFECT) === 0) { destroy_effect(effect2); } effect2 = next2; } } function destroy_effect(effect2, remove_dom = true) { var removed = false; if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes_start !== null) { remove_effect_dom( effect2.nodes_start, /** @type {TemplateNode} */ effect2.nodes_end ); removed = true; } destroy_effect_children(effect2, remove_dom && !removed); remove_reactions(effect2, 0); set_signal_status(effect2, DESTROYED); var transitions = effect2.transitions; if (transitions !== null) { for (const transition of transitions) { transition.stop(); } } execute_effect_teardown(effect2); var parent = effect2.parent; if (parent !== null && parent.first !== null) { unlink_effect(effect2); } effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes_start = effect2.nodes_end = null; } function remove_effect_dom(node, end) { while (node !== null) { var next2 = node === end ? null : ( /** @type {TemplateNode} */ /* @__PURE__ */ get_next_sibling(node) ); node.remove(); node = next2; } } function unlink_effect(effect2) { var parent = effect2.parent; var prev = effect2.prev; var next2 = effect2.next; if (prev !== null) prev.next = next2; if (next2 !== null) next2.prev = prev; if (parent !== null) { if (parent.first === effect2) parent.first = next2; if (parent.last === effect2) parent.last = prev; } } function pause_effect(effect2, callback) { var transitions = []; pause_children(effect2, transitions, true); run_out_transitions(transitions, () => { destroy_effect(effect2); if (callback) callback(); }); } function run_out_transitions(transitions, fn) { var remaining = transitions.length; if (remaining > 0) { var check = () => --remaining || fn(); for (var transition of transitions) { transition.out(check); } } else { fn(); } } function pause_children(effect2, transitions, local) { if ((effect2.f & INERT) !== 0) return; effect2.f ^= INERT; if (effect2.transitions !== null) { for (const transition of effect2.transitions) { if (transition.is_global || local) { transitions.push(transition); } } } var child2 = effect2.first; while (child2 !== null) { var sibling2 = child2.next; var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0; pause_children(child2, transitions, transparent ? local : false); child2 = sibling2; } } function resume_effect(effect2) { resume_children(effect2, true); } function resume_children(effect2, local) { if ((effect2.f & INERT) === 0) return; effect2.f ^= INERT; if ((effect2.f & CLEAN) === 0) { effect2.f ^= CLEAN; } if (check_dirtiness(effect2)) { set_signal_status(effect2, DIRTY); schedule_effect(effect2); } var child2 = effect2.first; while (child2 !== null) { var sibling2 = child2.next; var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0; resume_children(child2, transparent ? local : false); child2 = sibling2; } if (effect2.transitions !== null) { for (const transition of effect2.transitions) { if (transition.is_global || local) { transition.in(); } } } } let micro_tasks = []; let idle_tasks = []; function run_micro_tasks() { var tasks = micro_tasks; micro_tasks = []; run_all(tasks); } function run_idle_tasks() { var tasks = idle_tasks; idle_tasks = []; run_all(tasks); } function queue_micro_task(fn) { if (micro_tasks.length === 0) { queueMicrotask(run_micro_tasks); } micro_tasks.push(fn); } function flush_tasks() { if (micro_tasks.length > 0) { run_micro_tasks(); } if (idle_tasks.length > 0) { run_idle_tasks(); } } let is_throwing_error = false; let is_flushing = false; let last_scheduled_effect = null; let is_updating_effect = false; let is_destroying_effect = false; function set_is_destroying_effect(value) { is_destroying_effect = value; } let queued_root_effects = []; let active_reaction = null; let untracking = false; function set_active_reaction(reaction) { active_reaction = reaction; } let active_effect = null; function set_active_effect(effect2) { active_effect = effect2; } let reaction_sources = null; function push_reaction_value(value) { if (active_reaction !== null && active_reaction.f & EFFECT_IS_UPDATING) { if (reaction_sources === null) { reaction_sources = [value]; } else { reaction_sources.push(value); } } } let new_deps = null; let skipped_deps = 0; let untracked_writes = null; function set_untracked_writes(value) { untracked_writes = value; } let write_version = 1; let read_version = 0; let skip_reaction = false; function increment_write_version() { return ++write_version; } function check_dirtiness(reaction) { var _a2; var flags = reaction.f; if ((flags & DIRTY) !== 0) { return true; } if ((flags & MAYBE_DIRTY) !== 0) { var dependencies = reaction.deps; var is_unowned = (flags & UNOWNED) !== 0; if (dependencies !== null) { var i2; var dependency; var is_disconnected = (flags & DISCONNECTED) !== 0; var is_unowned_connected = is_unowned && active_effect !== null && !skip_reaction; var length = dependencies.length; if (is_disconnected || is_unowned_connected) { var derived2 = ( /** @type {Derived} */ reaction ); var parent = derived2.parent; for (i2 = 0; i2 < length; i2++) { dependency = dependencies[i2]; if (is_disconnected || !((_a2 = dependency == null ? void 0 : dependency.reactions) == null ? void 0 : _a2.includes(derived2))) { (dependency.reactions ?? (dependency.reactions = [])).push(derived2); } } if (is_disconnected) { derived2.f ^= DISCONNECTED; } if (is_unowned_connected && parent !== null && (parent.f & UNOWNED) === 0) { derived2.f ^= UNOWNED; } } for (i2 = 0; i2 < length; i2++) { dependency = dependencies[i2]; if (check_dirtiness( /** @type {Derived} */ dependency )) { update_derived( /** @type {Derived} */ dependency ); } if (dependency.wv > reaction.wv) { return true; } } } if (!is_unowned || active_effect !== null && !skip_reaction) { set_signal_status(reaction, CLEAN); } } return false; } function propagate_error(error, effect2) { var current = effect2; while (current !== null) { if ((current.f & BOUNDARY_EFFECT) !== 0) { try { current.fn(error); return; } catch { current.f ^= BOUNDARY_EFFECT; } } current = current.parent; } is_throwing_error = false; throw error; } function should_rethrow_error(effect2) { return (effect2.f & DESTROYED) === 0 && (effect2.parent === null || (effect2.parent.f & BOUNDARY_EFFECT) === 0); } function handle_error(error, effect2, previous_effect, component_context2) { if (is_throwing_error) { if (previous_effect === null) { is_throwing_error = false; } if (should_rethrow_error(effect2)) { throw error; } return; } if (previous_effect !== null) { is_throwing_error = true; } propagate_error(error, effect2); if (should_rethrow_error(effect2)) { throw error; } } function schedule_possible_effect_self_invalidation(signal, effect2, root2 = true) { var reactions = signal.reactions; if (reactions === null) return; for (var i2 = 0; i2 < reactions.length; i2++) { var reaction = reactions[i2]; if (reaction_sources == null ? void 0 : reaction_sources.includes(signal)) continue; if ((reaction.f & DERIVED) !== 0) { schedule_possible_effect_self_invalidation( /** @type {Derived} */ reaction, effect2, false ); } else if (effect2 === reaction) { if (root2) { set_signal_status(reaction, DIRTY); } else if ((reaction.f & CLEAN) !== 0) { set_signal_status(reaction, MAYBE_DIRTY); } schedule_effect( /** @type {Effect} */ reaction ); } } } function update_reaction(reaction) { var _a2; var previous_deps = new_deps; var previous_skipped_deps = skipped_deps; var previous_untracked_writes = untracked_writes; var previous_reaction = active_reaction; var previous_skip_reaction = skip_reaction; var previous_reaction_sources = reaction_sources; var previous_component_context = component_context; var previous_untracking = untracking; var flags = reaction.f; new_deps = /** @type {null | Value[]} */ null; skipped_deps = 0; untracked_writes = null; skip_reaction = (flags & UNOWNED) !== 0 && (untracking || !is_updating_effect || active_reaction === null); active_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null; reaction_sources = null; set_component_context(reaction.ctx); untracking = false; read_version++; reaction.f |= EFFECT_IS_UPDATING; try { var result = ( /** @type {Function} */ (0, reaction.fn)() ); var deps = reaction.deps; if (new_deps !== null) { var i2; remove_reactions(reaction, skipped_deps); if (deps !== null && skipped_deps > 0) { deps.length = skipped_deps + new_deps.length; for (i2 = 0; i2 < new_deps.length; i2++) { deps[skipped_deps + i2] = new_deps[i2]; } } else { reaction.deps = deps = new_deps; } if (!skip_reaction) { for (i2 = skipped_deps; i2 < deps.length; i2++) { ((_a2 = deps[i2]).reactions ?? (_a2.reactions = [])).push(reaction); } } } else if (deps !== null && skipped_deps < deps.length) { remove_reactions(reaction, skipped_deps); deps.length = skipped_deps; } if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) { for (i2 = 0; i2 < /** @type {Source[]} */ untracked_writes.length; i2++) { schedule_possible_effect_self_invalidation( untracked_writes[i2], /** @type {Effect} */ reaction ); } } if (previous_reaction !== null && previous_reaction !== reaction) { read_version++; if (untracked_writes !== null) { if (previous_untracked_writes === null) { previous_untracked_writes = untracked_writes; } else { previous_untracked_writes.push(.../** @type {Source[]} */ untracked_writes); } } } return result; } finally { new_deps = previous_deps; skipped_deps = previous_skipped_deps; untracked_writes = previous_untracked_writes; active_reaction = previous_reaction; skip_reaction = previous_skip_reaction; reaction_sources = previous_reaction_sources; set_component_context(previous_component_context); untracking = previous_untracking; reaction.f ^= EFFECT_IS_UPDATING; } } function remove_reaction(signal, dependency) { let reactions = dependency.reactions; if (reactions !== null) { var index = index_of.call(reactions, signal); if (index !== -1) { var new_length = reactions.length - 1; if (new_length === 0) { reactions = dependency.reactions = null; } else { reactions[index] = reactions[new_length]; reactions.pop(); } } } if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps` // allows us to skip the expensive work of disconnecting and immediately reconnecting it (new_deps === null || !new_deps.includes(dependency))) { set_signal_status(dependency, MAYBE_DIRTY); if ((dependency.f & (UNOWNED | DISCONNECTED)) === 0) { dependency.f ^= DISCONNECTED; } destroy_derived_effects( /** @type {Derived} **/ dependency ); remove_reactions( /** @type {Derived} **/ dependency, 0 ); } } function remove_reactions(signal, start_index) { var dependencies = signal.deps; if (dependencies === null) return; for (var i2 = start_index; i2 < dependencies.length; i2++) { remove_reaction(signal, dependencies[i2]); } } function update_effect(effect2) { var flags = effect2.f; if ((flags & DESTROYED) !== 0) { return; } set_signal_status(effect2, CLEAN); var previous_effect = active_effect; var previous_component_context = component_context; var was_updating_effect = is_updating_effect; active_effect = effect2; is_updating_effect = true; try { if ((flags & BLOCK_EFFECT) !== 0) { destroy_block_effect_children(effect2); } else { destroy_effect_children(effect2); } execute_effect_teardown(effect2); var teardown2 = update_reaction(effect2); effect2.teardown = typeof teardown2 === "function" ? teardown2 : null; effect2.wv = write_version; var deps = effect2.deps; var dep; if (DEV && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && deps !== null) ; if (DEV) ; } catch (error) { handle_error(error, effect2, previous_effect, previous_component_context || effect2.ctx); } finally { is_updating_effect = was_updating_effect; active_effect = previous_effect; } } function infinite_loop_guard() { try { effect_update_depth_exceeded(); } catch (error) { if (last_scheduled_effect !== null) { { handle_error(error, last_scheduled_effect, null); } } else { throw error; } } } function flush_queued_root_effects() { var was_updating_effect = is_updating_effect; try { var flush_count = 0; is_updating_effect = true; while (queued_root_effects.length > 0) { if (flush_count++ > 1e3) { infinite_loop_guard(); } var root_effects = queued_root_effects; var length = root_effects.length; queued_root_effects = []; for (var i2 = 0; i2 < length; i2++) { var collected_effects = process_effects(root_effects[i2]); flush_queued_effects(collected_effects); } old_values.clear(); } } finally { is_flushing = false; is_updating_effect = was_updating_effect; last_scheduled_effect = null; } } function flush_queued_effects(effects) { var length = effects.length; if (length === 0) return; for (var i2 = 0; i2 < length; i2++) { var effect2 = effects[i2]; if ((effect2.f & (DESTROYED | INERT)) === 0) { try { if (check_dirtiness(effect2)) { update_effect(effect2); if (effect2.deps === null && effect2.first === null && effect2.nodes_start === null) { if (effect2.teardown === null) { unlink_effect(effect2); } else { effect2.fn = null; } } } } catch (error) { handle_error(error, effect2, null, effect2.ctx); } } } } function schedule_effect(signal) { if (!is_flushing) { is_flushing = true; queueMicrotask(flush_queued_root_effects); } var effect2 = last_scheduled_effect = signal; while (effect2.parent !== null) { effect2 = effect2.parent; var flags = effect2.f; if ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) { if ((flags & CLEAN) === 0) return; effect2.f ^= CLEAN; } } queued_root_effects.push(effect2); } function process_effects(root2) { var effects = []; var effect2 = root2; while (effect2 !== null) { var flags = effect2.f; var is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0; var is_skippable_branch = is_branch && (flags & CLEAN) !== 0; if (!is_skippable_branch && (flags & INERT) === 0) { if ((flags & EFFECT) !== 0) { effects.push(effect2); } else if (is_branch) { effect2.f ^= CLEAN; } else { try { if (check_dirtiness(effect2)) { update_effect(effect2); } } catch (error) { handle_error(error, effect2, null, effect2.ctx); } } var child2 = effect2.first; if (child2 !== null) { effect2 = child2; continue; } } var parent = effect2.parent; effect2 = effect2.next; while (effect2 === null && parent !== null) { effect2 = parent.next; parent = parent.parent; } } return effects; } function flushSync(fn) { var result; while (true) { flush_tasks(); if (queued_root_effects.length === 0) { return ( /** @type {T} */ result ); } is_flushing = true; flush_queued_root_effects(); } } async function tick() { await Promise.resolve(); flushSync(); } function get(signal) { var flags = signal.f; var is_derived = (flags & DERIVED) !== 0; if (active_reaction !== null && !untracking) { if (!(reaction_sources == null ? void 0 : reaction_sources.includes(signal))) { var deps = active_reaction.deps; if (signal.rv < read_version) { signal.rv = read_version; if (new_deps === null && deps !== null && deps[skipped_deps] === signal) { skipped_deps++; } else if (new_deps === null) { new_deps = [signal]; } else if (!skip_reaction || !new_deps.includes(signal)) { new_deps.push(signal); } } } } else if (is_derived && /** @type {Derived} */ signal.deps === null && /** @type {Derived} */ signal.effects === null) { var derived2 = ( /** @type {Derived} */ signal ); var parent = derived2.parent; if (parent !== null && (parent.f & UNOWNED) === 0) { derived2.f ^= UNOWNED; } } if (is_derived) { derived2 = /** @type {Derived} */ signal; if (check_dirtiness(derived2)) { update_derived(derived2); } } if (is_destroying_effect && old_values.has(signal)) { return old_values.get(signal); } return signal.v; } function untrack(fn) { var previous_untracking = untracking; try { untracking = true; return fn(); } finally { untracking = previous_untracking; } } const STATUS_MASK = -7169; function set_signal_status(signal, status) { signal.f = signal.f & STATUS_MASK | status; } function deep_read_state(value) { if (typeof value !== "object" || !value || value instanceof EventTarget) { return; } if (STATE_SYMBOL in value) { deep_read(value); } else if (!Array.isArray(value)) { for (let key in value) { const prop2 = value[key]; if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) { deep_read(prop2); } } } } function deep_read(value, visited = /* @__PURE__ */ new Set()) { if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements !(value instanceof EventTarget) && !visited.has(value)) { visited.add(value); if (value instanceof Date) { value.getTime(); } for (let key in value) { try { deep_read(value[key], visited); } catch (e2) { } } const proto = get_prototype_of(value); if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) { const descriptors = get_descriptors(proto); for (let key in descriptors) { const get2 = descriptors[key].get; if (get2) { try { get2.call(value); } catch (e2) { } } } } } } function is_capture_event(name) { return name.endsWith("capture") && name !== "gotpointercapture" && name !== "lostpointercapture"; } const DELEGATED_EVENTS = [ "beforeinput", "click", "change", "dblclick", "contextmenu", "focusin", "focusout", "input", "keydown", "keyup", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "pointerdown", "pointermove", "pointerout", "pointerover", "pointerup", "touchend", "touchmove", "touchstart" ]; function is_delegated(event_name) { return DELEGATED_EVENTS.includes(event_name); } const ATTRIBUTE_ALIASES = { // no `class: 'className'` because we handle that separately formnovalidate: "formNoValidate", ismap: "isMap", nomodule: "noModule", playsinline: "playsInline", readonly: "readOnly", defaultvalue: "defaultValue", defaultchecked: "defaultChecked", srcobject: "srcObject", novalidate: "noValidate", allowfullscreen: "allowFullscreen", disablepictureinpicture: "disablePictureInPicture", disableremoteplayback: "disableRemotePlayback" }; function normalize_attribute(name) { name = name.toLowerCase(); return ATTRIBUTE_ALIASES[name] ?? name; } const PASSIVE_EVENTS = ["touchstart", "touchmove"]; function is_passive_event(name) { return PASSIVE_EVENTS.includes(name); } function autofocus(dom, value) { if (value) { const body = document.body; dom.autofocus = true; queue_micro_task(() => { if (document.activeElement === body) { dom.focus(); } }); } } function without_reactive_context(fn) { var previous_reaction = active_reaction; var previous_effect = active_effect; set_active_reaction(null); set_active_effect(null); try { return fn(); } finally { set_active_reaction(previous_reaction); set_active_effect(previous_effect); } } const all_registered_events = /* @__PURE__ */ new Set(); const root_event_handles = /* @__PURE__ */ new Set(); function create_event(event_name, dom, handler, options = {}) { function target_handler(event2) { if (!options.capture) { handle_event_propagation.call(dom, event2); } if (!event2.cancelBubble) { return without_reactive_context(() => { return handler == null ? void 0 : handler.call(this, event2); }); } } if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") { queue_micro_task(() => { dom.addEventListener(event_name, target_handler, options); }); } else { dom.addEventListener(event_name, target_handler, options); } return target_handler; } function on(element, type, handler, options = {}) { var target_handler = create_event(type, element, handler, options); return () => { element.removeEventListener(type, target_handler, options); }; } function event(event_name, dom, handler, capture, passive) { var options = { capture, passive }; var target_handler = create_event(event_name, dom, handler, options); if (dom === document.body || dom === window || dom === document) { teardown(() => { dom.removeEventListener(event_name, target_handler, options); }); } } function delegate(events) { for (var i2 = 0; i2 < events.length; i2++) { all_registered_events.add(events[i2]); } for (var fn of root_event_handles) { fn(events); } } function handle_event_propagation(event2) { var _a2; var handler_element = this; var owner_document = ( /** @type {Node} */ handler_element.ownerDocument ); var event_name = event2.type; var path = ((_a2 = event2.composedPath) == null ? void 0 : _a2.call(event2)) || []; var current_target = ( /** @type {null | Element} */ path[0] || event2.target ); var path_idx = 0; var handled_at = event2.__root; if (handled_at) { var at_idx = path.indexOf(handled_at); if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */ window)) { event2.__root = handler_element; return; } var handler_idx = path.indexOf(handler_element); if (handler_idx === -1) { return; } if (at_idx <= handler_idx) { path_idx = at_idx; } } current_target = /** @type {Element} */ path[path_idx] || event2.target; if (current_target === handler_element) return; define_property(event2, "currentTarget", { configurable: true, get() { return current_target || owner_document; } }); var previous_reaction = active_reaction; var previous_effect = active_effect; set_active_reaction(null); set_active_effect(null); try { var throw_error; var other_errors = []; while (current_target !== null) { var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */ current_target.host || null; try { var delegated = current_target["__" + event_name]; if (delegated != null && (!/** @type {any} */ current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well // -> the target could not have been disabled because it emits the event in the first place event2.target === current_target)) { if (is_array(delegated)) { var [fn, ...data] = delegated; fn.apply(current_target, [event2, ...data]); } else { delegated.call(current_target, event2); } } } catch (error) { if (throw_error) { other_errors.push(error); } else { throw_error = error; } } if (event2.cancelBubble || parent_element === handler_element || parent_element === null) { break; } current_target = parent_element; } if (throw_error) { for (let error of other_errors) { queueMicrotask(() => { throw error; }); } throw throw_error; } } finally { event2.__root = handler_element; delete event2.currentTarget; set_active_reaction(previous_reaction); set_active_effect(previous_effect); } } function create_fragment_from_html(html) { var elem = document.createElement("template"); elem.innerHTML = html; return elem.content; } function assign_nodes(start, end) { var effect2 = ( /** @type {Effect} */ active_effect ); if (effect2.nodes_start === null) { effect2.nodes_start = start; effect2.nodes_end = end; } } // @__NO_SIDE_EFFECTS__ function template(content, flags) { var is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0; var use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0; var node; var has_start = !content.startsWith(""); return () => { if (node === void 0) { node = create_fragment_from_html(has_start ? content : "" + content); if (!is_fragment) node = /** @type {Node} */ /* @__PURE__ */ get_first_child(node); } var clone = ( /** @type {TemplateNode} */ use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true) ); if (is_fragment) { var start = ( /** @type {TemplateNode} */ /* @__PURE__ */ get_first_child(clone) ); var end = ( /** @type {TemplateNode} */ clone.lastChild ); assign_nodes(start, end); } else { assign_nodes(clone, clone); } return clone; }; } // @__NO_SIDE_EFFECTS__ function ns_template(content, flags, ns = "svg") { var has_start = !content.startsWith(""); var wrapped = `<${ns}>${has_start ? content : "" + content}`; var node; return () => { if (!node) { var fragment = ( /** @type {DocumentFragment} */ create_fragment_from_html(wrapped) ); var root2 = ( /** @type {Element} */ /* @__PURE__ */ get_first_child(fragment) ); { node = /** @type {Element} */ /* @__PURE__ */ get_first_child(root2); } } var clone = ( /** @type {TemplateNode} */ node.cloneNode(true) ); { assign_nodes(clone, clone); } return clone; }; } function text(value = "") { { var t = create_text(value + ""); assign_nodes(t, t); return t; } } function comment() { var frag = document.createDocumentFragment(); var start = document.createComment(""); var anchor = create_text(); frag.append(start, anchor); assign_nodes(start, anchor); return frag; } function append(anchor, dom) { if (anchor === null) { return; } anchor.before( /** @type {Node} */ dom ); } function set_text(text2, value) { var str = value == null ? "" : typeof value === "object" ? value + "" : value; if (str !== (text2.__t ?? (text2.__t = text2.nodeValue))) { text2.__t = str; text2.nodeValue = str + ""; } } function mount(component2, options) { return _mount(component2, options); } const document_listeners = /* @__PURE__ */ new Map(); function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) { init_operations(); var registered_events = /* @__PURE__ */ new Set(); var event_handle = (events2) => { for (var i2 = 0; i2 < events2.length; i2++) { var event_name = events2[i2]; if (registered_events.has(event_name)) continue; registered_events.add(event_name); var passive = is_passive_event(event_name); target.addEventListener(event_name, handle_event_propagation, { passive }); var n = document_listeners.get(event_name); if (n === void 0) { document.addEventListener(event_name, handle_event_propagation, { passive }); document_listeners.set(event_name, 1); } else { document_listeners.set(event_name, n + 1); } } }; event_handle(array_from(all_registered_events)); root_event_handles.add(event_handle); var component2 = void 0; var unmount = component_root(() => { var anchor_node = anchor ?? target.appendChild(create_text()); branch(() => { if (context) { push({}); var ctx = ( /** @type {ComponentContext} */ component_context ); ctx.c = context; } if (events) { props.$$events = events; } component2 = Component(anchor_node, props) || {}; if (context) { pop(); } }); return () => { var _a2; for (var event_name of registered_events) { target.removeEventListener(event_name, handle_event_propagation); var n = ( /** @type {number} */ document_listeners.get(event_name) ); if (--n === 0) { document.removeEventListener(event_name, handle_event_propagation); document_listeners.delete(event_name); } else { document_listeners.set(event_name, n); } } root_event_handles.delete(event_handle); if (anchor_node !== anchor) { (_a2 = anchor_node.parentNode) == null ? void 0 : _a2.removeChild(anchor_node); } }; }); mounted_components.set(component2, unmount); return component2; } let mounted_components = /* @__PURE__ */ new WeakMap(); function if_block(node, fn, [root_index, hydrate_index] = [0, 0]) { var anchor = node; var consequent_effect = null; var alternate_effect = null; var condition = UNINITIALIZED; var flags = root_index > 0 ? EFFECT_TRANSPARENT : 0; var has_branch = false; const set_branch = (fn2, flag = true) => { has_branch = true; update_branch(flag, fn2); }; const update_branch = (new_condition, fn2) => { if (condition === (condition = new_condition)) return; if (condition) { if (consequent_effect) { resume_effect(consequent_effect); } else if (fn2) { consequent_effect = branch(() => fn2(anchor)); } if (alternate_effect) { pause_effect(alternate_effect, () => { alternate_effect = null; }); } } else { if (alternate_effect) { resume_effect(alternate_effect); } else if (fn2) { alternate_effect = branch(() => fn2(anchor, [root_index + 1, hydrate_index])); } if (consequent_effect) { pause_effect(consequent_effect, () => { consequent_effect = null; }); } } }; block(() => { has_branch = false; fn(set_branch); if (!has_branch) { update_branch(null, null); } }, flags); } function pause_effects(state2, items, controlled_anchor, items_map) { var transitions = []; var length = items.length; for (var i2 = 0; i2 < length; i2++) { pause_children(items[i2].e, transitions, true); } var is_controlled = length > 0 && transitions.length === 0 && controlled_anchor !== null; if (is_controlled) { var parent_node = ( /** @type {Element} */ /** @type {Element} */ controlled_anchor.parentNode ); clear_text_content(parent_node); parent_node.append( /** @type {Element} */ controlled_anchor ); items_map.clear(); link(state2, items[0].prev, items[length - 1].next); } run_out_transitions(transitions, () => { for (var i3 = 0; i3 < length; i3++) { var item = items[i3]; if (!is_controlled) { items_map.delete(item.k); link(state2, item.prev, item.next); } destroy_effect(item.e, !is_controlled); } }); } function each(node, flags, get_collection, get_key, render_fn, fallback_fn = null) { var anchor = node; var state2 = { flags, items: /* @__PURE__ */ new Map(), first: null }; var is_controlled = (flags & EACH_IS_CONTROLLED) !== 0; if (is_controlled) { var parent_node = ( /** @type {Element} */ node ); anchor = parent_node.appendChild(create_text()); } var fallback = null; var was_empty = false; var each_array = /* @__PURE__ */ derived_safe_equal(() => { var collection = get_collection(); return is_array(collection) ? collection : collection == null ? [] : array_from(collection); }); block(() => { var array = get(each_array); var length = array.length; if (was_empty && length === 0) { return; } was_empty = length === 0; { reconcile(array, state2, anchor, render_fn, flags, get_key, get_collection); } if (fallback_fn !== null) { if (length === 0) { if (fallback) { resume_effect(fallback); } else { fallback = branch(() => fallback_fn(anchor)); } } else if (fallback !== null) { pause_effect(fallback, () => { fallback = null; }); } } get(each_array); }); } function reconcile(array, state2, anchor, render_fn, flags, get_key, get_collection) { var _a2, _b, _c, _d; var is_animated = (flags & EACH_IS_ANIMATED) !== 0; var should_update = (flags & (EACH_ITEM_REACTIVE | EACH_INDEX_REACTIVE)) !== 0; var length = array.length; var items = state2.items; var first = state2.first; var current = first; var seen; var prev = null; var to_animate; var matched = []; var stashed = []; var value; var key; var item; var i2; if (is_animated) { for (i2 = 0; i2 < length; i2 += 1) { value = array[i2]; key = get_key(value, i2); item = items.get(key); if (item !== void 0) { (_a2 = item.a) == null ? void 0 : _a2.measure(); (to_animate ?? (to_animate = /* @__PURE__ */ new Set())).add(item); } } } for (i2 = 0; i2 < length; i2 += 1) { value = array[i2]; key = get_key(value, i2); item = items.get(key); if (item === void 0) { var child_anchor = current ? ( /** @type {TemplateNode} */ current.e.nodes_start ) : anchor; prev = create_item( child_anchor, state2, prev, prev === null ? state2.first : prev.next, value, key, i2, render_fn, flags, get_collection ); items.set(key, prev); matched = []; stashed = []; current = prev.next; continue; } if (should_update) { update_item(item, value, i2, flags); } if ((item.e.f & INERT) !== 0) { resume_effect(item.e); if (is_animated) { (_b = item.a) == null ? void 0 : _b.unfix(); (to_animate ?? (to_animate = /* @__PURE__ */ new Set())).delete(item); } } if (item !== current) { if (seen !== void 0 && seen.has(item)) { if (matched.length < stashed.length) { var start = stashed[0]; var j; prev = start.prev; var a2 = matched[0]; var b = matched[matched.length - 1]; for (j = 0; j < matched.length; j += 1) { move(matched[j], start, anchor); } for (j = 0; j < stashed.length; j += 1) { seen.delete(stashed[j]); } link(state2, a2.prev, b.next); link(state2, prev, a2); link(state2, b, start); current = start; prev = b; i2 -= 1; matched = []; stashed = []; } else { seen.delete(item); move(item, current, anchor); link(state2, item.prev, item.next); link(state2, item, prev === null ? state2.first : prev.next); link(state2, prev, item); prev = item; } continue; } matched = []; stashed = []; while (current !== null && current.k !== key) { if ((current.e.f & INERT) === 0) { (seen ?? (seen = /* @__PURE__ */ new Set())).add(current); } stashed.push(current); current = current.next; } if (current === null) { continue; } item = current; } matched.push(item); prev = item; current = item.next; } if (current !== null || seen !== void 0) { var to_destroy = seen === void 0 ? [] : array_from(seen); while (current !== null) { if ((current.e.f & INERT) === 0) { to_destroy.push(current); } current = current.next; } var destroy_length = to_destroy.length; if (destroy_length > 0) { var controlled_anchor = (flags & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null; if (is_animated) { for (i2 = 0; i2 < destroy_length; i2 += 1) { (_c = to_destroy[i2].a) == null ? void 0 : _c.measure(); } for (i2 = 0; i2 < destroy_length; i2 += 1) { (_d = to_destroy[i2].a) == null ? void 0 : _d.fix(); } } pause_effects(state2, to_destroy, controlled_anchor, items); } } if (is_animated) { queue_micro_task(() => { var _a3; if (to_animate === void 0) return; for (item of to_animate) { (_a3 = item.a) == null ? void 0 : _a3.apply(); } }); } active_effect.first = state2.first && state2.first.e; active_effect.last = prev && prev.e; } function update_item(item, value, index, type) { if ((type & EACH_ITEM_REACTIVE) !== 0) { internal_set(item.v, value); } if ((type & EACH_INDEX_REACTIVE) !== 0) { internal_set( /** @type {Value} */ item.i, index ); } else { item.i = index; } } function create_item(anchor, state2, prev, next2, value, key, index, render_fn, flags, get_collection) { var reactive = (flags & EACH_ITEM_REACTIVE) !== 0; var mutable = (flags & EACH_ITEM_IMMUTABLE) === 0; var v2 = reactive ? mutable ? /* @__PURE__ */ mutable_source(value) : source(value) : value; var i2 = (flags & EACH_INDEX_REACTIVE) === 0 ? index : source(index); var item = { i: i2, v: v2, k: key, a: null, // @ts-expect-error e: null, prev, next: next2 }; try { item.e = branch(() => render_fn(anchor, v2, i2, get_collection), hydrating); item.e.prev = prev && prev.e; item.e.next = next2 && next2.e; if (prev === null) { state2.first = item; } else { prev.next = item; prev.e.next = item.e; } if (next2 !== null) { next2.prev = item; next2.e.prev = item.e; } return item; } finally { } } function move(item, next2, anchor) { var end = item.next ? ( /** @type {TemplateNode} */ item.next.e.nodes_start ) : anchor; var dest = next2 ? ( /** @type {TemplateNode} */ next2.e.nodes_start ) : anchor; var node = ( /** @type {TemplateNode} */ item.e.nodes_start ); while (node !== end) { var next_node = ( /** @type {TemplateNode} */ /* @__PURE__ */ get_next_sibling(node) ); dest.before(node); node = next_node; } } function link(state2, prev, next2) { if (prev === null) { state2.first = next2; } else { prev.next = next2; prev.e.next = next2 && next2.e; } if (next2 !== null) { next2.prev = prev; next2.e.prev = prev && prev.e; } } function snippet(node, get_snippet, ...args) { var anchor = node; var snippet2 = noop; var snippet_effect; block(() => { if (snippet2 === (snippet2 = get_snippet())) return; if (snippet_effect) { destroy_effect(snippet_effect); snippet_effect = null; } snippet_effect = branch(() => ( /** @type {SnippetFn} */ snippet2(anchor, ...args) )); }, EFFECT_TRANSPARENT); } function component(node, get_component, render_fn) { var anchor = node; var component2; var effect2; block(() => { if (component2 === (component2 = get_component())) return; if (effect2) { pause_effect(effect2); effect2 = null; } if (component2) { effect2 = branch(() => render_fn(anchor, component2)); } }, EFFECT_TRANSPARENT); } function r(e2) { var t, f, n = ""; if ("string" == typeof e2 || "number" == typeof e2) n += e2; else if ("object" == typeof e2) if (Array.isArray(e2)) { var o2 = e2.length; for (t = 0; t < o2; t++) e2[t] && (f = r(e2[t])) && (n && (n += " "), n += f); } else for (f in e2) e2[f] && (n && (n += " "), n += f); return n; } function clsx$1() { for (var e2, t, f = 0, n = "", o2 = arguments.length; f < o2; f++) (e2 = arguments[f]) && (t = r(e2)) && (n && (n += " "), n += t); return n; } function clsx(value) { if (typeof value === "object") { return clsx$1(value); } else { return value ?? ""; } } const whitespace = [..." \n\r\f \v\uFEFF"]; function to_class(value, hash, directives) { var classname = value == null ? "" : "" + value; if (hash) { classname = classname ? classname + " " + hash : hash; } if (directives) { for (var key in directives) { if (directives[key]) { classname = classname ? classname + " " + key : key; } else if (classname.length) { var len = key.length; var a2 = 0; while ((a2 = classname.indexOf(key, a2)) >= 0) { var b = a2 + len; if ((a2 === 0 || whitespace.includes(classname[a2 - 1])) && (b === classname.length || whitespace.includes(classname[b]))) { classname = (a2 === 0 ? "" : classname.substring(0, a2)) + classname.substring(b + 1); } else { a2 = b; } } } } } return classname === "" ? null : classname; } function append_styles(styles, important = false) { var separator = important ? " !important;" : ";"; var css = ""; for (var key in styles) { var value = styles[key]; if (value != null && value !== "") { css += " " + key + ": " + value + separator; } } return css; } function to_css_name(name) { if (name[0] !== "-" || name[1] !== "-") { return name.toLowerCase(); } return name; } function to_style(value, styles) { if (styles) { var new_style = ""; var normal_styles; var important_styles; if (Array.isArray(styles)) { normal_styles = styles[0]; important_styles = styles[1]; } else { normal_styles = styles; } if (value) { value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim(); var in_str = false; var in_apo = 0; var in_comment = false; var reserved_names = []; if (normal_styles) { reserved_names.push(...Object.keys(normal_styles).map(to_css_name)); } if (important_styles) { reserved_names.push(...Object.keys(important_styles).map(to_css_name)); } var start_index = 0; var name_index = -1; const len = value.length; for (var i2 = 0; i2 < len; i2++) { var c2 = value[i2]; if (in_comment) { if (c2 === "/" && value[i2 - 1] === "*") { in_comment = false; } } else if (in_str) { if (in_str === c2) { in_str = false; } } else if (c2 === "/" && value[i2 + 1] === "*") { in_comment = true; } else if (c2 === '"' || c2 === "'") { in_str = c2; } else if (c2 === "(") { in_apo++; } else if (c2 === ")") { in_apo--; } if (!in_comment && in_str === false && in_apo === 0) { if (c2 === ":" && name_index === -1) { name_index = i2; } else if (c2 === ";" || i2 === len - 1) { if (name_index !== -1) { var name = to_css_name(value.substring(start_index, name_index).trim()); if (!reserved_names.includes(name)) { if (c2 !== ";") { i2++; } var property = value.substring(start_index, i2).trim(); new_style += " " + property + ";"; } } start_index = i2 + 1; name_index = -1; } } } } if (normal_styles) { new_style += append_styles(normal_styles); } if (important_styles) { new_style += append_styles(important_styles, true); } new_style = new_style.trim(); return new_style === "" ? null : new_style; } return value == null ? null : String(value); } function set_class(dom, is_html, value, hash, prev_classes, next_classes) { var prev = dom.__className; if (prev !== value || prev === void 0) { var next_class_name = to_class(value, hash, next_classes); { if (next_class_name == null) { dom.removeAttribute("class"); } else if (is_html) { dom.className = next_class_name; } else { dom.setAttribute("class", next_class_name); } } dom.__className = value; } else if (next_classes && prev_classes !== next_classes) { for (var key in next_classes) { var is_present = !!next_classes[key]; if (prev_classes == null || is_present !== !!prev_classes[key]) { dom.classList.toggle(key, is_present); } } } return next_classes; } function update_styles(dom, prev = {}, next2, priority) { for (var key in next2) { var value = next2[key]; if (prev[key] !== value) { if (next2[key] == null) { dom.style.removeProperty(key); } else { dom.style.setProperty(key, value, priority); } } } } function set_style(dom, value, prev_styles, next_styles) { var prev = dom.__style; if (prev !== value) { var next_style_attr = to_style(value, next_styles); { if (next_style_attr == null) { dom.removeAttribute("style"); } else { dom.style.cssText = next_style_attr; } } dom.__style = value; } else if (next_styles) { if (Array.isArray(next_styles)) { update_styles(dom, prev_styles == null ? void 0 : prev_styles[0], next_styles[0]); update_styles(dom, prev_styles == null ? void 0 : prev_styles[1], next_styles[1], "important"); } else { update_styles(dom, prev_styles, next_styles); } } return next_styles; } const CLASS = Symbol("class"); const STYLE = Symbol("style"); const IS_CUSTOM_ELEMENT = Symbol("is custom element"); const IS_HTML = Symbol("is html"); function set_selected(element, selected) { if (selected) { if (!element.hasAttribute("selected")) { element.setAttribute("selected", ""); } } else { element.removeAttribute("selected"); } } function set_attribute(element, attribute, value, skip_warning) { var attributes = get_attributes(element); if (attributes[attribute] === (attributes[attribute] = value)) return; if (attribute === "loading") { element[LOADING_ATTR_SYMBOL] = value; } if (value == null) { element.removeAttribute(attribute); } else if (typeof value !== "string" && get_setters(element).includes(attribute)) { element[attribute] = value; } else { element.setAttribute(attribute, value); } } function set_attributes(element, prev, next2, css_hash, skip_warning = false) { var attributes = get_attributes(element); var is_custom_element = attributes[IS_CUSTOM_ELEMENT]; var preserve_attribute_case = !attributes[IS_HTML]; var current = prev || {}; var is_option_element = element.tagName === "OPTION"; for (var key in prev) { if (!(key in next2)) { next2[key] = null; } } if (next2.class) { next2.class = clsx(next2.class); } else if (css_hash || next2[CLASS]) { next2.class = null; } if (next2[STYLE]) { next2.style ?? (next2.style = null); } var setters = get_setters(element); for (const key2 in next2) { let value = next2[key2]; if (is_option_element && key2 === "value" && value == null) { element.value = element.__value = ""; current[key2] = value; continue; } if (key2 === "class") { var is_html = element.namespaceURI === "http://www.w3.org/1999/xhtml"; set_class(element, is_html, value, css_hash, prev == null ? void 0 : prev[CLASS], next2[CLASS]); current[key2] = value; current[CLASS] = next2[CLASS]; continue; } if (key2 === "style") { set_style(element, value, prev == null ? void 0 : prev[STYLE], next2[STYLE]); current[key2] = value; current[STYLE] = next2[STYLE]; continue; } var prev_value = current[key2]; if (value === prev_value) continue; current[key2] = value; var prefix = key2[0] + key2[1]; if (prefix === "$$") continue; if (prefix === "on") { const opts = {}; const event_handle_key = "$$" + key2; let event_name = key2.slice(2); var delegated = is_delegated(event_name); if (is_capture_event(event_name)) { event_name = event_name.slice(0, -7); opts.capture = true; } if (!delegated && prev_value) { if (value != null) continue; element.removeEventListener(event_name, current[event_handle_key], opts); current[event_handle_key] = null; } if (value != null) { if (!delegated) { let handle = function(evt) { current[key2].call(this, evt); }; current[event_handle_key] = create_event(event_name, element, handle, opts); } else { element[`__${event_name}`] = value; delegate([event_name]); } } else if (delegated) { element[`__${event_name}`] = void 0; } } else if (key2 === "style") { set_attribute(element, key2, value); } else if (key2 === "autofocus") { autofocus( /** @type {HTMLElement} */ element, Boolean(value) ); } else if (!is_custom_element && (key2 === "__value" || key2 === "value" && value != null)) { element.value = element.__value = value; } else if (key2 === "selected" && is_option_element) { set_selected( /** @type {HTMLOptionElement} */ element, value ); } else { var name = key2; if (!preserve_attribute_case) { name = normalize_attribute(name); } var is_default = name === "defaultValue" || name === "defaultChecked"; if (value == null && !is_custom_element && !is_default) { attributes[key2] = null; if (name === "value" || name === "checked") { let input = ( /** @type {HTMLInputElement} */ element ); const use_default = prev === void 0; if (name === "value") { let previous = input.defaultValue; input.removeAttribute(name); input.defaultValue = previous; input.value = input.__value = use_default ? previous : null; } else { let previous = input.defaultChecked; input.removeAttribute(name); input.defaultChecked = previous; input.checked = use_default ? previous : false; } } else { element.removeAttribute(key2); } } else if (is_default || setters.includes(name) && (is_custom_element || typeof value !== "string")) { element[name] = value; } else if (typeof value !== "function") { set_attribute(element, name, value); } } } return current; } function get_attributes(element) { return ( /** @type {Record} **/ // @ts-expect-error element.__attributes ?? (element.__attributes = { [IS_CUSTOM_ELEMENT]: element.nodeName.includes("-"), [IS_HTML]: element.namespaceURI === NAMESPACE_HTML }) ); } var setters_cache = /* @__PURE__ */ new Map(); function get_setters(element) { var setters = setters_cache.get(element.nodeName); if (setters) return setters; setters_cache.set(element.nodeName, setters = []); var descriptors; var proto = element; var element_proto = Element.prototype; while (element_proto !== proto) { descriptors = get_descriptors(proto); for (var key in descriptors) { if (descriptors[key].set) { setters.push(key); } } proto = get_prototype_of(proto); } return setters; } function is_bound_this(bound_value, element_or_component) { return bound_value === element_or_component || (bound_value == null ? void 0 : bound_value[STATE_SYMBOL]) === element_or_component; } function bind_this(element_or_component = {}, update, get_value, get_parts) { effect(() => { var old_parts; var parts; render_effect(() => { old_parts = parts; parts = []; untrack(() => { if (element_or_component !== get_value(...parts)) { update(element_or_component, ...parts); if (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) { update(null, ...old_parts); } } }); }); return () => { queue_micro_task(() => { if (parts && is_bound_this(get_value(...parts), element_or_component)) { update(null, ...parts); } }); }; }); return element_or_component; } function init(immutable = false) { const context = ( /** @type {ComponentContextLegacy} */ component_context ); const callbacks = context.l.u; if (!callbacks) return; let props = () => deep_read_state(context.s); if (immutable) { let version = 0; let prev = ( /** @type {Record} */ {} ); const d = /* @__PURE__ */ derived(() => { let changed = false; const props2 = context.s; for (const key in props2) { if (props2[key] !== prev[key]) { prev[key] = props2[key]; changed = true; } } if (changed) version++; return version; }); props = () => get(d); } if (callbacks.b.length) { user_pre_effect(() => { observe_all(context, props); run_all(callbacks.b); }); } user_effect(() => { const fns = untrack(() => callbacks.m.map(run)); return () => { for (const fn of fns) { if (typeof fn === "function") { fn(); } } }; }); if (callbacks.a.length) { user_effect(() => { observe_all(context, props); run_all(callbacks.a); }); } } function observe_all(context, props) { if (context.l.s) { for (const signal of context.l.s) get(signal); } props(); } let is_store_binding = false; function capture_store_binding(fn) { var previous_is_store_binding = is_store_binding; try { is_store_binding = false; return [fn(), is_store_binding]; } finally { is_store_binding = previous_is_store_binding; } } const rest_props_handler = { get(target, key) { if (target.exclude.includes(key)) return; return target.props[key]; }, set(target, key) { return false; }, getOwnPropertyDescriptor(target, key) { if (target.exclude.includes(key)) return; if (key in target.props) { return { enumerable: true, configurable: true, value: target.props[key] }; } }, has(target, key) { if (target.exclude.includes(key)) return false; return key in target.props; }, ownKeys(target) { return Reflect.ownKeys(target.props).filter((key) => !target.exclude.includes(key)); } }; // @__NO_SIDE_EFFECTS__ function rest_props(props, exclude, name) { return new Proxy( { props, exclude }, rest_props_handler ); } const spread_props_handler = { get(target, key) { let i2 = target.props.length; while (i2--) { let p = target.props[i2]; if (is_function(p)) p = p(); if (typeof p === "object" && p !== null && key in p) return p[key]; } }, set(target, key, value) { let i2 = target.props.length; while (i2--) { let p = target.props[i2]; if (is_function(p)) p = p(); const desc = get_descriptor(p, key); if (desc && desc.set) { desc.set(value); return true; } } return false; }, getOwnPropertyDescriptor(target, key) { let i2 = target.props.length; while (i2--) { let p = target.props[i2]; if (is_function(p)) p = p(); if (typeof p === "object" && p !== null && key in p) { const descriptor = get_descriptor(p, key); if (descriptor && !descriptor.configurable) { descriptor.configurable = true; } return descriptor; } } }, has(target, key) { if (key === STATE_SYMBOL || key === LEGACY_PROPS) return false; for (let p of target.props) { if (is_function(p)) p = p(); if (p != null && key in p) return true; } return false; }, ownKeys(target) { const keys = []; for (let p of target.props) { if (is_function(p)) p = p(); for (const key in p) { if (!keys.includes(key)) keys.push(key); } } return keys; } }; function spread_props(...props) { return new Proxy({ props }, spread_props_handler); } function has_destroyed_component_ctx(current_value) { var _a2; return ((_a2 = current_value.ctx) == null ? void 0 : _a2.d) ?? false; } function prop(props, key, flags, fallback) { var _a2; var immutable = (flags & PROPS_IS_IMMUTABLE) !== 0; var runes = !legacy_mode_flag || (flags & PROPS_IS_RUNES) !== 0; var bindable = (flags & PROPS_IS_BINDABLE) !== 0; var lazy = (flags & PROPS_IS_LAZY_INITIAL) !== 0; var is_store_sub = false; var prop_value; if (bindable) { [prop_value, is_store_sub] = capture_store_binding(() => ( /** @type {V} */ props[key] )); } else { prop_value = /** @type {V} */ props[key]; } var is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props; var setter = bindable && (((_a2 = get_descriptor(props, key)) == null ? void 0 : _a2.set) ?? (is_entry_props && key in props && ((v2) => props[key] = v2))) || void 0; var fallback_value = ( /** @type {V} */ fallback ); var fallback_dirty = true; var fallback_used = false; var get_fallback = () => { fallback_used = true; if (fallback_dirty) { fallback_dirty = false; if (lazy) { fallback_value = untrack( /** @type {() => V} */ fallback ); } else { fallback_value = /** @type {V} */ fallback; } } return fallback_value; }; if (prop_value === void 0 && fallback !== void 0) { if (setter && runes) { props_invalid_value(); } prop_value = get_fallback(); if (setter) setter(prop_value); } var getter; if (runes) { getter = () => { var value = ( /** @type {V} */ props[key] ); if (value === void 0) return get_fallback(); fallback_dirty = true; fallback_used = false; return value; }; } else { var derived_getter = (immutable ? derived : derived_safe_equal)( () => ( /** @type {V} */ props[key] ) ); derived_getter.f |= LEGACY_DERIVED_PROP; getter = () => { var value = get(derived_getter); if (value !== void 0) fallback_value = /** @type {V} */ void 0; return value === void 0 ? fallback_value : value; }; } if ((flags & PROPS_IS_UPDATED) === 0) { return getter; } if (setter) { var legacy_parent = props.$$legacy; return function(value, mutation) { if (arguments.length > 0) { if (!runes || !mutation || legacy_parent || is_store_sub) { setter(mutation ? getter() : value); } return value; } else { return getter(); } }; } var from_child = false; var inner_current_value = /* @__PURE__ */ mutable_source(prop_value); var current_value = /* @__PURE__ */ derived(() => { var parent_value = getter(); var child_value = get(inner_current_value); if (from_child) { from_child = false; return child_value; } return inner_current_value.v = parent_value; }); if (bindable) { get(current_value); } if (!immutable) current_value.equals = safe_equals; return function(value, mutation) { if (arguments.length > 0) { const new_value = mutation ? get(current_value) : runes && bindable ? proxy(value) : value; if (!current_value.equals(new_value)) { from_child = true; set(inner_current_value, new_value); if (fallback_used && fallback_value !== void 0) { fallback_value = new_value; } if (has_destroyed_component_ctx(current_value)) { return value; } untrack(() => get(current_value)); } return value; } if (has_destroyed_component_ctx(current_value)) { return current_value.v; } return get(current_value); }; } function onMount(fn) { if (component_context === null) { lifecycle_outside_component(); } if (legacy_mode_flag && component_context.l !== null) { init_update_callbacks(component_context).m.push(fn); } else { user_effect(() => { const cleanup = untrack(fn); if (typeof cleanup === "function") return ( /** @type {() => void} */ cleanup ); }); } } function init_update_callbacks(context) { var l = ( /** @type {ComponentContextLegacy} */ context.l ); return l.u ?? (l.u = { a: [], b: [], m: [] }); } const PUBLIC_VERSION = "5"; if (typeof window !== "undefined") { ((_a = window.__svelte ?? (window.__svelte = {})).v ?? (_a.v = /* @__PURE__ */ new Set())).add(PUBLIC_VERSION); } enable_legacy_mode_flag(); const bars = Array(12).fill(0); var root_1$4 = /* @__PURE__ */ template(`
`); var root$9 = /* @__PURE__ */ template(`
`); function Loader($$anchor, $$props) { push($$props, true); var div = root$9(); var div_1 = child(div); each(div_1, 23, () => bars, (_, i2) => `spinner-bar-${i2}`, ($$anchor2, _) => { var div_2 = root_1$4(); append($$anchor2, div_2); }); template_effect( ($0) => { set_class(div, 1, $0); set_attribute(div, "data-visible", $$props.visible); }, [ () => clsx(["sonner-loading-wrapper", $$props.class].filter(Boolean).join(" ")) ] ); append($$anchor, div); pop(); } function cn(...classes) { return classes.filter(Boolean).join(" "); } const isBrowser = typeof document !== "undefined"; const defaultWindow = typeof window !== "undefined" ? window : void 0; function getActiveElement(document2) { let activeElement = document2.activeElement; while (activeElement == null ? void 0 : activeElement.shadowRoot) { const node = activeElement.shadowRoot.activeElement; if (node === activeElement) break; else activeElement = node; } return activeElement; } function increment(source2) { set(source2, source2.v + 1); } function createSubscriber(start) { let subscribers = 0; let version = source(0); let stop; return () => { if (effect_tracking()) { get(version); render_effect(() => { if (subscribers === 0) { stop = untrack(() => start(() => increment(version))); } subscribers += 1; return () => { tick().then(() => { subscribers -= 1; if (subscribers === 0) { stop == null ? void 0 : stop(); stop = void 0; } }); }; }); } }; } class ActiveElement { constructor(options = {}) { __privateAdd(this, _document); __privateAdd(this, _subscribe); const { window: window2 = defaultWindow, document: document2 = window2 == null ? void 0 : window2.document } = options; if (window2 === void 0) return; __privateSet(this, _document, document2); __privateSet(this, _subscribe, createSubscriber((update) => { const cleanupFocusIn = on(window2, "focusin", update); const cleanupFocusOut = on(window2, "focusout", update); return () => { cleanupFocusIn(); cleanupFocusOut(); }; })); } get current() { var _a2; (_a2 = __privateGet(this, _subscribe)) == null ? void 0 : _a2.call(this); if (!__privateGet(this, _document)) return null; return getActiveElement(__privateGet(this, _document)); } } _document = new WeakMap(); _subscribe = new WeakMap(); new ActiveElement(); class Context { /** * @param name The name of the context. * This is used for generating the context key and error messages. */ constructor(name) { __privateAdd(this, _name); __privateAdd(this, _key); __privateSet(this, _name, name); __privateSet(this, _key, Symbol(name)); } /** * The key used to get and set the context. * * It is not recommended to use this value directly. * Instead, use the methods provided by this class. */ get key() { return __privateGet(this, _key); } /** * Checks whether this has been set in the context of a parent component. * * Must be called during component initialisation. */ exists() { return hasContext(__privateGet(this, _key)); } /** * Retrieves the context that belongs to the closest parent component. * * Must be called during component initialisation. * * @throws An error if the context does not exist. */ get() { const context = getContext(__privateGet(this, _key)); if (context === void 0) { throw new Error(`Context "${__privateGet(this, _name)}" not found`); } return context; } /** * Retrieves the context that belongs to the closest parent component, * or the given fallback value if the context does not exist. * * Must be called during component initialisation. */ getOr(fallback) { const context = getContext(__privateGet(this, _key)); if (context === void 0) { return fallback; } return context; } /** * Associates the given value with the current component and returns it. * * Must be called during component initialisation. */ set(context) { return setContext(__privateGet(this, _key), context); } } _name = new WeakMap(); _key = new WeakMap(); const sonnerContext = new Context(""); let toastsCounter = 0; class ToastState { constructor() { __privateAdd(this, _toasts, /* @__PURE__ */ state(proxy([]))); __privateAdd(this, _heights, /* @__PURE__ */ state(proxy([]))); __privateAdd(this, _findToastIdx, (id) => { const idx = this.toasts.findIndex((toast2) => toast2.id === id); if (idx === -1) return null; return idx; }); __publicField(this, "addToast", (data) => { if (!isBrowser) return; this.toasts.unshift(data); }); __publicField(this, "updateToast", ({ id, data, type, message }) => { const toastIdx = this.toasts.findIndex((toast2) => toast2.id === id); const toastToUpdate = this.toasts[toastIdx]; this.toasts[toastIdx] = { ...toastToUpdate, ...data, id, title: message, type, updated: true }; }); __publicField(this, "create", (data) => { var _a2; const { message, ...rest } = data; const id = typeof (data == null ? void 0 : data.id) === "number" || data.id && ((_a2 = data.id) == null ? void 0 : _a2.length) > 0 ? data.id : toastsCounter++; const dismissable = data.dismissable === void 0 ? true : data.dismissable; const type = data.type === void 0 ? "default" : data.type; const alreadyExists = this.toasts.find((toast2) => toast2.id === id); if (alreadyExists) { this.updateToast({ id, data, type, message, dismissable }); } else { this.addToast({ ...rest, id, title: message, dismissable, type }); } return id; }); __publicField(this, "dismiss", (id) => { if (id === void 0) { this.toasts = this.toasts.map((toast2) => ({ ...toast2, dismiss: true })); return; } const toastIdx = this.toasts.findIndex((toast2) => toast2.id === id); if (this.toasts[toastIdx]) { this.toasts[toastIdx] = { ...this.toasts[toastIdx], dismiss: true }; } return id; }); __publicField(this, "remove", (id) => { if (id === void 0) { this.toasts = []; return; } const toastIdx = __privateGet(this, _findToastIdx).call(this, id); if (toastIdx === null) return; this.toasts.splice(toastIdx, 1); return id; }); __publicField(this, "message", (message, data) => { return this.create({ ...data, type: "default", message }); }); __publicField(this, "error", (message, data) => { return this.create({ ...data, type: "error", message }); }); __publicField(this, "success", (message, data) => { return this.create({ ...data, type: "success", message }); }); __publicField(this, "info", (message, data) => { return this.create({ ...data, type: "info", message }); }); __publicField(this, "warning", (message, data) => { return this.create({ ...data, type: "warning", message }); }); __publicField(this, "loading", (message, data) => { return this.create({ ...data, type: "loading", message }); }); __publicField(this, "promise", (promise, data) => { if (!data) { return; } let id = void 0; if (data.loading !== void 0) { id = this.create({ ...data, promise, type: "loading", message: typeof data.loading === "string" ? data.loading : data.loading() }); } const p = promise instanceof Promise ? promise : promise(); let shouldDismiss = id !== void 0; p.then((response) => { if (typeof response === "object" && response && "ok" in response && typeof response.ok === "boolean" && !response.ok) { shouldDismiss = false; const message = constructPromiseErrorMessage(response); this.create({ id, type: "error", message }); } else if (data.success !== void 0) { shouldDismiss = false; const message = typeof data.success === "function" ? data.success(response) : data.success; this.create({ id, type: "success", message }); } }).catch((error) => { if (data.error !== void 0) { shouldDismiss = false; const message = typeof data.error === "function" ? data.error(error) : data.error; this.create({ id, type: "error", message }); } }).finally(() => { var _a2; if (shouldDismiss) { this.dismiss(id); id = void 0; } (_a2 = data.finally) == null ? void 0 : _a2.call(data); }); return id; }); __publicField(this, "custom", (component2, data) => { const id = (data == null ? void 0 : data.id) || toastsCounter++; this.create({ component: component2, id, ...data }); return id; }); __publicField(this, "removeHeight", (id) => { this.heights = this.heights.filter((height) => height.toastId !== id); }); __publicField(this, "setHeight", (data) => { const toastIdx = __privateGet(this, _findToastIdx).call(this, data.toastId); if (toastIdx === null) { this.heights.push(data); return; } this.heights[toastIdx] = data; }); __publicField(this, "reset", () => { this.toasts = []; this.heights = []; }); } get toasts() { return get(__privateGet(this, _toasts)); } set toasts(value) { set(__privateGet(this, _toasts), value, true); } get heights() { return get(__privateGet(this, _heights)); } set heights(value) { set(__privateGet(this, _heights), value, true); } } _toasts = new WeakMap(); _heights = new WeakMap(); _findToastIdx = new WeakMap(); function constructPromiseErrorMessage(response) { if (response && typeof response === "object" && "status" in response) { return `HTTP error! Status: ${response.status}`; } return `Error! ${response}`; } const toastState = new ToastState(); function toastFunction(message, data) { return toastState.create({ message, ...data }); } class SonnerState { constructor() { __privateAdd(this, _activeToasts, /* @__PURE__ */ user_derived(() => toastState.toasts.filter((toast2) => !toast2.dismiss))); } get toasts() { return get(__privateGet(this, _activeToasts)); } } _activeToasts = new WeakMap(); const basicToast = toastFunction; const toast = Object.assign(basicToast, { success: toastState.success, info: toastState.info, warning: toastState.warning, error: toastState.error, custom: toastState.custom, message: toastState.message, promise: toastState.promise, dismiss: toastState.dismiss, loading: toastState.loading, getActiveToasts: () => { return toastState.toasts.filter((toast2) => !toast2.dismiss); } }); function isAction(action) { return action.label !== void 0; } function useDocumentHidden() { let current = /* @__PURE__ */ state(proxy(typeof document !== "undefined" ? document.hidden : false)); user_effect(() => { return on(document, "visibilitychange", () => { set(current, document.hidden, true); }); }); return { get current() { return get(current); } }; } const TOAST_LIFETIME$1 = 4e3; const GAP$1 = 14; const SWIPE_THRESHOLD = 45; const TIME_BEFORE_UNMOUNT = 200; const SCALE_MULTIPLIER = 0.05; const DEFAULT_TOAST_CLASSES = { toast: "", title: "", description: "", loader: "", closeButton: "", cancelButton: "", actionButton: "", action: "", warning: "", error: "", success: "", default: "", info: "", loading: "" }; function getDefaultSwipeDirections(position) { const [y2, x] = position.split("-"); const directions = []; if (y2) { directions.push(y2); } if (x) { directions.push(x); } return directions; } function getDampening(delta) { const factor = Math.abs(delta) / 20; return 1 / (1.5 + factor); } var root_2$2 = /* @__PURE__ */ template(`
`); var on_click = (_, disabled, dismissable, deleteToast, $$props) => { var _a2, _b; if (get(disabled) || !get(dismissable)) return; deleteToast(); (_b = (_a2 = $$props.toast).onDismiss) == null ? void 0 : _b.call(_a2, $$props.toast); }; var root_4 = /* @__PURE__ */ template(``); var root_7 = /* @__PURE__ */ template(`
`); var root_24 = /* @__PURE__ */ template(`
`); var on_click_1 = (event2, $$props, dismissable, deleteToast) => { var _a2, _b; if (!isAction($$props.toast.cancel)) return; if (!get(dismissable)) return; (_b = (_a2 = $$props.toast.cancel) == null ? void 0 : _a2.onClick) == null ? void 0 : _b.call(_a2, event2); deleteToast(); }; var root_30 = /* @__PURE__ */ template(``); var on_click_2 = (event2, $$props, deleteToast) => { var _a2; if (!isAction($$props.toast.action)) return; (_a2 = $$props.toast.action) == null ? void 0 : _a2.onClick(event2); if (event2.defaultPrevented) return; deleteToast(); }; var root_34 = /* @__PURE__ */ template(``); var root_6 = /* @__PURE__ */ template(`
`, 1); var root$8 = /* @__PURE__ */ template(`
  • `); function Toast($$anchor, $$props) { push($$props, true); const LoadingIcon = ($$anchor2) => { var fragment = comment(); var node = first_child(fragment); { var consequent = ($$anchor3) => { var div = root_2$2(); var node_1 = child(div); snippet(node_1, () => $$props.loadingIcon); template_effect( ($0) => { set_class(div, 1, $0); set_attribute(div, "data-visible", get(toastType) === "loading"); }, [ () => { var _a2, _b, _c; return clsx(cn((_a2 = get(classes)) == null ? void 0 : _a2.loader, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.loader, "sonner-loader")); } ] ); append($$anchor3, div); }; var alternate = ($$anchor3) => { const expression = /* @__PURE__ */ user_derived(() => { var _a2, _b; return cn((_a2 = get(classes)) == null ? void 0 : _a2.loader, (_b = $$props.toast.classes) == null ? void 0 : _b.loader); }); const expression_1 = /* @__PURE__ */ user_derived(() => get(toastType) === "loading"); Loader($$anchor3, { get class() { return get(expression); }, get visible() { return get(expression_1); } }); }; if_block(node, ($$render) => { if ($$props.loadingIcon) $$render(consequent); else $$render(alternate, false); }); } append($$anchor2, fragment); }; let cancelButtonStyle = prop($$props, "cancelButtonStyle", 3, ""), actionButtonStyle = prop($$props, "actionButtonStyle", 3, ""), descriptionClass = prop($$props, "descriptionClass", 3, ""), unstyled = prop($$props, "unstyled", 3, false), defaultRichColors = prop($$props, "defaultRichColors", 3, false); const defaultClasses = { ...DEFAULT_TOAST_CLASSES }; let mounted = /* @__PURE__ */ state(false); let removed = /* @__PURE__ */ state(false); let swiping = /* @__PURE__ */ state(false); let swipeOut = /* @__PURE__ */ state(false); let isSwiped = /* @__PURE__ */ state(false); let offsetBeforeRemove = /* @__PURE__ */ state(0); let initialHeight = /* @__PURE__ */ state(0); let remainingTime = $$props.toast.duration || $$props.duration || TOAST_LIFETIME$1; let toastRef = /* @__PURE__ */ state(void 0); let swipeDirection = /* @__PURE__ */ state(null); let swipeOutDirection = /* @__PURE__ */ state(null); const isFront = /* @__PURE__ */ user_derived(() => $$props.index === 0); const isVisible = /* @__PURE__ */ user_derived(() => $$props.index + 1 <= $$props.visibleToasts); const toastType = /* @__PURE__ */ user_derived(() => $$props.toast.type); const dismissable = /* @__PURE__ */ user_derived(() => $$props.toast.dismissable !== false); const toastClass = /* @__PURE__ */ user_derived(() => $$props.toast.class || ""); const toastDescriptionClass = /* @__PURE__ */ user_derived(() => $$props.toast.descriptionClass || ""); const heightIndex = /* @__PURE__ */ user_derived(() => toastState.heights.findIndex((height) => height.toastId === $$props.toast.id) || 0); const closeButton = /* @__PURE__ */ user_derived(() => $$props.toast.closeButton ?? $$props.closeButton); const duration = /* @__PURE__ */ user_derived(() => $$props.toast.duration ?? $$props.duration ?? TOAST_LIFETIME$1); let pointerStart = null; const coords = /* @__PURE__ */ user_derived(() => $$props.position.split("-")); const toastsHeightBefore = /* @__PURE__ */ user_derived(() => toastState.heights.reduce( (prev, curr, reducerIndex) => { if (reducerIndex >= get(heightIndex)) return prev; return prev + curr.height; }, 0 )); const isDocumentHidden = useDocumentHidden(); const invert = /* @__PURE__ */ user_derived(() => $$props.toast.invert || $$props.invert); const disabled = /* @__PURE__ */ user_derived(() => get(toastType) === "loading"); const classes = /* @__PURE__ */ user_derived(() => ({ ...defaultClasses, ...$$props.classes })); const toastTitle = /* @__PURE__ */ user_derived(() => $$props.toast.title); const toastDescription = /* @__PURE__ */ user_derived(() => $$props.toast.description); let closeTimerStartTime = /* @__PURE__ */ state(0); let lastCloseTimerStartTime = /* @__PURE__ */ state(0); const offset = /* @__PURE__ */ user_derived(() => Math.round(get(heightIndex) * GAP$1 + get(toastsHeightBefore))); user_effect(() => { get(toastTitle); get(toastDescription); let scale; if ($$props.expanded || $$props.expandByDefault) { scale = 1; } else { scale = 1 - $$props.index * SCALE_MULTIPLIER; } const toastEl = untrack(() => get(toastRef)); if (toastEl === void 0) return; toastEl.style.setProperty("height", "auto"); const offsetHeight = toastEl.offsetHeight; const rectHeight = toastEl.getBoundingClientRect().height; const scaledRectHeight = Math.round(rectHeight / scale + Number.EPSILON & 100) / 100; toastEl.style.removeProperty("height"); let finalHeight; if (Math.abs(scaledRectHeight - offsetHeight) < 1) { finalHeight = scaledRectHeight; } else { finalHeight = offsetHeight; } set(initialHeight, finalHeight, true); toastState.setHeight({ toastId: $$props.toast.id, height: finalHeight }); }); function deleteToast() { set(removed, true); set(offsetBeforeRemove, get(offset), true); toastState.removeHeight($$props.toast.id); setTimeout( () => { toastState.remove($$props.toast.id); }, TIME_BEFORE_UNMOUNT ); } let timeoutId; const isPromiseLoadingOrInfiniteDuration = /* @__PURE__ */ user_derived(() => $$props.toast.promise && get(toastType) === "loading" || $$props.toast.duration === Number.POSITIVE_INFINITY); function startTimer() { set(closeTimerStartTime, (/* @__PURE__ */ new Date()).getTime(), true); timeoutId = setTimeout( () => { var _a2, _b; (_b = (_a2 = $$props.toast).onAutoClose) == null ? void 0 : _b.call(_a2, $$props.toast); deleteToast(); }, remainingTime ); } function pauseTimer() { if (get(lastCloseTimerStartTime) < get(closeTimerStartTime)) { const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - get(closeTimerStartTime); remainingTime = remainingTime - elapsedTime; } set(lastCloseTimerStartTime, (/* @__PURE__ */ new Date()).getTime(), true); } user_effect(() => { if ($$props.toast.updated) { clearTimeout(timeoutId); remainingTime = get(duration); startTimer(); } }); user_effect(() => { if (!get(isPromiseLoadingOrInfiniteDuration)) { if ($$props.expanded || $$props.interacting || isDocumentHidden.current) { pauseTimer(); } else { startTimer(); } } return () => clearTimeout(timeoutId); }); onMount(() => { var _a2; set(mounted, true); const height = (_a2 = get(toastRef)) == null ? void 0 : _a2.getBoundingClientRect().height; set(initialHeight, height, true); toastState.setHeight({ toastId: $$props.toast.id, height }); return () => { toastState.removeHeight($$props.toast.id); }; }); user_effect(() => { if ($$props.toast.delete) { deleteToast(); } }); const handlePointerDown = (event2) => { if (get(disabled)) return; set(offsetBeforeRemove, get(offset), true); const target = event2.target; target.setPointerCapture(event2.pointerId); if (target.tagName === "BUTTON") return; set(swiping, true); pointerStart = { x: event2.clientX, y: event2.clientY }; }; const handlePointerUp = () => { var _a2, _b, _c, _d, _e, _f; if (get(swipeOut) || !get(dismissable)) return; pointerStart = null; const swipeAmountX = Number(((_a2 = get(toastRef)) == null ? void 0 : _a2.style.getPropertyValue("--swipe-amount-x").replace("px", "")) || 0); const swipeAmountY = Number(((_b = get(toastRef)) == null ? void 0 : _b.style.getPropertyValue("--swipe-amount-y").replace("px", "")) || 0); const timeTaken = (/* @__PURE__ */ new Date()).getTime() - 0; const swipeAmount = get(swipeDirection) === "x" ? swipeAmountX : swipeAmountY; const velocity = Math.abs(swipeAmount) / timeTaken; if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) { set(offsetBeforeRemove, get(offset), true); (_d = (_c = $$props.toast).onDismiss) == null ? void 0 : _d.call(_c, $$props.toast); if (get(swipeDirection) === "x") { set(swipeOutDirection, swipeAmountX > 0 ? "right" : "left", true); } else { set(swipeOutDirection, swipeAmountY > 0 ? "down" : "up", true); } deleteToast(); set(swipeOut, true); return; } else { (_e = get(toastRef)) == null ? void 0 : _e.style.setProperty("--swipe-amount-x", "0px"); (_f = get(toastRef)) == null ? void 0 : _f.style.setProperty("--swipe-amount-y", "0px"); } set(isSwiped, false); set(swiping, false); set(swipeDirection, null); }; const handlePointerMove = (event2) => { var _a2, _b, _c; if (!pointerStart || !get(dismissable)) return; const isHighlighted = (((_a2 = window.getSelection()) == null ? void 0 : _a2.toString().length) ?? -1) > 0; if (isHighlighted) return; const yDelta = event2.clientY - pointerStart.y; const xDelta = event2.clientX - pointerStart.x; const swipeDirections = $$props.swipeDirections ?? getDefaultSwipeDirections($$props.position); if (!get(swipeDirection) && (Math.abs(xDelta) > 1 || Math.abs(yDelta) > 1)) { set(swipeDirection, Math.abs(xDelta) > Math.abs(yDelta) ? "x" : "y", true); } let swipeAmount = { x: 0, y: 0 }; if (get(swipeDirection) === "y") { if (swipeDirections.includes("top") || swipeDirections.includes("bottom")) { if (swipeDirections.includes("top") && yDelta < 0 || swipeDirections.includes("bottom") && yDelta > 0) { swipeAmount.y = yDelta; } else { const dampenedDelta = yDelta * getDampening(yDelta); swipeAmount.y = Math.abs(dampenedDelta) < Math.abs(yDelta) ? dampenedDelta : yDelta; } } } else if (get(swipeDirection) === "x") { if (swipeDirections.includes("left") || swipeDirections.includes("right")) { if (swipeDirections.includes("left") && xDelta < 0 || swipeDirections.includes("right") && xDelta > 0) { swipeAmount.x = xDelta; } else { const dampenedDelta = xDelta * getDampening(xDelta); swipeAmount.x = Math.abs(dampenedDelta) < Math.abs(xDelta) ? dampenedDelta : xDelta; } } } if (Math.abs(swipeAmount.x) > 0 || Math.abs(swipeAmount.y) > 0) { set(isSwiped, true); } (_b = get(toastRef)) == null ? void 0 : _b.style.setProperty("--swipe-amount-x", `${swipeAmount.x}px`); (_c = get(toastRef)) == null ? void 0 : _c.style.setProperty("--swipe-amount-y", `${swipeAmount.y}px`); }; const handleDragEnd = () => { set(swiping, false); set(swipeDirection, null); pointerStart = null; }; const icon = /* @__PURE__ */ user_derived(() => { if ($$props.toast.icon) return $$props.toast.icon; if (get(toastType) === "success") return $$props.successIcon; if (get(toastType) === "error") return $$props.errorIcon; if (get(toastType) === "warning") return $$props.warningIcon; if (get(toastType) === "info") return $$props.infoIcon; if (get(toastType) === "loading") return $$props.loadingIcon; return null; }); var li = root$8(); set_attribute(li, "tabindex", 0); let styles; li.__pointermove = handlePointerMove; li.__pointerup = handlePointerUp; li.__pointerdown = handlePointerDown; var node_2 = child(li); { var consequent_1 = ($$anchor2) => { var button = root_4(); button.__click = [ on_click, disabled, dismissable, deleteToast, $$props ]; var node_3 = child(button); snippet(node_3, () => $$props.closeIcon ?? noop); template_effect( ($0) => { set_attribute(button, "aria-label", $$props.closeButtonAriaLabel); set_attribute(button, "data-disabled", get(disabled)); set_class(button, 1, $0); }, [ () => { var _a2, _b, _c; return clsx(cn((_a2 = get(classes)) == null ? void 0 : _a2.closeButton, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.closeButton)); } ] ); append($$anchor2, button); }; if_block(node_2, ($$render) => { if (get(closeButton) && !$$props.toast.component && get(toastType) !== "loading" && $$props.closeIcon !== null) $$render(consequent_1); }); } var node_4 = sibling(node_2, 2); { var consequent_2 = ($$anchor2) => { var fragment_2 = comment(); const Component = /* @__PURE__ */ user_derived(() => $$props.toast.component); var node_5 = first_child(fragment_2); component(node_5, () => get(Component), ($$anchor3, $$component) => { $$component($$anchor3, spread_props(() => $$props.toast.componentProps, { closeToast: deleteToast })); }); append($$anchor2, fragment_2); }; var alternate_1 = ($$anchor2) => { var fragment_3 = root_6(); var node_6 = first_child(fragment_3); { var consequent_11 = ($$anchor3) => { var div_1 = root_7(); var node_7 = child(div_1); { var consequent_4 = ($$anchor4) => { var fragment_4 = comment(); var node_8 = first_child(fragment_4); { var consequent_3 = ($$anchor5) => { var fragment_5 = comment(); var node_9 = first_child(fragment_5); component(node_9, () => $$props.toast.icon, ($$anchor6, $$component) => { $$component($$anchor6, {}); }); append($$anchor5, fragment_5); }; var alternate_2 = ($$anchor5) => { LoadingIcon($$anchor5); }; if_block(node_8, ($$render) => { if ($$props.toast.icon) $$render(consequent_3); else $$render(alternate_2, false); }); } append($$anchor4, fragment_4); }; if_block(node_7, ($$render) => { if ($$props.toast.promise || get(toastType) === "loading") $$render(consequent_4); }); } var node_10 = sibling(node_7, 2); { var consequent_10 = ($$anchor4) => { var fragment_7 = comment(); var node_11 = first_child(fragment_7); { var consequent_5 = ($$anchor5) => { var fragment_8 = comment(); var node_12 = first_child(fragment_8); component(node_12, () => $$props.toast.icon, ($$anchor6, $$component) => { $$component($$anchor6, {}); }); append($$anchor5, fragment_8); }; var alternate_3 = ($$anchor5, $$elseif) => { { var consequent_6 = ($$anchor6) => { var fragment_9 = comment(); var node_13 = first_child(fragment_9); snippet(node_13, () => $$props.successIcon ?? noop); append($$anchor6, fragment_9); }; var alternate_4 = ($$anchor6, $$elseif2) => { { var consequent_7 = ($$anchor7) => { var fragment_10 = comment(); var node_14 = first_child(fragment_10); snippet(node_14, () => $$props.errorIcon ?? noop); append($$anchor7, fragment_10); }; var alternate_5 = ($$anchor7, $$elseif3) => { { var consequent_8 = ($$anchor8) => { var fragment_11 = comment(); var node_15 = first_child(fragment_11); snippet(node_15, () => $$props.warningIcon ?? noop); append($$anchor8, fragment_11); }; var alternate_6 = ($$anchor8, $$elseif4) => { { var consequent_9 = ($$anchor9) => { var fragment_12 = comment(); var node_16 = first_child(fragment_12); snippet(node_16, () => $$props.infoIcon ?? noop); append($$anchor9, fragment_12); }; if_block( $$anchor8, ($$render) => { if (get(toastType) === "info") $$render(consequent_9); }, $$elseif4 ); } }; if_block( $$anchor7, ($$render) => { if (get(toastType) === "warning") $$render(consequent_8); else $$render(alternate_6, false); }, $$elseif3 ); } }; if_block( $$anchor6, ($$render) => { if (get(toastType) === "error") $$render(consequent_7); else $$render(alternate_5, false); }, $$elseif2 ); } }; if_block( $$anchor5, ($$render) => { if (get(toastType) === "success") $$render(consequent_6); else $$render(alternate_4, false); }, $$elseif ); } }; if_block(node_11, ($$render) => { if ($$props.toast.icon) $$render(consequent_5); else $$render(alternate_3, false); }); } append($$anchor4, fragment_7); }; if_block(node_10, ($$render) => { if ($$props.toast.type !== "loading") $$render(consequent_10); }); } template_effect(($0) => set_class(div_1, 1, $0), [ () => { var _a2, _b, _c; return clsx(cn((_a2 = get(classes)) == null ? void 0 : _a2.icon, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.icon)); } ]); append($$anchor3, div_1); }; if_block(node_6, ($$render) => { if ((get(toastType) || $$props.toast.icon || $$props.toast.promise) && $$props.toast.icon !== null && (get(icon) !== null || $$props.toast.icon)) $$render(consequent_11); }); } var div_2 = sibling(node_6, 2); var div_3 = child(div_2); var node_17 = child(div_3); { var consequent_13 = ($$anchor3) => { var fragment_13 = comment(); var node_18 = first_child(fragment_13); { var consequent_12 = ($$anchor4) => { var fragment_14 = comment(); const Title = /* @__PURE__ */ user_derived(() => $$props.toast.title); var node_19 = first_child(fragment_14); component(node_19, () => get(Title), ($$anchor5, $$component) => { $$component($$anchor5, spread_props(() => $$props.toast.componentProps)); }); append($$anchor4, fragment_14); }; var alternate_7 = ($$anchor4) => { var text$1 = text(); template_effect(() => set_text(text$1, $$props.toast.title)); append($$anchor4, text$1); }; if_block(node_18, ($$render) => { if (typeof $$props.toast.title !== "string") $$render(consequent_12); else $$render(alternate_7, false); }); } append($$anchor3, fragment_13); }; if_block(node_17, ($$render) => { if ($$props.toast.title) $$render(consequent_13); }); } var node_20 = sibling(div_3, 2); { var consequent_15 = ($$anchor3) => { var div_4 = root_24(); var node_21 = child(div_4); { var consequent_14 = ($$anchor4) => { var fragment_16 = comment(); const Description = /* @__PURE__ */ user_derived(() => $$props.toast.description); var node_22 = first_child(fragment_16); component(node_22, () => get(Description), ($$anchor5, $$component) => { $$component($$anchor5, spread_props(() => $$props.toast.componentProps)); }); append($$anchor4, fragment_16); }; var alternate_8 = ($$anchor4) => { var text_1 = text(); template_effect(() => set_text(text_1, $$props.toast.description)); append($$anchor4, text_1); }; if_block(node_21, ($$render) => { if (typeof $$props.toast.description !== "string") $$render(consequent_14); else $$render(alternate_8, false); }); } template_effect(($0) => set_class(div_4, 1, $0), [ () => { var _a2, _b; return clsx(cn(descriptionClass(), get(toastDescriptionClass), (_a2 = get(classes)) == null ? void 0 : _a2.description, (_b = $$props.toast.classes) == null ? void 0 : _b.description)); } ]); append($$anchor3, div_4); }; if_block(node_20, ($$render) => { if ($$props.toast.description) $$render(consequent_15); }); } var node_23 = sibling(div_2, 2); { var consequent_18 = ($$anchor3) => { var fragment_18 = comment(); var node_24 = first_child(fragment_18); { var consequent_16 = ($$anchor4) => { var fragment_19 = comment(); var node_25 = first_child(fragment_19); component(node_25, () => $$props.toast.cancel, ($$anchor5, $$component) => { $$component($$anchor5, {}); }); append($$anchor4, fragment_19); }; var alternate_9 = ($$anchor4, $$elseif) => { { var consequent_17 = ($$anchor5) => { var button_1 = root_30(); button_1.__click = [ on_click_1, $$props, dismissable, deleteToast ]; var text_2 = child(button_1); template_effect( ($0) => { set_style(button_1, $$props.toast.cancelButtonStyle ?? cancelButtonStyle()); set_class(button_1, 1, $0); set_text(text_2, $$props.toast.cancel.label); }, [ () => { var _a2, _b, _c; return clsx(cn((_a2 = get(classes)) == null ? void 0 : _a2.cancelButton, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.cancelButton)); } ] ); append($$anchor5, button_1); }; if_block( $$anchor4, ($$render) => { if (isAction($$props.toast.cancel)) $$render(consequent_17); }, $$elseif ); } }; if_block(node_24, ($$render) => { if (typeof $$props.toast.cancel === "function") $$render(consequent_16); else $$render(alternate_9, false); }); } append($$anchor3, fragment_18); }; if_block(node_23, ($$render) => { if ($$props.toast.cancel) $$render(consequent_18); }); } var node_26 = sibling(node_23, 2); { var consequent_21 = ($$anchor3) => { var fragment_20 = comment(); var node_27 = first_child(fragment_20); { var consequent_19 = ($$anchor4) => { var fragment_21 = comment(); var node_28 = first_child(fragment_21); component(node_28, () => $$props.toast.action, ($$anchor5, $$component) => { $$component($$anchor5, {}); }); append($$anchor4, fragment_21); }; var alternate_10 = ($$anchor4, $$elseif) => { { var consequent_20 = ($$anchor5) => { var button_2 = root_34(); button_2.__click = [on_click_2, $$props, deleteToast]; var text_3 = child(button_2); template_effect( ($0) => { set_style(button_2, $$props.toast.actionButtonStyle ?? actionButtonStyle()); set_class(button_2, 1, $0); set_text(text_3, $$props.toast.action.label); }, [ () => { var _a2, _b, _c; return clsx(cn((_a2 = get(classes)) == null ? void 0 : _a2.actionButton, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.actionButton)); } ] ); append($$anchor5, button_2); }; if_block( $$anchor4, ($$render) => { if (isAction($$props.toast.action)) $$render(consequent_20); }, $$elseif ); } }; if_block(node_27, ($$render) => { if (typeof $$props.toast.action === "function") $$render(consequent_19); else $$render(alternate_10, false); }); } append($$anchor3, fragment_20); }; if_block(node_26, ($$render) => { if ($$props.toast.action) $$render(consequent_21); }); } template_effect(($0) => set_class(div_3, 1, $0), [ () => { var _a2, _b, _c; return clsx(cn((_a2 = get(classes)) == null ? void 0 : _a2.title, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.title)); } ]); append($$anchor2, fragment_3); }; if_block(node_4, ($$render) => { if ($$props.toast.component) $$render(consequent_2); else $$render(alternate_1, false); }); } bind_this(li, ($$value) => set(toastRef, $$value), () => get(toastRef)); template_effect( ($0, $1, $2) => { set_class(li, 1, $0); set_attribute(li, "data-rich-colors", $$props.toast.richColors ?? defaultRichColors()); set_attribute(li, "data-styled", !($$props.toast.component || $$props.toast.unstyled || unstyled())); set_attribute(li, "data-mounted", get(mounted)); set_attribute(li, "data-promise", $1); set_attribute(li, "data-swiped", get(isSwiped)); set_attribute(li, "data-removed", get(removed)); set_attribute(li, "data-visible", get(isVisible)); set_attribute(li, "data-y-position", get(coords)[0]); set_attribute(li, "data-x-position", get(coords)[1]); set_attribute(li, "data-index", $$props.index); set_attribute(li, "data-front", get(isFront)); set_attribute(li, "data-swiping", get(swiping)); set_attribute(li, "data-dismissable", get(dismissable)); set_attribute(li, "data-type", get(toastType)); set_attribute(li, "data-invert", get(invert)); set_attribute(li, "data-swipe-out", get(swipeOut)); set_attribute(li, "data-swipe-direction", get(swipeOutDirection)); set_attribute(li, "data-expanded", $2); styles = set_style(li, `${$$props.style} ${$$props.toast.style}`, styles, { "--index": $$props.index, "--toasts-before": $$props.index, "--z-index": toastState.toasts.length - $$props.index, "--offset": `${get(removed) ? get(offsetBeforeRemove) : get(offset)}px`, "--initial-height": $$props.expandByDefault ? "auto" : `${get(initialHeight)}px` }); }, [ () => { var _a2, _b, _c, _d, _e, _f; return clsx(cn($$props.class, get(toastClass), (_a2 = get(classes)) == null ? void 0 : _a2.toast, (_c = (_b = $$props.toast) == null ? void 0 : _b.classes) == null ? void 0 : _c.toast, (_d = get(classes)) == null ? void 0 : _d[get(toastType)], (_f = (_e = $$props.toast) == null ? void 0 : _e.classes) == null ? void 0 : _f[get(toastType)])); }, () => Boolean($$props.toast.promise), () => Boolean($$props.expanded || $$props.expandByDefault && get(mounted)) ] ); event("dragend", li, handleDragEnd); append($$anchor, li); pop(); } delegate([ "pointermove", "pointerup", "pointerdown", "click" ]); var root$7 = /* @__PURE__ */ ns_template(``); function SuccessIcon($$anchor) { var svg = root$7(); append($$anchor, svg); } var root$6 = /* @__PURE__ */ ns_template(``); function ErrorIcon($$anchor) { var svg = root$6(); append($$anchor, svg); } var root$5 = /* @__PURE__ */ ns_template(``); function WarningIcon($$anchor) { var svg = root$5(); append($$anchor, svg); } var root$4 = /* @__PURE__ */ ns_template(``); function InfoIcon($$anchor) { var svg = root$4(); append($$anchor, svg); } var root$3 = /* @__PURE__ */ ns_template(``); function CloseIcon($$anchor) { var svg = root$3(); append($$anchor, svg); } const VISIBLE_TOASTS_AMOUNT = 3; const VIEWPORT_OFFSET = "24px"; const MOBILE_VIEWPORT_OFFSET = "16px"; const TOAST_LIFETIME = 4e3; const TOAST_WIDTH = 356; const GAP = 14; const DARK = "dark"; const LIGHT = "light"; function getOffsetObject(defaultOffset, mobileOffset) { const styles = {}; [defaultOffset, mobileOffset].forEach((offset, index) => { const isMobile = index === 1; const prefix = isMobile ? "--mobile-offset" : "--offset"; const defaultValue = isMobile ? MOBILE_VIEWPORT_OFFSET : VIEWPORT_OFFSET; function assignAll(offset2) { ["top", "right", "bottom", "left"].forEach((key) => { styles[`${prefix}-${key}`] = typeof offset2 === "number" ? `${offset2}px` : offset2; }); } if (typeof offset === "number" || typeof offset === "string") { assignAll(offset); } else if (typeof offset === "object") { ["top", "right", "bottom", "left"].forEach((key) => { const value = offset[key]; if (value === void 0) { styles[`${prefix}-${key}`] = defaultValue; } else { styles[`${prefix}-${key}`] = typeof value === "number" ? `${value}px` : value; } }); } else { assignAll(defaultValue); } }); return styles; } var root_2$1 = /* @__PURE__ */ template(`
      `); var root$2 = /* @__PURE__ */ template(`
      `); function Toaster($$anchor, $$props) { push($$props, true); function getInitialTheme(t) { if (t !== "system") return t; if (typeof window !== "undefined") { if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) { return DARK; } return LIGHT; } return LIGHT; } function getDocumentDirection() { if (typeof window === "undefined") return "ltr"; if (typeof document === "undefined") return "ltr"; const dirAttribute = document.documentElement.getAttribute("dir"); if (dirAttribute === "auto" || !dirAttribute) { return window.getComputedStyle(document.documentElement).direction; } return dirAttribute; } let invert = prop($$props, "invert", 3, false), position = prop($$props, "position", 3, "bottom-right"), hotkey = prop($$props, "hotkey", 19, () => ["altKey", "KeyT"]), expand = prop($$props, "expand", 3, false), closeButton = prop($$props, "closeButton", 3, false), offset = prop($$props, "offset", 3, VIEWPORT_OFFSET), mobileOffset = prop($$props, "mobileOffset", 3, MOBILE_VIEWPORT_OFFSET), theme = prop($$props, "theme", 3, "light"), richColors = prop($$props, "richColors", 3, false), duration = prop($$props, "duration", 3, TOAST_LIFETIME), visibleToasts = prop($$props, "visibleToasts", 3, VISIBLE_TOASTS_AMOUNT), toastOptions = prop($$props, "toastOptions", 19, () => ({})), dir = prop($$props, "dir", 19, getDocumentDirection), gap = prop($$props, "gap", 3, GAP), containerAriaLabel = prop($$props, "containerAriaLabel", 3, "Notifications"), closeButtonAriaLabel = prop($$props, "closeButtonAriaLabel", 3, "Close toast"), restProps = /* @__PURE__ */ rest_props($$props, [ "$$slots", "$$events", "$$legacy", "invert", "position", "hotkey", "expand", "closeButton", "offset", "mobileOffset", "theme", "richColors", "duration", "visibleToasts", "toastOptions", "dir", "gap", "loadingIcon", "successIcon", "errorIcon", "warningIcon", "closeIcon", "infoIcon", "containerAriaLabel", "class", "closeButtonAriaLabel" ]); const possiblePositions = /* @__PURE__ */ user_derived(() => Array.from(new Set([ position(), ...toastState.toasts.filter((toast2) => toast2.position).map((toast2) => toast2.position) ].filter(Boolean)))); let expanded = /* @__PURE__ */ state(false); let interacting = /* @__PURE__ */ state(false); let actualTheme = /* @__PURE__ */ state(proxy(getInitialTheme(theme()))); let listRef = /* @__PURE__ */ state(void 0); let lastFocusedElementRef = /* @__PURE__ */ state(null); let isFocusWithin = /* @__PURE__ */ state(false); const hotkeyLabel = /* @__PURE__ */ user_derived(() => hotkey().join("+").replace(/Key/g, "").replace(/Digit/g, "")); user_effect(() => { if (toastState.toasts.length <= 1) { set(expanded, false); } }); user_effect(() => { const toastsToDismiss = toastState.toasts.filter((toast2) => toast2.dismiss && !toast2.delete); if (toastsToDismiss.length > 0) { const updatedToasts = toastState.toasts.map((toast2) => { const matchingToast = toastsToDismiss.find((dismissToast) => dismissToast.id === toast2.id); if (matchingToast) { return { ...toast2, delete: true }; } return toast2; }); toastState.toasts = updatedToasts; } }); user_effect(() => { return () => { if (get(listRef) && get(lastFocusedElementRef)) { get(lastFocusedElementRef).focus({ preventScroll: true }); set(lastFocusedElementRef, null); set(isFocusWithin, false); } }; }); onMount(() => { toastState.reset(); const handleKeydown = (event2) => { var _a2, _b; const isHotkeyPressed = hotkey().every((key) => ( // eslint-disable-next-line @typescript-eslint/no-explicit-any event2[key] || event2.code === key )); if (isHotkeyPressed) { set(expanded, true); (_a2 = get(listRef)) == null ? void 0 : _a2.focus(); } if (event2.code === "Escape" && (document.activeElement === get(listRef) || ((_b = get(listRef)) == null ? void 0 : _b.contains(document.activeElement)))) { set(expanded, false); } }; document.addEventListener("keydown", handleKeydown); return () => { document.removeEventListener("keydown", handleKeydown); }; }); user_effect(() => { if (theme() !== "system") { set(actualTheme, theme()); } if (typeof window !== "undefined") { if (theme() === "system") { if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) { set(actualTheme, DARK); } else { set(actualTheme, LIGHT); } } const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)"); const changeHandler = ({ matches }) => { set(actualTheme, matches ? DARK : LIGHT, true); }; if ("addEventListener" in mediaQueryList) { mediaQueryList.addEventListener("change", changeHandler); } else { mediaQueryList.addListener(changeHandler); } } }); const handleBlur = (event2) => { if (get(isFocusWithin) && !event2.currentTarget.contains(event2.relatedTarget)) { set(isFocusWithin, false); if (get(lastFocusedElementRef)) { get(lastFocusedElementRef).focus({ preventScroll: true }); set(lastFocusedElementRef, null); } } }; const handleFocus = (event2) => { const isNotDismissable = event2.target instanceof HTMLElement && event2.target.dataset.dismissable === "false"; if (isNotDismissable) return; if (!get(isFocusWithin)) { set(isFocusWithin, true); set(lastFocusedElementRef, event2.relatedTarget, true); } }; const handlePointerDown = (event2) => { const isNotDismissable = event2.target instanceof HTMLElement && event2.target.dataset.dismissable === "false"; if (isNotDismissable) return; set(interacting, true); }; const handleMouseEnter = () => { set(expanded, true); }; const handleMouseLeave = () => { if (!get(interacting)) { set(expanded, false); } }; const handleMouseMove = () => { set(expanded, true); }; const handleDragEnd = () => { set(expanded, false); }; const handlePointerUp = () => { set(interacting, false); }; sonnerContext.set(new SonnerState()); var section = root$2(); set_attribute(section, "tabindex", -1); var node = child(section); { var consequent_10 = ($$anchor2) => { var fragment = comment(); var node_1 = first_child(fragment); each(node_1, 18, () => get(possiblePositions), (position2) => position2, ($$anchor3, position2, index, $$array) => { var ol = root_2$1(); const computed_const = /* @__PURE__ */ user_derived(() => { const [y2, x] = position2.split("-"); return { y: y2, x }; }); const isLifted = /* @__PURE__ */ user_derived(() => get(expanded) && toastState.toasts.length > 1 && !expand()); const offsetObject = /* @__PURE__ */ user_derived(() => getOffsetObject(offset(), mobileOffset())); let attributes; each(ol, 23, () => toastState.toasts.filter((toast2) => !toast2.position && get(index) === 0 || toast2.position === position2), (toast2) => toast2.id, ($$anchor4, toast2, index2, $$array_1) => { const expression = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.duration) ?? duration(); }); const expression_1 = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.class) ?? ""; }); const expression_2 = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.descriptionClass) || ""; }); const expression_3 = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.style) ?? ""; }); const expression_4 = /* @__PURE__ */ user_derived(() => toastOptions().classes || {}); const expression_5 = /* @__PURE__ */ user_derived(() => toastOptions().unstyled ?? false); const expression_6 = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.cancelButtonStyle) ?? ""; }); const expression_7 = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.actionButtonStyle) ?? ""; }); const expression_8 = /* @__PURE__ */ user_derived(() => { var _a2; return ((_a2 = toastOptions()) == null ? void 0 : _a2.closeButtonAriaLabel) ?? closeButtonAriaLabel(); }); { const successIcon = ($$anchor5) => { var fragment_2 = comment(); var node_2 = first_child(fragment_2); { var consequent = ($$anchor6) => { var fragment_3 = comment(); var node_3 = first_child(fragment_3); snippet(node_3, () => $$props.successIcon ?? noop); append($$anchor6, fragment_3); }; var alternate = ($$anchor6, $$elseif) => { { var consequent_1 = ($$anchor7) => { SuccessIcon($$anchor7); }; if_block( $$anchor6, ($$render) => { if ($$props.successIcon !== null) $$render(consequent_1); }, $$elseif ); } }; if_block(node_2, ($$render) => { if ($$props.successIcon) $$render(consequent); else $$render(alternate, false); }); } append($$anchor5, fragment_2); }; const errorIcon = ($$anchor5) => { var fragment_5 = comment(); var node_4 = first_child(fragment_5); { var consequent_2 = ($$anchor6) => { var fragment_6 = comment(); var node_5 = first_child(fragment_6); snippet(node_5, () => $$props.errorIcon ?? noop); append($$anchor6, fragment_6); }; var alternate_1 = ($$anchor6, $$elseif) => { { var consequent_3 = ($$anchor7) => { ErrorIcon($$anchor7); }; if_block( $$anchor6, ($$render) => { if ($$props.errorIcon !== null) $$render(consequent_3); }, $$elseif ); } }; if_block(node_4, ($$render) => { if ($$props.errorIcon) $$render(consequent_2); else $$render(alternate_1, false); }); } append($$anchor5, fragment_5); }; const warningIcon = ($$anchor5) => { var fragment_8 = comment(); var node_6 = first_child(fragment_8); { var consequent_4 = ($$anchor6) => { var fragment_9 = comment(); var node_7 = first_child(fragment_9); snippet(node_7, () => $$props.warningIcon ?? noop); append($$anchor6, fragment_9); }; var alternate_2 = ($$anchor6, $$elseif) => { { var consequent_5 = ($$anchor7) => { WarningIcon($$anchor7); }; if_block( $$anchor6, ($$render) => { if ($$props.warningIcon !== null) $$render(consequent_5); }, $$elseif ); } }; if_block(node_6, ($$render) => { if ($$props.warningIcon) $$render(consequent_4); else $$render(alternate_2, false); }); } append($$anchor5, fragment_8); }; const infoIcon = ($$anchor5) => { var fragment_11 = comment(); var node_8 = first_child(fragment_11); { var consequent_6 = ($$anchor6) => { var fragment_12 = comment(); var node_9 = first_child(fragment_12); snippet(node_9, () => $$props.infoIcon ?? noop); append($$anchor6, fragment_12); }; var alternate_3 = ($$anchor6, $$elseif) => { { var consequent_7 = ($$anchor7) => { InfoIcon($$anchor7); }; if_block( $$anchor6, ($$render) => { if ($$props.infoIcon !== null) $$render(consequent_7); }, $$elseif ); } }; if_block(node_8, ($$render) => { if ($$props.infoIcon) $$render(consequent_6); else $$render(alternate_3, false); }); } append($$anchor5, fragment_11); }; const closeIcon = ($$anchor5) => { var fragment_14 = comment(); var node_10 = first_child(fragment_14); { var consequent_8 = ($$anchor6) => { var fragment_15 = comment(); var node_11 = first_child(fragment_15); snippet(node_11, () => $$props.closeIcon ?? noop); append($$anchor6, fragment_15); }; var alternate_4 = ($$anchor6, $$elseif) => { { var consequent_9 = ($$anchor7) => { CloseIcon($$anchor7); }; if_block( $$anchor6, ($$render) => { if ($$props.closeIcon !== null) $$render(consequent_9); }, $$elseif ); } }; if_block(node_10, ($$render) => { if ($$props.closeIcon) $$render(consequent_8); else $$render(alternate_4, false); }); } append($$anchor5, fragment_14); }; Toast($$anchor4, { get index() { return get(index2); }, get toast() { return get(toast2); }, get defaultRichColors() { return richColors(); }, get duration() { return get(expression); }, get class() { return get(expression_1); }, get descriptionClass() { return get(expression_2); }, get invert() { return invert(); }, get visibleToasts() { return visibleToasts(); }, get closeButton() { return closeButton(); }, get interacting() { return get(interacting); }, get position() { return position2; }, get style() { return get(expression_3); }, get classes() { return get(expression_4); }, get unstyled() { return get(expression_5); }, get cancelButtonStyle() { return get(expression_6); }, get actionButtonStyle() { return get(expression_7); }, get closeButtonAriaLabel() { return get(expression_8); }, get expandByDefault() { return expand(); }, get expanded() { return get(expanded); }, get loadingIcon() { return $$props.loadingIcon; }, successIcon, errorIcon, warningIcon, infoIcon, closeIcon, $$slots: { successIcon: true, errorIcon: true, warningIcon: true, infoIcon: true, closeIcon: true } }); } }); bind_this(ol, ($$value) => set(listRef, $$value), () => get(listRef)); template_effect( ($0) => { var _a2; attributes = set_attributes( ol, attributes, { tabindex: -1, dir: $0, class: $$props.class, "data-sonner-toaster": true, "data-sonner-theme": get(actualTheme), "data-y-position": get(computed_const).y, "data-lifted": get(isLifted), "data-x-position": get(computed_const).x, style: $$props.style, onblur: handleBlur, onfocus: handleFocus, onmouseenter: handleMouseEnter, onmousemove: handleMouseMove, onmouseleave: handleMouseLeave, ondragend: handleDragEnd, onpointerdown: handlePointerDown, onpointerup: handlePointerUp, ...restProps, [STYLE]: { "--front-toast-height": `${(_a2 = toastState.heights[0]) == null ? void 0 : _a2.height}px`, "--width": `${TOAST_WIDTH}px`, "--gap": `${gap()}px`, "--offset-top": get(offsetObject)["--offset-top"], "--offset-right": get(offsetObject)["--offset-right"], "--offset-bottom": get(offsetObject)["--offset-bottom"], "--offset-left": get(offsetObject)["--offset-left"], "--mobile-offset-top": get(offsetObject)["--mobile-offset-top"], "--mobile-offset-right": get(offsetObject)["--mobile-offset-right"], "--mobile-offset-bottom": get(offsetObject)["--mobile-offset-bottom"], "--mobile-offset-left": get(offsetObject)["--mobile-offset-left"] } }, "svelte-xsmi9t" ); ol.dir = ol.dir; }, [ () => dir() === "auto" ? getDocumentDirection() : dir() ] ); append($$anchor3, ol); }); append($$anchor2, fragment); }; if_block(node, ($$render) => { if (toastState.toasts.length > 0) $$render(consequent_10); }); } template_effect(() => set_attribute(section, "aria-label", `${containerAriaLabel() ?? ""} ${get(hotkeyLabel) ?? ""}`)); append($$anchor, section); pop(); } const CONFIG = { APP_NAME: "LeetCode Toolkit", EDITORIAL_READER_URL: "https://leetcode-editorial-reader.vercel.app" }; const messageToastTypes = [ "success", "info", "warning", "error", "message", "loading" ]; function addPrefix(message) { if (typeof message === "string") { return `${CONFIG.APP_NAME}: ${message}`; } return message; } const prefixToast = new Proxy(toast, { // Handle direct function calls: toast('message') apply(target, thisArg, args) { if (args.length > 0) { args[0] = addPrefix(args[0]); } return Reflect.apply(target, thisArg, args); }, get(target, prop2, receiver) { const originalProp = Reflect.get(target, prop2, receiver); if (typeof originalProp === "function" && messageToastTypes.includes(prop2.toString())) { return (...args) => { if (args.length > 0) { args[0] = addPrefix(args[0]); } return originalProp.apply(this, args); }; } if (prop2 === "promise") { return (...args) => { const [promise, data] = args; if (!data) return originalProp; const prefixedData = { ...data, loading: typeof data.loading === "string" ? addPrefix(data.loading) : data.loading, success: typeof data.success === "string" ? addPrefix(data.success) : data.success, error: typeof data.error === "string" ? addPrefix(data.error) : data.error }; return originalProp.call(this, promise, prefixedData); }; } return originalProp; } }); class GlobalState { constructor() { __privateAdd(this, _site); } get site() { if (!__privateGet(this, _site)) { const hostname = window.location.hostname; __privateSet(this, _site, hostname === "leetcode.cn" ? "cn" : "global"); } return __privateGet(this, _site); } } _site = new WeakMap(); const globalState = new GlobalState(); var _GM_getResourceText = /* @__PURE__ */ (() => typeof GM_getResourceText != "undefined" ? GM_getResourceText : void 0)(); var _unsafeWindow = /* @__PURE__ */ (() => typeof unsafeWindow != "undefined" ? unsafeWindow : void 0)(); class TimeoutError extends Error { constructor(item, timeout) { super(); __publicField(this, "name", this.constructor.name); this.message = `"${item}" not found within timeout (${timeout}ms)`; } } function find(finderFn, { subject = document, observerOption = { childList: true, subtree: true }, timeout = 5e3, itemName = "Item" }) { return new Promise((resolve, reject) => { const item = finderFn(); if (item) return resolve(item); let timeoutId; const observer = new MutationObserver(() => { const item2 = finderFn(); if (item2) { observer.disconnect(); clearTimeout(timeoutId); return resolve(item2); } }); observer.observe(subject, observerOption); if (timeout > 0) { timeoutId = setTimeout(() => { observer.disconnect(); prefixToast.error( `${itemName} not found within timeout. Please refresh the page or disable the script.` ); const error = new TimeoutError(itemName, timeout); console.error(error); return reject(error); }, timeout); } }); } async function findElement(selector, { parent = document, timeout = 500, additionalRule } = {}) { const element = await find( () => { const el = parent.querySelector(selector); if (additionalRule && el) { return additionalRule(el) ? el : null; } else { return el; } }, { subject: parent, timeout, itemName: `Element ${selector}` } ); return element; } const overrideOptions = { selectionHighlight: true, parameterHints: { enabled: true }, hover: { enabled: true }, quickSuggestions: true, suggestOnTriggerCharacters: true, "bracketPairColorization.enabled": true }; function addIntellisense(editor) { const originalUpdateOptions = editor.updateOptions.bind(editor); editor.updateOptions = (options) => { originalUpdateOptions({ ...options, ...overrideOptions }); }; } async function findMonacoEditor() { function getEditor() { var _a2; return ((_a2 = _unsafeWindow.monaco) == null ? void 0 : _a2.editor.getEditors()[0]) ?? null; } const editor = find(getEditor, { subject: document.head, observerOption: { childList: true }, itemName: "Monaco Editor" }); return editor; } class ProblemPageState { constructor() { __publicField(this, "editor", null); } async patchMonacoEditor() { this.editor = await findMonacoEditor(); this.enableFormatOnSave(); addIntellisense(this.editor); } enableFormatOnSave() { document.addEventListener("keydown", async (e2) => { var _a2, _b; if (!(e2.ctrlKey && e2.key === "s")) return; try { await ((_b = (_a2 = this.editor) == null ? void 0 : _a2.getAction("editor.action.formatDocument")) == null ? void 0 : _b.run()); } catch (err) { console.error(err); if (err instanceof Error) { toast.error("Failed to format code:" + err.message); } } }); } } const problemState = new ProblemPageState(); function u$1(o2, n, a2) { let t = (r2) => o2(r2, ...n); return t; } function u(r2, n, o2) { let a2 = r2.length - n.length; if (a2 === 0) return r2(...n); if (a2 === 1) return u$1(r2, n); throw new Error("Wrong number of arguments"); } var o$1 = [" ", ` `, "\v", "\f", "\r", " ", "…", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "\u2028", "\u2029", " ", " ", " ", "\uFEFF"], c = /* @__PURE__ */ new Set(["-", "_", ...o$1]), i = (r2) => { let e2 = [], t = "", u2 = () => { t.length > 0 && (e2.push(t), t = ""); }; for (let s of r2) { if (c.has(s)) { u2(); continue; } if (/[a-z]$/u.test(t) && /[A-Z]/u.test(s)) u2(); else if (/[A-Z][A-Z]$/u.test(t) && /[a-z]/u.test(s)) { let n = t.slice(-1); t = t.slice(0, -1), u2(), t = n; } else /\d$/u.test(t) !== /\d/u.test(s) && u2(); t += s; } return u2(), e2; }; function a(...e2) { return u(o, e2); } var o = (e2) => i(e2).join("-").toLowerCase(); function e(o2) { return o2 instanceof Promise; } var root$1 = /* @__PURE__ */ template(`
      `); function ButtonGroup($$anchor, $$props) { let props = /* @__PURE__ */ rest_props($$props, [ "$$slots", "$$events", "$$legacy", "children" ]); var div = root$1(); let attributes; var node = child(div); snippet(node, () => $$props.children); template_effect(() => attributes = set_attributes(div, attributes, { ...props }, "svelte-4mbyk0")); append($$anchor, div); } const mouseClickEvents = ["mousedown", "mouseup", "click"]; function simulateMouseClickReact(element) { mouseClickEvents.forEach( (mouseEventType) => element.dispatchEvent( new MouseEvent(mouseEventType, { view: _unsafeWindow, bubbles: true, cancelable: true, buttons: 1 }) ) ); } const loaderIcon = ($$anchor) => { var svg = root_1$3(); append($$anchor, svg); }; var root_1$3 = /* @__PURE__ */ ns_template(``); var root_2 = /* @__PURE__ */ template(``); var root_3 = /* @__PURE__ */ template(``); function Button($$anchor, $$props) { push($$props, true); let variant = prop($$props, "variant", 3, "purple"), type = prop($$props, "type", 3, "button"), restProps = /* @__PURE__ */ rest_props($$props, [ "$$slots", "$$events", "$$legacy", "onclick", "children", "variant", "type", "href" ]); const variants = { purple: "--bg: #6c5ce7; --shadow: #a29bfe", green: "--bg: #1ba13e; --shadow: #42de6e", orange: "--bg: #ffa116; --shadow: #fedd9b" }; let loading = /* @__PURE__ */ state(false); async function handleOnClick(e$1) { if (!$$props.onclick) return; const returnValue = $$props.onclick(e$1); if (e(returnValue)) { set(loading, true); await returnValue; set(loading, false); } } var fragment = comment(); var node = first_child(fragment); { var consequent = ($$anchor2) => { var a2 = root_2(); let attributes; var node_1 = child(a2); snippet(node_1, () => $$props.children ?? noop); template_effect(() => attributes = set_attributes( a2, attributes, { style: variants[variant()], href: $$props.href, target: "_blank", ...restProps }, "svelte-ll0ynk" )); append($$anchor2, a2); }; var alternate = ($$anchor2) => { var button = root_3(); let attributes_1; var node_2 = child(button); { var consequent_1 = ($$anchor3) => { loaderIcon($$anchor3); }; if_block(node_2, ($$render) => { if (get(loading)) $$render(consequent_1); }); } var node_3 = sibling(node_2, 2); snippet(node_3, () => $$props.children ?? noop); template_effect(() => attributes_1 = set_attributes( button, attributes_1, { style: variants[variant()], type: type(), disabled: get(loading), onclick: handleOnClick, ...restProps }, "svelte-ll0ynk" )); append($$anchor2, button); }; if_block(node, ($$render) => { if ($$props.href) $$render(consequent); else $$render(alternate, false); }); } append($$anchor, fragment); pop(); } async function copy(text2, toastId) { try { await navigator.clipboard.writeText(text2); prefixToast.success( globalState.site === "cn" ? "复制到剪贴板!" : "Copied to clipboard!", { id: toastId // update an already present toast, if given the id of that toast } ); } catch (err) { if (err instanceof Error) { const errorMessage = globalState.site === "cn" ? "复制失败" : "Failed to copy"; prefixToast.error(errorMessage + ": " + err.message, { id: toastId }); console.error(errorMessage + err); } else throw err; } } const getTitle = async () => { const descriptionTabButton = (await findElement("#description_tab")).closest(".flexlayout__tab_button"); if (!(descriptionTabButton == null ? void 0 : descriptionTabButton.classList.contains(".flexlayout__tab_button--selected"))) { simulateMouseClickReact(descriptionTabButton); } return (await findElement(".text-title-large")).textContent ?? ""; }; function Copy_title($$anchor, $$props) { push($$props, false); async function copyTitle() { copy(await getTitle()); } init(); Button($$anchor, { onclick: copyTitle, children: ($$anchor2, $$slotProps) => { var text$1 = text(); template_effect(() => set_text(text$1, globalState.site === "cn" ? "复制标题" : "Copy Title")); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } function extend(destination) { for (var i2 = 1; i2 < arguments.length; i2++) { var source2 = arguments[i2]; for (var key in source2) { if (source2.hasOwnProperty(key)) destination[key] = source2[key]; } } return destination; } function repeat(character, count) { return Array(count + 1).join(character); } function trimLeadingNewlines(string) { return string.replace(/^\n*/, ""); } function trimTrailingNewlines(string) { var indexEnd = string.length; while (indexEnd > 0 && string[indexEnd - 1] === "\n") indexEnd--; return string.substring(0, indexEnd); } var blockElements = [ "ADDRESS", "ARTICLE", "ASIDE", "AUDIO", "BLOCKQUOTE", "BODY", "CANVAS", "CENTER", "DD", "DIR", "DIV", "DL", "DT", "FIELDSET", "FIGCAPTION", "FIGURE", "FOOTER", "FORM", "FRAMESET", "H1", "H2", "H3", "H4", "H5", "H6", "HEADER", "HGROUP", "HR", "HTML", "ISINDEX", "LI", "MAIN", "MENU", "NAV", "NOFRAMES", "NOSCRIPT", "OL", "OUTPUT", "P", "PRE", "SECTION", "TABLE", "TBODY", "TD", "TFOOT", "TH", "THEAD", "TR", "UL" ]; function isBlock(node) { return is(node, blockElements); } var voidElements = [ "AREA", "BASE", "BR", "COL", "COMMAND", "EMBED", "HR", "IMG", "INPUT", "KEYGEN", "LINK", "META", "PARAM", "SOURCE", "TRACK", "WBR" ]; function isVoid(node) { return is(node, voidElements); } function hasVoid(node) { return has(node, voidElements); } var meaningfulWhenBlankElements = [ "A", "TABLE", "THEAD", "TBODY", "TFOOT", "TH", "TD", "IFRAME", "SCRIPT", "AUDIO", "VIDEO" ]; function isMeaningfulWhenBlank(node) { return is(node, meaningfulWhenBlankElements); } function hasMeaningfulWhenBlank(node) { return has(node, meaningfulWhenBlankElements); } function is(node, tagNames) { return tagNames.indexOf(node.nodeName) >= 0; } function has(node, tagNames) { return node.getElementsByTagName && tagNames.some(function(tagName) { return node.getElementsByTagName(tagName).length; }); } var rules = {}; rules.paragraph = { filter: "p", replacement: function(content) { return "\n\n" + content + "\n\n"; } }; rules.lineBreak = { filter: "br", replacement: function(content, node, options) { return options.br + "\n"; } }; rules.heading = { filter: ["h1", "h2", "h3", "h4", "h5", "h6"], replacement: function(content, node, options) { var hLevel = Number(node.nodeName.charAt(1)); if (options.headingStyle === "setext" && hLevel < 3) { var underline = repeat(hLevel === 1 ? "=" : "-", content.length); return "\n\n" + content + "\n" + underline + "\n\n"; } else { return "\n\n" + repeat("#", hLevel) + " " + content + "\n\n"; } } }; rules.blockquote = { filter: "blockquote", replacement: function(content) { content = content.replace(/^\n+|\n+$/g, ""); content = content.replace(/^/gm, "> "); return "\n\n" + content + "\n\n"; } }; rules.list = { filter: ["ul", "ol"], replacement: function(content, node) { var parent = node.parentNode; if (parent.nodeName === "LI" && parent.lastElementChild === node) { return "\n" + content; } else { return "\n\n" + content + "\n\n"; } } }; rules.listItem = { filter: "li", replacement: function(content, node, options) { content = content.replace(/^\n+/, "").replace(/\n+$/, "\n").replace(/\n/gm, "\n "); var prefix = options.bulletListMarker + " "; var parent = node.parentNode; if (parent.nodeName === "OL") { var start = parent.getAttribute("start"); var index = Array.prototype.indexOf.call(parent.children, node); prefix = (start ? Number(start) + index : index + 1) + ". "; } return prefix + content + (node.nextSibling && !/\n$/.test(content) ? "\n" : ""); } }; rules.indentedCodeBlock = { filter: function(node, options) { return options.codeBlockStyle === "indented" && node.nodeName === "PRE" && node.firstChild && node.firstChild.nodeName === "CODE"; }, replacement: function(content, node, options) { return "\n\n " + node.firstChild.textContent.replace(/\n/g, "\n ") + "\n\n"; } }; rules.fencedCodeBlock = { filter: function(node, options) { return options.codeBlockStyle === "fenced" && node.nodeName === "PRE" && node.firstChild && node.firstChild.nodeName === "CODE"; }, replacement: function(content, node, options) { var className = node.firstChild.getAttribute("class") || ""; var language = (className.match(/language-(\S+)/) || [null, ""])[1]; var code = node.firstChild.textContent; var fenceChar = options.fence.charAt(0); var fenceSize = 3; var fenceInCodeRegex = new RegExp("^" + fenceChar + "{3,}", "gm"); var match; while (match = fenceInCodeRegex.exec(code)) { if (match[0].length >= fenceSize) { fenceSize = match[0].length + 1; } } var fence = repeat(fenceChar, fenceSize); return "\n\n" + fence + language + "\n" + code.replace(/\n$/, "") + "\n" + fence + "\n\n"; } }; rules.horizontalRule = { filter: "hr", replacement: function(content, node, options) { return "\n\n" + options.hr + "\n\n"; } }; rules.inlineLink = { filter: function(node, options) { return options.linkStyle === "inlined" && node.nodeName === "A" && node.getAttribute("href"); }, replacement: function(content, node) { var href = node.getAttribute("href"); if (href) href = href.replace(/([()])/g, "\\$1"); var title = cleanAttribute(node.getAttribute("title")); if (title) title = ' "' + title.replace(/"/g, '\\"') + '"'; return "[" + content + "](" + href + title + ")"; } }; rules.referenceLink = { filter: function(node, options) { return options.linkStyle === "referenced" && node.nodeName === "A" && node.getAttribute("href"); }, replacement: function(content, node, options) { var href = node.getAttribute("href"); var title = cleanAttribute(node.getAttribute("title")); if (title) title = ' "' + title + '"'; var replacement; var reference; switch (options.linkReferenceStyle) { case "collapsed": replacement = "[" + content + "][]"; reference = "[" + content + "]: " + href + title; break; case "shortcut": replacement = "[" + content + "]"; reference = "[" + content + "]: " + href + title; break; default: var id = this.references.length + 1; replacement = "[" + content + "][" + id + "]"; reference = "[" + id + "]: " + href + title; } this.references.push(reference); return replacement; }, references: [], append: function(options) { var references = ""; if (this.references.length) { references = "\n\n" + this.references.join("\n") + "\n\n"; this.references = []; } return references; } }; rules.emphasis = { filter: ["em", "i"], replacement: function(content, node, options) { if (!content.trim()) return ""; return options.emDelimiter + content + options.emDelimiter; } }; rules.strong = { filter: ["strong", "b"], replacement: function(content, node, options) { if (!content.trim()) return ""; return options.strongDelimiter + content + options.strongDelimiter; } }; rules.code = { filter: function(node) { var hasSiblings = node.previousSibling || node.nextSibling; var isCodeBlock = node.parentNode.nodeName === "PRE" && !hasSiblings; return node.nodeName === "CODE" && !isCodeBlock; }, replacement: function(content) { if (!content) return ""; content = content.replace(/\r?\n|\r/g, " "); var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? " " : ""; var delimiter = "`"; var matches = content.match(/`+/gm) || []; while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + "`"; return delimiter + extraSpace + content + extraSpace + delimiter; } }; rules.image = { filter: "img", replacement: function(content, node) { var alt = cleanAttribute(node.getAttribute("alt")); var src = node.getAttribute("src") || ""; var title = cleanAttribute(node.getAttribute("title")); var titlePart = title ? ' "' + title + '"' : ""; return src ? "![" + alt + "](" + src + titlePart + ")" : ""; } }; function cleanAttribute(attribute) { return attribute ? attribute.replace(/(\n+\s*)+/g, "\n") : ""; } function Rules(options) { this.options = options; this._keep = []; this._remove = []; this.blankRule = { replacement: options.blankReplacement }; this.keepReplacement = options.keepReplacement; this.defaultRule = { replacement: options.defaultReplacement }; this.array = []; for (var key in options.rules) this.array.push(options.rules[key]); } Rules.prototype = { add: function(key, rule) { this.array.unshift(rule); }, keep: function(filter) { this._keep.unshift({ filter, replacement: this.keepReplacement }); }, remove: function(filter) { this._remove.unshift({ filter, replacement: function() { return ""; } }); }, forNode: function(node) { if (node.isBlank) return this.blankRule; var rule; if (rule = findRule(this.array, node, this.options)) return rule; if (rule = findRule(this._keep, node, this.options)) return rule; if (rule = findRule(this._remove, node, this.options)) return rule; return this.defaultRule; }, forEach: function(fn) { for (var i2 = 0; i2 < this.array.length; i2++) fn(this.array[i2], i2); } }; function findRule(rules2, node, options) { for (var i2 = 0; i2 < rules2.length; i2++) { var rule = rules2[i2]; if (filterValue(rule, node, options)) return rule; } return void 0; } function filterValue(rule, node, options) { var filter = rule.filter; if (typeof filter === "string") { if (filter === node.nodeName.toLowerCase()) return true; } else if (Array.isArray(filter)) { if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true; } else if (typeof filter === "function") { if (filter.call(rule, node, options)) return true; } else { throw new TypeError("`filter` needs to be a string, array, or function"); } } function collapseWhitespace(options) { var element = options.element; var isBlock2 = options.isBlock; var isVoid2 = options.isVoid; var isPre = options.isPre || function(node2) { return node2.nodeName === "PRE"; }; if (!element.firstChild || isPre(element)) return; var prevText = null; var keepLeadingWs = false; var prev = null; var node = next(prev, element, isPre); while (node !== element) { if (node.nodeType === 3 || node.nodeType === 4) { var text2 = node.data.replace(/[ \r\n\t]+/g, " "); if ((!prevText || / $/.test(prevText.data)) && !keepLeadingWs && text2[0] === " ") { text2 = text2.substr(1); } if (!text2) { node = remove(node); continue; } node.data = text2; prevText = node; } else if (node.nodeType === 1) { if (isBlock2(node) || node.nodeName === "BR") { if (prevText) { prevText.data = prevText.data.replace(/ $/, ""); } prevText = null; keepLeadingWs = false; } else if (isVoid2(node) || isPre(node)) { prevText = null; keepLeadingWs = true; } else if (prevText) { keepLeadingWs = false; } } else { node = remove(node); continue; } var nextNode = next(prev, node, isPre); prev = node; node = nextNode; } if (prevText) { prevText.data = prevText.data.replace(/ $/, ""); if (!prevText.data) { remove(prevText); } } } function remove(node) { var next2 = node.nextSibling || node.parentNode; node.parentNode.removeChild(node); return next2; } function next(prev, current, isPre) { if (prev && prev.parentNode === current || isPre(current)) { return current.nextSibling || current.parentNode; } return current.firstChild || current.nextSibling || current.parentNode; } var root = typeof window !== "undefined" ? window : {}; function canParseHTMLNatively() { var Parser = root.DOMParser; var canParse = false; try { if (new Parser().parseFromString("", "text/html")) { canParse = true; } } catch (e2) { } return canParse; } function createHTMLParser() { var Parser = function() { }; { if (shouldUseActiveX()) { Parser.prototype.parseFromString = function(string) { var doc = new window.ActiveXObject("htmlfile"); doc.designMode = "on"; doc.open(); doc.write(string); doc.close(); return doc; }; } else { Parser.prototype.parseFromString = function(string) { var doc = document.implementation.createHTMLDocument(""); doc.open(); doc.write(string); doc.close(); return doc; }; } } return Parser; } function shouldUseActiveX() { var useActiveX = false; try { document.implementation.createHTMLDocument("").open(); } catch (e2) { if (root.ActiveXObject) useActiveX = true; } return useActiveX; } var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser(); function RootNode(input, options) { var root2; if (typeof input === "string") { var doc = htmlParser().parseFromString( // DOM parsers arrange elements in the and . // Wrapping in a custom element ensures elements are reliably arranged in // a single element. '' + input + "", "text/html" ); root2 = doc.getElementById("turndown-root"); } else { root2 = input.cloneNode(true); } collapseWhitespace({ element: root2, isBlock, isVoid, isPre: options.preformattedCode ? isPreOrCode : null }); return root2; } var _htmlParser; function htmlParser() { _htmlParser = _htmlParser || new HTMLParser(); return _htmlParser; } function isPreOrCode(node) { return node.nodeName === "PRE" || node.nodeName === "CODE"; } function Node$1(node, options) { node.isBlock = isBlock(node); node.isCode = node.nodeName === "CODE" || node.parentNode.isCode; node.isBlank = isBlank(node); node.flankingWhitespace = flankingWhitespace(node, options); return node; } function isBlank(node) { return !isVoid(node) && !isMeaningfulWhenBlank(node) && /^\s*$/i.test(node.textContent) && !hasVoid(node) && !hasMeaningfulWhenBlank(node); } function flankingWhitespace(node, options) { if (node.isBlock || options.preformattedCode && node.isCode) { return { leading: "", trailing: "" }; } var edges = edgeWhitespace(node.textContent); if (edges.leadingAscii && isFlankedByWhitespace("left", node, options)) { edges.leading = edges.leadingNonAscii; } if (edges.trailingAscii && isFlankedByWhitespace("right", node, options)) { edges.trailing = edges.trailingNonAscii; } return { leading: edges.leading, trailing: edges.trailing }; } function edgeWhitespace(string) { var m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/); return { leading: m[1], // whole string for whitespace-only strings leadingAscii: m[2], leadingNonAscii: m[3], trailing: m[4], // empty for whitespace-only strings trailingNonAscii: m[5], trailingAscii: m[6] }; } function isFlankedByWhitespace(side, node, options) { var sibling2; var regExp; var isFlanked; if (side === "left") { sibling2 = node.previousSibling; regExp = / $/; } else { sibling2 = node.nextSibling; regExp = /^ /; } if (sibling2) { if (sibling2.nodeType === 3) { isFlanked = regExp.test(sibling2.nodeValue); } else if (options.preformattedCode && sibling2.nodeName === "CODE") { isFlanked = false; } else if (sibling2.nodeType === 1 && !isBlock(sibling2)) { isFlanked = regExp.test(sibling2.textContent); } } return isFlanked; } var reduce = Array.prototype.reduce; var escapes = [ [/\\/g, "\\\\"], [/\*/g, "\\*"], [/^-/g, "\\-"], [/^\+ /g, "\\+ "], [/^(=+)/g, "\\$1"], [/^(#{1,6}) /g, "\\$1 "], [/`/g, "\\`"], [/^~~~/g, "\\~~~"], [/\[/g, "\\["], [/\]/g, "\\]"], [/^>/g, "\\>"], [/_/g, "\\_"], [/^(\d+)\. /g, "$1\\. "] ]; function TurndownService(options) { if (!(this instanceof TurndownService)) return new TurndownService(options); var defaults = { rules, headingStyle: "setext", hr: "* * *", bulletListMarker: "*", codeBlockStyle: "indented", fence: "```", emDelimiter: "_", strongDelimiter: "**", linkStyle: "inlined", linkReferenceStyle: "full", br: " ", preformattedCode: false, blankReplacement: function(content, node) { return node.isBlock ? "\n\n" : ""; }, keepReplacement: function(content, node) { return node.isBlock ? "\n\n" + node.outerHTML + "\n\n" : node.outerHTML; }, defaultReplacement: function(content, node) { return node.isBlock ? "\n\n" + content + "\n\n" : content; } }; this.options = extend({}, defaults, options); this.rules = new Rules(this.options); } TurndownService.prototype = { /** * The entry point for converting a string or DOM node to Markdown * @public * @param {String|HTMLElement} input The string or DOM node to convert * @returns A Markdown representation of the input * @type String */ turndown: function(input) { if (!canConvert(input)) { throw new TypeError( input + " is not a string, or an element/document/fragment node." ); } if (input === "") return ""; var output = process.call(this, new RootNode(input, this.options)); return postProcess.call(this, output); }, /** * Add one or more plugins * @public * @param {Function|Array} plugin The plugin or array of plugins to add * @returns The Turndown instance for chaining * @type Object */ use: function(plugin) { if (Array.isArray(plugin)) { for (var i2 = 0; i2 < plugin.length; i2++) this.use(plugin[i2]); } else if (typeof plugin === "function") { plugin(this); } else { throw new TypeError("plugin must be a Function or an Array of Functions"); } return this; }, /** * Adds a rule * @public * @param {String} key The unique key of the rule * @param {Object} rule The rule * @returns The Turndown instance for chaining * @type Object */ addRule: function(key, rule) { this.rules.add(key, rule); return this; }, /** * Keep a node (as HTML) that matches the filter * @public * @param {String|Array|Function} filter The unique key of the rule * @returns The Turndown instance for chaining * @type Object */ keep: function(filter) { this.rules.keep(filter); return this; }, /** * Remove a node that matches the filter * @public * @param {String|Array|Function} filter The unique key of the rule * @returns The Turndown instance for chaining * @type Object */ remove: function(filter) { this.rules.remove(filter); return this; }, /** * Escapes Markdown syntax * @public * @param {String} string The string to escape * @returns A string with Markdown syntax escaped * @type String */ escape: function(string) { return escapes.reduce(function(accumulator, escape) { return accumulator.replace(escape[0], escape[1]); }, string); } }; function process(parentNode) { var self = this; return reduce.call(parentNode.childNodes, function(output, node) { node = new Node$1(node, self.options); var replacement = ""; if (node.nodeType === 3) { replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue); } else if (node.nodeType === 1) { replacement = replacementForNode.call(self, node); } return join(output, replacement); }, ""); } function postProcess(output) { var self = this; this.rules.forEach(function(rule) { if (typeof rule.append === "function") { output = join(output, rule.append(self.options)); } }); return output.replace(/^[\t\r\n]+/, "").replace(/[\t\r\n\s]+$/, ""); } function replacementForNode(node) { var rule = this.rules.forNode(node); var content = process.call(this, node); var whitespace2 = node.flankingWhitespace; if (whitespace2.leading || whitespace2.trailing) content = content.trim(); return whitespace2.leading + rule.replacement(content, node, this.options) + whitespace2.trailing; } function join(output, replacement) { var s1 = trimTrailingNewlines(output); var s2 = trimLeadingNewlines(replacement); var nls = Math.max(output.length - s1.length, replacement.length - s2.length); var separator = "\n\n".substring(0, nls); return s1 + separator + s2; } function canConvert(input) { return input != null && (typeof input === "string" || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11)); } var turndownPluginGfm_cjs = {}; var hasRequiredTurndownPluginGfm_cjs; function requireTurndownPluginGfm_cjs() { if (hasRequiredTurndownPluginGfm_cjs) return turndownPluginGfm_cjs; hasRequiredTurndownPluginGfm_cjs = 1; Object.defineProperty(turndownPluginGfm_cjs, "__esModule", { value: true }); var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/; function highlightedCodeBlock(turndownService) { turndownService.addRule("highlightedCodeBlock", { filter: function(node) { var firstChild = node.firstChild; return node.nodeName === "DIV" && highlightRegExp.test(node.className) && firstChild && firstChild.nodeName === "PRE"; }, replacement: function(content, node, options) { var className = node.className || ""; var language = (className.match(highlightRegExp) || [null, ""])[1]; return "\n\n" + options.fence + language + "\n" + node.firstChild.textContent + "\n" + options.fence + "\n\n"; } }); } function strikethrough(turndownService) { turndownService.addRule("strikethrough", { filter: ["del", "s", "strike"], replacement: function(content) { return "~~" + content + "~~"; } }); } var indexOf = Array.prototype.indexOf; var every = Array.prototype.every; var rules2 = {}; var alignMap = { left: ":---", right: "---:", center: ":---:" }; let isCodeBlock_ = null; let options_ = null; const tableShouldBeSkippedCache_ = /* @__PURE__ */ new WeakMap(); function getAlignment(node) { return node ? (node.getAttribute("align") || node.style.textAlign || "").toLowerCase() : ""; } function getBorder(alignment) { return alignment ? alignMap[alignment] : "---"; } function getColumnAlignment(table, columnIndex) { var votes = { left: 0, right: 0, center: 0, "": 0 }; var align = ""; for (var i2 = 0; i2 < table.rows.length; ++i2) { var row = table.rows[i2]; if (columnIndex < row.childNodes.length) { var cellAlignment = getAlignment(row.childNodes[columnIndex]); ++votes[cellAlignment]; if (votes[cellAlignment] > votes[align]) { align = cellAlignment; } } } return align; } rules2.tableCell = { filter: ["th", "td"], replacement: function(content, node) { if (tableShouldBeSkipped(nodeParentTable(node))) return content; return cell(content, node); } }; rules2.tableRow = { filter: "tr", replacement: function(content, node) { const parentTable = nodeParentTable(node); if (tableShouldBeSkipped(parentTable)) return content; var borderCells = ""; if (isHeadingRow(node)) { const colCount = tableColCount(parentTable); for (var i2 = 0; i2 < colCount; i2++) { const childNode = i2 < node.childNodes.length ? node.childNodes[i2] : null; var border = getBorder(getColumnAlignment(parentTable, i2)); borderCells += cell(border, childNode, i2); } } return "\n" + content + (borderCells ? "\n" + borderCells : ""); } }; rules2.table = { filter: function(node, options) { return node.nodeName === "TABLE"; }, replacement: function(content, node) { if (tableShouldBeHtml(node, options_)) { let html = node.outerHTML; let divParent = nodeParentDiv(node); if (divParent === null || !divParent.classList.contains("joplin-table-wrapper")) { return `
      ${html}
      `; } else { return html; } } else { if (tableShouldBeSkipped(node)) return content; content = content.replace(/\n+/g, "\n"); var secondLine = content.trim().split("\n"); if (secondLine.length >= 2) secondLine = secondLine[1]; var secondLineIsDivider = /\| :?---/.test(secondLine); var columnCount = tableColCount(node); var emptyHeader = ""; if (columnCount && !secondLineIsDivider) { emptyHeader = "|" + " |".repeat(columnCount) + "\n|"; for (var columnIndex = 0; columnIndex < columnCount; ++columnIndex) { emptyHeader += " " + getBorder(getColumnAlignment(node, columnIndex)) + " |"; } } const captionContent = node.caption ? node.caption.textContent || "" : ""; const caption = captionContent ? `${captionContent} ` : ""; const tableContent = `${emptyHeader}${content}`.trimStart(); return ` ${caption}${tableContent} `; } } }; rules2.tableCaption = { filter: ["caption"], replacement: () => "" }; rules2.tableColgroup = { filter: ["colgroup", "col"], replacement: () => "" }; rules2.tableSection = { filter: ["thead", "tbody", "tfoot"], replacement: function(content) { return content; } }; function isHeadingRow(tr) { var parentNode = tr.parentNode; return parentNode.nodeName === "THEAD" || parentNode.firstChild === tr && (parentNode.nodeName === "TABLE" || isFirstTbody(parentNode)) && every.call(tr.childNodes, function(n) { return n.nodeName === "TH"; }); } function isFirstTbody(element) { var previousSibling = element.previousSibling; return element.nodeName === "TBODY" && (!previousSibling || previousSibling.nodeName === "THEAD" && /^\s*$/i.test(previousSibling.textContent)); } function cell(content, node = null, index = null) { if (index === null) index = indexOf.call(node.parentNode.childNodes, node); var prefix = " "; if (index === 0) prefix = "| "; let filteredContent = content.trim().replace(/\n\r/g, "
      ").replace(/\n/g, "
      "); filteredContent = filteredContent.replace(/\|+/g, "\\|"); while (filteredContent.length < 3) filteredContent += " "; if (node) filteredContent = handleColSpan(filteredContent, node, " "); return prefix + filteredContent + " |"; } function nodeContainsTable(node) { if (!node.childNodes) return false; for (let i2 = 0; i2 < node.childNodes.length; i2++) { const child2 = node.childNodes[i2]; if (child2.nodeName === "TABLE") return true; if (nodeContainsTable(child2)) return true; } return false; } const nodeContains = (node, types) => { if (!node.childNodes) return false; for (let i2 = 0; i2 < node.childNodes.length; i2++) { const child2 = node.childNodes[i2]; if (types === "code" && isCodeBlock_ && isCodeBlock_(child2)) return true; if (types.includes(child2.nodeName)) return true; if (nodeContains(child2, types)) return true; } return false; }; const tableShouldBeHtml = (tableNode, options) => { const possibleTags = [ "UL", "OL", "H1", "H2", "H3", "H4", "H5", "H6", "HR", "BLOCKQUOTE" ]; if (options.preserveNestedTables) possibleTags.push("TABLE"); return nodeContains(tableNode, "code") || nodeContains(tableNode, possibleTags); }; function tableShouldBeSkipped(tableNode) { const cached = tableShouldBeSkippedCache_.get(tableNode); if (cached !== void 0) return cached; const result = tableShouldBeSkipped_(tableNode); tableShouldBeSkippedCache_.set(tableNode, result); return result; } function tableShouldBeSkipped_(tableNode) { if (!tableNode) return true; if (!tableNode.rows) return true; if (tableNode.rows.length === 1 && tableNode.rows[0].childNodes.length <= 1) return true; if (nodeContainsTable(tableNode)) return true; return false; } function nodeParentDiv(node) { let parent = node.parentNode; while (parent.nodeName !== "DIV") { parent = parent.parentNode; if (!parent) return null; } return parent; } function nodeParentTable(node) { let parent = node.parentNode; while (parent.nodeName !== "TABLE") { parent = parent.parentNode; if (!parent) return null; } return parent; } function handleColSpan(content, node, emptyChar) { const colspan = node.getAttribute("colspan") || 1; for (let i2 = 1; i2 < colspan; i2++) { content += " | " + emptyChar.repeat(3); } return content; } function tableColCount(node) { let maxColCount = 0; for (let i2 = 0; i2 < node.rows.length; i2++) { const row = node.rows[i2]; const colCount = row.childNodes.length; if (colCount > maxColCount) maxColCount = colCount; } return maxColCount; } function tables(turndownService) { isCodeBlock_ = turndownService.isCodeBlock; options_ = turndownService.options; turndownService.keep(function(node) { if (node.nodeName === "TABLE" && tableShouldBeHtml(node, turndownService.options)) return true; return false; }); for (var key in rules2) turndownService.addRule(key, rules2[key]); } function taskListItems(turndownService) { turndownService.addRule("taskListItems", { filter: function(node) { return node.type === "checkbox" && node.parentNode.nodeName === "LI"; }, replacement: function(content, node) { return (node.checked ? "[x]" : "[ ]") + " "; } }); } function gfm(turndownService) { turndownService.use([ highlightedCodeBlock, strikethrough, tables, taskListItems ]); } turndownPluginGfm_cjs.gfm = gfm; turndownPluginGfm_cjs.highlightedCodeBlock = highlightedCodeBlock; turndownPluginGfm_cjs.strikethrough = strikethrough; turndownPluginGfm_cjs.tables = tables; turndownPluginGfm_cjs.taskListItems = taskListItems; return turndownPluginGfm_cjs; } var turndownPluginGfm_cjsExports = requireTurndownPluginGfm_cjs(); var M = "__monkeyWindow-" + (() => { try { return new URL((_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('__entry.js', document.baseURI).href)).origin; } catch { return location.origin; } })(), y = document[M] ?? window, g = y.GM, v = y.GM_xmlhttpRequest; function k(l) { var e2; const t = new Headers(), a2 = l.replace(/\r?\n[\t ]+/g, " "); for (const d of a2.split(/\r?\n/)) { const i2 = d.split(":"), o2 = (e2 = i2.shift()) == null ? void 0 : e2.trim(); if (o2) { const r2 = i2.join(":").trim(); try { t.append(o2, r2); } catch (c2) { console.warn(`Response ${c2.message}`); } } } return t; } const H = async (l, t) => { const a2 = v || g.xmlHttpRequest; if (typeof a2 != "function") throw new DOMException( "GM_xmlhttpRequest or GM.xmlHttpRequest is not granted.", "NotFoundError" ); const e2 = new Request(l, t); if (e2.signal.aborted) throw new DOMException("Network request aborted.", "AbortError"); const d = await e2.blob(), i2 = Object.fromEntries(e2.headers); return new Headers(void 0).forEach((o2, r2) => { i2[r2] = o2; }), new Promise((o2, r2) => { let c2 = false; const R = new Promise((n) => { const { abort: h } = a2({ method: e2.method.toUpperCase(), url: e2.url || location.href, headers: i2, data: d.size ? d : void 0, redirect: e2.redirect, binary: true, nocache: e2.cache === "no-store", revalidate: e2.cache === "reload", timeout: 3e5, responseType: a2.RESPONSE_TYPE_STREAM ?? "blob", overrideMimeType: e2.headers.get("Content-Type") ?? void 0, anonymous: e2.credentials === "omit", onload: ({ response: s }) => { if (c2) { n(null); return; } n(s); }, async onreadystatechange({ readyState: s, responseHeaders: p, status: b, statusText: q, finalUrl: w, response: E }) { if (s === XMLHttpRequest.DONE) e2.signal.removeEventListener("abort", h); else if (s !== XMLHttpRequest.HEADERS_RECEIVED) return; if (c2) { n(null); return; } const u2 = k(p), f = e2.url !== w, m = new Response( E instanceof ReadableStream ? E : await R, { headers: u2, status: b, statusText: q } ); Object.defineProperties(m, { url: { value: w }, type: { value: "basic" }, ...m.redirected !== f ? { redirected: { value: f } } : {}, // https://fetch.spec.whatwg.org/#forbidden-response-header-name ...u2.has("set-cookie") || u2.has("set-cookie2") ? { headers: { value: u2 } } : {} }), o2(m), c2 = true; }, onerror: ({ statusText: s, error: p }) => { r2( new TypeError(s || p || "Network request failed.") ), n(null); }, ontimeout() { r2(new TypeError("Network request timeout.")), n(null); }, onabort() { r2(new DOMException("Network request aborted.", "AbortError")), n(null); } }); e2.signal.addEventListener("abort", h); }); }); }; function blobToDataURL(blob) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result); reader.onerror = (error) => reject(error); reader.readAsDataURL(blob); }); } async function convertSrcToDataURL(src) { if (src.startsWith("data:")) { return src; } try { const response = await H(src); const blob = await response.blob(); const dataURL = await blobToDataURL(blob); return dataURL; } catch (err) { console.error(`Failed to fetch image: ${src}`, err); throw err; } } const imageCache = /* @__PURE__ */ new Map(); async function prefetchImages(node) { const images = Array.from(node.querySelectorAll("img")); const fetchPromises = images.map(async ({ src }) => { if (imageCache.has(src)) return; const dataURL = await convertSrcToDataURL(src); imageCache.set(src, dataURL); }); await Promise.all(fetchPromises); } function createTurndownService() { const turndown2 = new TurndownService({ emDelimiter: "*", bulletListMarker: "-" }); turndown2.addRule("pre", { filter: ["pre"], replacement: (_content, node) => { var _a2; return "\n```txt\n" + ((_a2 = node.textContent) == null ? void 0 : _a2.trim()) + "\n```\n"; } }); turndown2.addRule("superscript", { filter: ["sup"], replacement: (content) => "^" + content }); turndown2.addRule("paragraph", { filter: ["p"], replacement: (content) => "\n\n" + content + "\n\n" }); turndown2.addRule("convert-img-src-to-base64", { filter: ["img"], replacement: (_content, node) => { const { src, alt } = node; const dataURL = imageCache.get(src); if (dataURL) { return `![${alt}](${dataURL})`; } return `![${alt}](${src})`; } }); turndown2.use(turndownPluginGfm_cjsExports.tables); return turndown2; } async function htmlToMd(node, { turndownService = createTurndownService(), convertImage = true } = {}) { if (convertImage) await prefetchImages(node); const md = turndownService.turndown(node); if (convertImage) imageCache.clear(); return md; } const getDescription = async (convertImage = true) => { const el = await findElement("div[data-track-load='description_content']"); return htmlToMd(el, { convertImage }); }; function Copy_description($$anchor, $$props) { push($$props, false); async function copyDescription() { const desc = await getDescription(false); copy(desc); } init(); Button($$anchor, { variant: "green", onclick: copyDescription, children: ($$anchor2, $$slotProps) => { var text$1 = text(); template_effect(() => set_text(text$1, globalState.site === "cn" ? "复制描述" : "Copy Description")); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } function downloadFile(blob, filename, extension) { const url2 = URL.createObjectURL(blob); const a2 = document.createElement("a"); a2.href = url2; a2.download = filename + "." + extension; document.body.appendChild(a2); a2.click(); document.body.removeChild(a2); URL.revokeObjectURL(url2); } function createNotebook({ title, description, code, language = "python", url: url2 }) { const notebook = { metadata: { language_info: { name: language } }, nbformat: 5, nbformat_minor: 10, cells: [] }; const regex = /^(https:\/\/(leetcode\.com|leetcode\.cn)\/problems\/[a-zA-Z0-9_-]+)/; const match = url2.match(regex); const titleCell = createMarkdownCell( `# [${title}](${match ? match[0] : url2})` ); const descriptionPrefix = globalState.site === "cn" ? "题目描述" : "Description"; const descriptionCell = createMarkdownCell( `## ${descriptionPrefix} ` + description ); const partitionCell = createMarkdownCell("---\n\n"); const solutionPrefix = globalState.site === "cn" ? "解答" : "Solution"; const solutionCell = createMarkdownCell(`## ${solutionPrefix}`); const codeCell = createCodeCell(code); notebook.cells.push( titleCell, descriptionCell, partitionCell, solutionCell, codeCell ); return notebook; } function createMarkdownCell(content) { return { cell_type: "markdown", metadata: {}, source: content }; } function createCodeCell(content) { return { cell_type: "code", metadata: {}, source: content, execution_count: null, outputs: [] }; } function downloadNotebook(notebook, filename) { const blob = new Blob([JSON.stringify(notebook)], { type: "application/x-ipynb+json" }); downloadFile(blob, filename, "ipynb"); } function Download_as_jupyter($$anchor, $$props) { push($$props, false); async function saveAsJupyter() { var _a2, _b, _c, _d; const title = await getTitle(); const notebook = createNotebook({ title, description: await getDescription(), code: ((_b = (_a2 = problemState.editor) == null ? void 0 : _a2.getModel()) == null ? void 0 : _b.getValue()) ?? "", language: ((_d = (_c = problemState.editor) == null ? void 0 : _c.getModel()) == null ? void 0 : _d.getLanguageId()) ?? "python", url: window.location.href }); downloadNotebook(notebook, title); } init(); Button($$anchor, { variant: "orange", onclick: () => { prefixToast.promise(saveAsJupyter(), { loading: "Scraping problem description and code...", success: "Start downloading jupyter notebook...", error: "Something went wrong while scraping. See browser console for more detail." }); }, children: ($$anchor2, $$slotProps) => { var text$1 = text(); template_effect(() => set_text(text$1, globalState.site === "cn" ? "保存为 Jupyter Notebook (.ipynb)" : "Save as Jupyter Notebook (.ipynb)")); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } var root_1$2 = /* @__PURE__ */ template(` `, 1); function DescriptionButttons($$anchor) { ButtonGroup($$anchor, { children: ($$anchor2, $$slotProps) => { var fragment_1 = root_1$2(); var node = first_child(fragment_1); Copy_title(node, {}); var node_1 = sibling(node, 2); Copy_description(node_1, {}); var node_2 = sibling(node_1, 2); Download_as_jupyter(node_2, {}); append($$anchor2, fragment_1); }, $$slots: { default: true } }); } async function initDescriptionTab() { var _a2; const descriptionTab = await findElement( ".flexlayout__tab:has([data-track-load='description_content'])", { timeout: 0, additionalRule: (el) => el.style.display !== "none" } ); const titleContainer = await findElement("div:has(> .text-title-large)", { parent: descriptionTab }); const buttonsContainer = document.createElement("div"); buttonsContainer.setAttribute( "id", a(CONFIG.APP_NAME) + "-description" ); buttonsContainer.style.cssText = "display: contents;"; (_a2 = titleContainer.parentElement) == null ? void 0 : _a2.before(buttonsContainer); mount(DescriptionButttons, { target: buttonsContainer }); } function Find_editorial_screenshot($$anchor, $$props) { push($$props, false); const editorialsMarkdown = _GM_getResourceText("editorials"); function extractScreenshotLink(problemTitle) { const cleanTitle = problemTitle.trim(); const headingPattern = new RegExp(`####\\s+\\[${cleanTitle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\]\\((.*?)\\)`, "i"); const match = editorialsMarkdown.match(headingPattern); return match ? match[1] : null; } async function goToEditorialScreenshot() { const title = await getTitle(); const link2 = extractScreenshotLink(title); if (link2) { window.open(link2, "_blank"); } else { toast.warning(`Editorial screenshot not found for problem: ${title}`); } } init(); Button($$anchor, { onclick: goToEditorialScreenshot, children: ($$anchor2, $$slotProps) => { var text$1 = text("Find Screenshot"); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } const turndown = createTurndownService(); turndown.addRule("remove-heading-link", { filter: (node) => node.nodeName === "A" && node.getAttribute("aria-hidden") === "true", replacement: () => "" }); turndown.addRule("save-math-as-is", { filter: (node) => ["SPAN", "DIV"].includes(node.nodeName) && node.matches(".math, .maths, .math-tex"), replacement: (_content, node) => node.outerHTML }); function waitForIframeToLoad(iframe) { return new Promise((resolve) => { var _a2, _b, _c, _d; if (iframe.src !== "about:blank") { const isSameOrigin = new URL(iframe.src).hostname === window.location.hostname; if (!isSameOrigin || ((_b = (_a2 = iframe.contentWindow) == null ? void 0 : _a2.location) == null ? void 0 : _b.href) !== "about:blank" && ((_c = iframe.contentWindow) == null ? void 0 : _c.document.readyState) == "complete") { resolve(void 0); return; } } console.log("wait for iframe to load..."); (_d = iframe.contentWindow) == null ? void 0 : _d.addEventListener("load", resolve, { once: true }); }); } const playgroundCache = /* @__PURE__ */ new Map(); async function prefetchPlayground(editorialEl) { const iframes = Array.from(editorialEl.querySelectorAll("iframe")); const promises = iframes.map(async (iframe) => { var _a2, _b; await waitForIframeToLoad(iframe); const { src, contentDocument } = iframe; if (!src.includes("playground")) return; console.log((_b = (_a2 = iframe.contentWindow) == null ? void 0 : _a2.location) == null ? void 0 : _b.href); const langTab = await findElement("div.lang-btn-set", { parent: contentDocument, timeout: 1e3 }); const textarea = contentDocument == null ? void 0 : contentDocument.querySelector( "textarea[name='lc-codemirror']" ); let result = ` `; Array.from( langTab.children ).forEach((button) => { var _a3; let lang = (_a3 = button.textContent) == null ? void 0 : _a3.toLowerCase(); if (lang === "python3") lang = "python"; button.click(); const code = textarea == null ? void 0 : textarea.textContent; result += `\`\`\`${lang} ${code} \`\`\` `; }); result += ``; playgroundCache.set(src, result); }); await Promise.all(promises); } turndown.addRule("save-code-playground", { filter: ["iframe"], replacement: (_content, node) => { const { src } = node; if (!src.includes("playground")) return ""; return `[LeetCode Playground](${src}) ` + (playgroundCache.get(src) ?? ""); } }); const slideCache = /* @__PURE__ */ new Map(); async function preFetchSlides(editorialEl) { const slideImages = editorialEl.querySelectorAll("img[alt='Current']"); const promises = Array.from(slideImages).map(async (image) => { var _a2, _b, _c; const slideContainer = (_a2 = image.parentElement) == null ? void 0 : _a2.parentElement; if (!slideContainer) { throw new Error("Slide container not found"); } const slideNumIndicator = slideContainer.children[2].children[1]; slideNumIndicator.setAttribute("data-skip-me-turndown", "true"); const slidesCountStr = (_c = (_b = slideNumIndicator.textContent) == null ? void 0 : _b.match(/\d+$/)) == null ? void 0 : _c[0]; if (!slidesCountStr) { throw new Error("Slide count not found"); } const nextSlideButton = slideContainer.querySelector("svg:nth-child(3)"); if (!nextSlideButton) { throw new Error("Next slide button not found"); } const firstSlideSrc = image.src; slideCache.set(firstSlideSrc, []); for (let i2 = 0; i2 < Number(slidesCountStr); i2++) { simulateMouseClickReact(nextSlideButton); const dataURL = await convertSrcToDataURL(image.src); slideCache.get(firstSlideSrc).push(dataURL); } }); await Promise.all(promises); } turndown.addRule("save-slides", { filter: (node) => node.tagName === "IMG" && node.alt === "Current", replacement: (_content, node) => { const { src } = node; const dataURLs = slideCache.get(src); if (!dataURLs) return ""; let res = ` `; dataURLs.forEach((dataURL, index) => { res += `![Slide ${index + 1}](${dataURL}) `; }); res += ` `; return res; } }); turndown.addRule("save-details-as-is", { filter: ["details"], replacement: (_content, node) => { const { children } = node; [...children].forEach((child2) => { if (!child2.textContent) node.removeChild(child2); }); return node.outerHTML; } }); turndown.remove( (node) => node.getAttribute("data-skip-me-turndown") === "true" ); async function scrapeEditorial(editorialEl) { await prefetchPlayground(editorialEl); await preFetchSlides(editorialEl); const editorial = await htmlToMd(editorialEl, { turndownService: turndown }); playgroundCache.clear(); slideCache.clear(); return editorial; } async function downloadEditorial(editorialFinder, titleFinder) { prefixToast.promise( async () => { const editorialEl = await editorialFinder(); const editorial = await scrapeEditorial(editorialEl); const title = await titleFinder(); const blob = new Blob([`# ${title} `, editorial], { type: "text/markdown; charset=UTF-8" }); downloadFile(blob, title, "md"); }, { loading: "Scraping editorial...", success: "Editorial scraped. Downloading...", error: "Something went wrong while scraping. See browser console for more detail." } ); } function Save_editorial($$anchor, $$props) { push($$props, false); async function findEditorial() { const editorialEl = await findElement(".flexlayout__tab:has(#editorial-quick-navigation) div.WRmCx", { timeout: 2e3 }); return editorialEl; } init(); Button($$anchor, { onclick: () => downloadEditorial(findEditorial, getTitle), variant: "orange", children: ($$anchor2, $$slotProps) => { var text$1 = text("Save Editorial as Markdown"); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } function Read_saved_editorial($$anchor, $$props) { push($$props, false); init(); Button($$anchor, { get href() { return CONFIG.EDITORIAL_READER_URL; }, variant: "green", children: ($$anchor2, $$slotProps) => { var text$1 = text("Read Saved Editorial"); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } var root_1$1 = /* @__PURE__ */ template(` `, 1); function EditorialButtons($$anchor) { ButtonGroup($$anchor, { style: "z-index: 10; position:relative; padding: 0.5rem", children: ($$anchor2, $$slotProps) => { var fragment_1 = root_1$1(); var node = first_child(fragment_1); Find_editorial_screenshot(node, {}); var node_1 = sibling(node, 2); Save_editorial(node_1, {}); var node_2 = sibling(node_1, 2); Read_saved_editorial(node_2, {}); append($$anchor2, fragment_1); }, $$slots: { default: true } }); } async function initEditorialTab() { const editorialTab = await findElement( ".flexlayout__tab:has(div.bg-blocker, #editorial-quick-navigation)", { timeout: 0, additionalRule: (el) => el.style.display !== "none" } ); const buttonsContainer = document.createElement("div"); buttonsContainer.style.cssText = "display: contents;"; buttonsContainer.setAttribute( "id", a(CONFIG.APP_NAME) + "-editorial" ); editorialTab.prepend(buttonsContainer); mount(EditorialButtons, { target: buttonsContainer }); } async function main$1() { const initPromises = []; initPromises.push(problemState.patchMonacoEditor()); initPromises.push(initDescriptionTab()); if (globalState.site === "global") { initPromises.push(initEditorialTab()); } await Promise.all(initPromises); } function getElementIndex(element) { if (!element.parentNode) throw new Error("Element has no parent node"); return Array.from(element.parentNode.children).indexOf(element); } function Save_explore_article($$anchor, $$props) { push($$props, false); async function findExploreEditorial() { return await findElement("div.block-markdown"); } async function getExploreTitle() { var _a2, _b; const tocContainer = await findElement("div.list-group:not(.item-list-group)"); const titleContainer = tocContainer.querySelector(".list-group-item .selected"); if (!titleContainer) { throw new Error("Title container not found"); } const title = ((_b = (_a2 = titleContainer.querySelector(".title")) == null ? void 0 : _a2.textContent) == null ? void 0 : _b.trim()) ?? ""; const articleNumber = getElementIndex(titleContainer) + 1; const chapterEl = titleContainer.closest("div.chapter-item"); if (!chapterEl) { throw new Error("Chapter not found"); } const chapterNumber = getElementIndex(chapterEl); return `${chapterNumber}.${articleNumber} ${title}`; } init(); Button($$anchor, { onclick: () => downloadEditorial(findExploreEditorial, getExploreTitle), children: ($$anchor2, $$slotProps) => { var text$1 = text("Save Article as Markdown"); append($$anchor2, text$1); }, $$slots: { default: true } }); pop(); } var root_1 = /* @__PURE__ */ template(` `, 1); function ExploreButtons($$anchor) { ButtonGroup($$anchor, { children: ($$anchor2, $$slotProps) => { var fragment_1 = root_1(); var node = first_child(fragment_1); Save_explore_article(node, {}); var node_1 = sibling(node, 2); Read_saved_editorial(node_1, {}); append($$anchor2, fragment_1); }, $$slots: { default: true } }); } async function main() { const toolbar = await findElement("div.left-side", { timeout: 0 }); const container = document.createElement("div"); container.style.cssText = "display: contents;"; toolbar.append(container); mount(ExploreButtons, { target: container }); } mount(Toaster, { target: document.body, props: { richColors: true, position: "top-center" } }); const url = window.location.href; const problemPageRegex = /https?:\/\/leetcode\.com\/problems\/.*|https?:\/\/leetcode\.cn\/problems\/.*/; const explorePageRegex = /https?:\/\/leetcode\.com\/explore\/learn\/card\/.*/; if (problemPageRegex.test(url)) { main$1(); } else if (explorePageRegex.test(url)) { main(); } })();