LeetCode Toolkit

Find & Save Editorial, Copy problem as Markdown or Download as Jupyter Notebook, Format on Save, Unlock IntelliSense

  1. // ==UserScript==
  2. // @name LeetCode Toolkit
  3. // @name:zh-CN LeetCode工具箱
  4. // @namespace https://github.com/eclipher/leetcode-toolkit
  5. // @version 2.5.5
  6. // @author eclipher
  7. // @description Find & Save Editorial, Copy problem as Markdown or Download as Jupyter Notebook, Format on Save, Unlock IntelliSense
  8. // @description:zh-CN 复制题目为 Markdown | 下载为 Jupyter Notebook | 保存时自动格式化 | 免费自动补全
  9. // @license MIT
  10. // @icon https://www.google.com/s2/favicons?sz=64&domain=leetcode.com
  11. // @homepage https://github.com/eclipher/leetcode-toolkit
  12. // @include /https?:\/\/leetcode\.com\/problems\/.*/
  13. // @include /https?:\/\/leetcode\.cn\/problems\/.*/
  14. // @include /https?:\/\/leetcode\.com\/explore\/learn\/card\/.*/
  15. // @exclude *://leetcode.com/problems/*/post-solution/*
  16. // @exclude *://leetcode.cn/problems/*/post-solution/*
  17. // @resource editorials https://raw.githubusercontent.com/akhilkammila/leetcode-screenshotter/refs/heads/main/ReadMe.md
  18. // @connect assets.leetcode.com
  19. // @connect *
  20. // @grant GM_addStyle
  21. // @grant GM_getResourceText
  22. // @grant GM_xmlhttpRequest
  23. // @grant unsafeWindow
  24. // ==/UserScript==
  25.  
  26. (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%} ');
  27.  
  28. (function () {
  29. 'use strict';
  30.  
  31. var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
  32. var __defProp = Object.defineProperty;
  33. var __typeError = (msg) => {
  34. throw TypeError(msg);
  35. };
  36. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  37. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  38. var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
  39. var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
  40. 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);
  41. var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
  42. var _a, _document, _subscribe, _name, _key, _toasts, _heights, _findToastIdx, _activeToasts, _site;
  43. const DEV = false;
  44. var is_array = Array.isArray;
  45. var index_of = Array.prototype.indexOf;
  46. var array_from = Array.from;
  47. var define_property = Object.defineProperty;
  48. var get_descriptor = Object.getOwnPropertyDescriptor;
  49. var get_descriptors = Object.getOwnPropertyDescriptors;
  50. var object_prototype = Object.prototype;
  51. var array_prototype = Array.prototype;
  52. var get_prototype_of = Object.getPrototypeOf;
  53. var is_extensible = Object.isExtensible;
  54. function is_function(thing) {
  55. return typeof thing === "function";
  56. }
  57. const noop = () => {
  58. };
  59. function run(fn) {
  60. return fn();
  61. }
  62. function run_all(arr) {
  63. for (var i2 = 0; i2 < arr.length; i2++) {
  64. arr[i2]();
  65. }
  66. }
  67. const DERIVED = 1 << 1;
  68. const EFFECT = 1 << 2;
  69. const RENDER_EFFECT = 1 << 3;
  70. const BLOCK_EFFECT = 1 << 4;
  71. const BRANCH_EFFECT = 1 << 5;
  72. const ROOT_EFFECT = 1 << 6;
  73. const BOUNDARY_EFFECT = 1 << 7;
  74. const UNOWNED = 1 << 8;
  75. const DISCONNECTED = 1 << 9;
  76. const CLEAN = 1 << 10;
  77. const DIRTY = 1 << 11;
  78. const MAYBE_DIRTY = 1 << 12;
  79. const INERT = 1 << 13;
  80. const DESTROYED = 1 << 14;
  81. const EFFECT_RAN = 1 << 15;
  82. const EFFECT_TRANSPARENT = 1 << 16;
  83. const LEGACY_DERIVED_PROP = 1 << 17;
  84. const HEAD_EFFECT = 1 << 19;
  85. const EFFECT_HAS_DERIVED = 1 << 20;
  86. const EFFECT_IS_UPDATING = 1 << 21;
  87. const STATE_SYMBOL = Symbol("$state");
  88. const LEGACY_PROPS = Symbol("legacy props");
  89. const LOADING_ATTR_SYMBOL = Symbol("");
  90. function equals(value) {
  91. return value === this.v;
  92. }
  93. function safe_not_equal(a2, b) {
  94. return a2 != a2 ? b == b : a2 !== b || a2 !== null && typeof a2 === "object" || typeof a2 === "function";
  95. }
  96. function safe_equals(value) {
  97. return !safe_not_equal(value, this.v);
  98. }
  99. function effect_in_teardown(rune) {
  100. {
  101. throw new Error(`https://svelte.dev/e/effect_in_teardown`);
  102. }
  103. }
  104. function effect_in_unowned_derived() {
  105. {
  106. throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`);
  107. }
  108. }
  109. function effect_orphan(rune) {
  110. {
  111. throw new Error(`https://svelte.dev/e/effect_orphan`);
  112. }
  113. }
  114. function effect_update_depth_exceeded() {
  115. {
  116. throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
  117. }
  118. }
  119. function props_invalid_value(key) {
  120. {
  121. throw new Error(`https://svelte.dev/e/props_invalid_value`);
  122. }
  123. }
  124. function state_descriptors_fixed() {
  125. {
  126. throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
  127. }
  128. }
  129. function state_prototype_fixed() {
  130. {
  131. throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
  132. }
  133. }
  134. function state_unsafe_mutation() {
  135. {
  136. throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
  137. }
  138. }
  139. let legacy_mode_flag = false;
  140. let tracing_mode_flag = false;
  141. function enable_legacy_mode_flag() {
  142. legacy_mode_flag = true;
  143. }
  144. const EACH_ITEM_REACTIVE = 1;
  145. const EACH_INDEX_REACTIVE = 1 << 1;
  146. const EACH_IS_CONTROLLED = 1 << 2;
  147. const EACH_IS_ANIMATED = 1 << 3;
  148. const EACH_ITEM_IMMUTABLE = 1 << 4;
  149. const PROPS_IS_IMMUTABLE = 1;
  150. const PROPS_IS_RUNES = 1 << 1;
  151. const PROPS_IS_UPDATED = 1 << 2;
  152. const PROPS_IS_BINDABLE = 1 << 3;
  153. const PROPS_IS_LAZY_INITIAL = 1 << 4;
  154. const TEMPLATE_FRAGMENT = 1;
  155. const TEMPLATE_USE_IMPORT_NODE = 1 << 1;
  156. const UNINITIALIZED = Symbol();
  157. const NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";
  158. function lifecycle_outside_component(name) {
  159. {
  160. throw new Error(`https://svelte.dev/e/lifecycle_outside_component`);
  161. }
  162. }
  163. let component_context = null;
  164. function set_component_context(context) {
  165. component_context = context;
  166. }
  167. function getContext(key) {
  168. const context_map = get_or_init_context_map();
  169. const result = (
  170. /** @type {T} */
  171. context_map.get(key)
  172. );
  173. return result;
  174. }
  175. function setContext(key, context) {
  176. const context_map = get_or_init_context_map();
  177. context_map.set(key, context);
  178. return context;
  179. }
  180. function hasContext(key) {
  181. const context_map = get_or_init_context_map();
  182. return context_map.has(key);
  183. }
  184. function push(props, runes = false, fn) {
  185. var ctx = component_context = {
  186. p: component_context,
  187. c: null,
  188. d: false,
  189. e: null,
  190. m: false,
  191. s: props,
  192. x: null,
  193. l: null
  194. };
  195. if (legacy_mode_flag && !runes) {
  196. component_context.l = {
  197. s: null,
  198. u: null,
  199. r1: [],
  200. r2: source(false)
  201. };
  202. }
  203. teardown(() => {
  204. ctx.d = true;
  205. });
  206. }
  207. function pop(component2) {
  208. const context_stack_item = component_context;
  209. if (context_stack_item !== null) {
  210. const component_effects = context_stack_item.e;
  211. if (component_effects !== null) {
  212. var previous_effect = active_effect;
  213. var previous_reaction = active_reaction;
  214. context_stack_item.e = null;
  215. try {
  216. for (var i2 = 0; i2 < component_effects.length; i2++) {
  217. var component_effect = component_effects[i2];
  218. set_active_effect(component_effect.effect);
  219. set_active_reaction(component_effect.reaction);
  220. effect(component_effect.fn);
  221. }
  222. } finally {
  223. set_active_effect(previous_effect);
  224. set_active_reaction(previous_reaction);
  225. }
  226. }
  227. component_context = context_stack_item.p;
  228. context_stack_item.m = true;
  229. }
  230. return (
  231. /** @type {T} */
  232. {}
  233. );
  234. }
  235. function is_runes() {
  236. return !legacy_mode_flag || component_context !== null && component_context.l === null;
  237. }
  238. function get_or_init_context_map(name) {
  239. if (component_context === null) {
  240. lifecycle_outside_component();
  241. }
  242. return component_context.c ?? (component_context.c = new Map(get_parent_context(component_context) || void 0));
  243. }
  244. function get_parent_context(component_context2) {
  245. let parent = component_context2.p;
  246. while (parent !== null) {
  247. const context_map = parent.c;
  248. if (context_map !== null) {
  249. return context_map;
  250. }
  251. parent = parent.p;
  252. }
  253. return null;
  254. }
  255. function proxy(value) {
  256. if (typeof value !== "object" || value === null || STATE_SYMBOL in value) {
  257. return value;
  258. }
  259. const prototype = get_prototype_of(value);
  260. if (prototype !== object_prototype && prototype !== array_prototype) {
  261. return value;
  262. }
  263. var sources = /* @__PURE__ */ new Map();
  264. var is_proxied_array = is_array(value);
  265. var version = /* @__PURE__ */ state(0);
  266. var reaction = active_reaction;
  267. var with_parent = (fn) => {
  268. var previous_reaction = active_reaction;
  269. set_active_reaction(reaction);
  270. var result = fn();
  271. set_active_reaction(previous_reaction);
  272. return result;
  273. };
  274. if (is_proxied_array) {
  275. sources.set("length", /* @__PURE__ */ state(
  276. /** @type {any[]} */
  277. value.length
  278. ));
  279. }
  280. return new Proxy(
  281. /** @type {any} */
  282. value,
  283. {
  284. defineProperty(_, prop2, descriptor) {
  285. if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) {
  286. state_descriptors_fixed();
  287. }
  288. var s = sources.get(prop2);
  289. if (s === void 0) {
  290. s = with_parent(() => /* @__PURE__ */ state(descriptor.value));
  291. sources.set(prop2, s);
  292. } else {
  293. set(
  294. s,
  295. with_parent(() => proxy(descriptor.value))
  296. );
  297. }
  298. return true;
  299. },
  300. deleteProperty(target, prop2) {
  301. var s = sources.get(prop2);
  302. if (s === void 0) {
  303. if (prop2 in target) {
  304. sources.set(
  305. prop2,
  306. with_parent(() => /* @__PURE__ */ state(UNINITIALIZED))
  307. );
  308. update_version(version);
  309. }
  310. } else {
  311. if (is_proxied_array && typeof prop2 === "string") {
  312. var ls = (
  313. /** @type {Source<number>} */
  314. sources.get("length")
  315. );
  316. var n = Number(prop2);
  317. if (Number.isInteger(n) && n < ls.v) {
  318. set(ls, n);
  319. }
  320. }
  321. set(s, UNINITIALIZED);
  322. update_version(version);
  323. }
  324. return true;
  325. },
  326. get(target, prop2, receiver) {
  327. var _a2;
  328. if (prop2 === STATE_SYMBOL) {
  329. return value;
  330. }
  331. var s = sources.get(prop2);
  332. var exists = prop2 in target;
  333. if (s === void 0 && (!exists || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable))) {
  334. s = with_parent(() => /* @__PURE__ */ state(proxy(exists ? target[prop2] : UNINITIALIZED)));
  335. sources.set(prop2, s);
  336. }
  337. if (s !== void 0) {
  338. var v2 = get(s);
  339. return v2 === UNINITIALIZED ? void 0 : v2;
  340. }
  341. return Reflect.get(target, prop2, receiver);
  342. },
  343. getOwnPropertyDescriptor(target, prop2) {
  344. var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
  345. if (descriptor && "value" in descriptor) {
  346. var s = sources.get(prop2);
  347. if (s) descriptor.value = get(s);
  348. } else if (descriptor === void 0) {
  349. var source2 = sources.get(prop2);
  350. var value2 = source2 == null ? void 0 : source2.v;
  351. if (source2 !== void 0 && value2 !== UNINITIALIZED) {
  352. return {
  353. enumerable: true,
  354. configurable: true,
  355. value: value2,
  356. writable: true
  357. };
  358. }
  359. }
  360. return descriptor;
  361. },
  362. has(target, prop2) {
  363. var _a2;
  364. if (prop2 === STATE_SYMBOL) {
  365. return true;
  366. }
  367. var s = sources.get(prop2);
  368. var has2 = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2);
  369. if (s !== void 0 || active_effect !== null && (!has2 || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable))) {
  370. if (s === void 0) {
  371. s = with_parent(() => /* @__PURE__ */ state(has2 ? proxy(target[prop2]) : UNINITIALIZED));
  372. sources.set(prop2, s);
  373. }
  374. var value2 = get(s);
  375. if (value2 === UNINITIALIZED) {
  376. return false;
  377. }
  378. }
  379. return has2;
  380. },
  381. set(target, prop2, value2, receiver) {
  382. var _a2;
  383. var s = sources.get(prop2);
  384. var has2 = prop2 in target;
  385. if (is_proxied_array && prop2 === "length") {
  386. for (var i2 = value2; i2 < /** @type {Source<number>} */
  387. s.v; i2 += 1) {
  388. var other_s = sources.get(i2 + "");
  389. if (other_s !== void 0) {
  390. set(other_s, UNINITIALIZED);
  391. } else if (i2 in target) {
  392. other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED));
  393. sources.set(i2 + "", other_s);
  394. }
  395. }
  396. }
  397. if (s === void 0) {
  398. if (!has2 || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable)) {
  399. s = with_parent(() => /* @__PURE__ */ state(void 0));
  400. set(
  401. s,
  402. with_parent(() => proxy(value2))
  403. );
  404. sources.set(prop2, s);
  405. }
  406. } else {
  407. has2 = s.v !== UNINITIALIZED;
  408. set(
  409. s,
  410. with_parent(() => proxy(value2))
  411. );
  412. }
  413. var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
  414. if (descriptor == null ? void 0 : descriptor.set) {
  415. descriptor.set.call(receiver, value2);
  416. }
  417. if (!has2) {
  418. if (is_proxied_array && typeof prop2 === "string") {
  419. var ls = (
  420. /** @type {Source<number>} */
  421. sources.get("length")
  422. );
  423. var n = Number(prop2);
  424. if (Number.isInteger(n) && n >= ls.v) {
  425. set(ls, n + 1);
  426. }
  427. }
  428. update_version(version);
  429. }
  430. return true;
  431. },
  432. ownKeys(target) {
  433. get(version);
  434. var own_keys = Reflect.ownKeys(target).filter((key2) => {
  435. var source3 = sources.get(key2);
  436. return source3 === void 0 || source3.v !== UNINITIALIZED;
  437. });
  438. for (var [key, source2] of sources) {
  439. if (source2.v !== UNINITIALIZED && !(key in target)) {
  440. own_keys.push(key);
  441. }
  442. }
  443. return own_keys;
  444. },
  445. setPrototypeOf() {
  446. state_prototype_fixed();
  447. }
  448. }
  449. );
  450. }
  451. function update_version(signal, d = 1) {
  452. set(signal, signal.v + d);
  453. }
  454. // @__NO_SIDE_EFFECTS__
  455. function derived(fn) {
  456. var flags = DERIVED | DIRTY;
  457. var parent_derived = active_reaction !== null && (active_reaction.f & DERIVED) !== 0 ? (
  458. /** @type {Derived} */
  459. active_reaction
  460. ) : null;
  461. if (active_effect === null || parent_derived !== null && (parent_derived.f & UNOWNED) !== 0) {
  462. flags |= UNOWNED;
  463. } else {
  464. active_effect.f |= EFFECT_HAS_DERIVED;
  465. }
  466. const signal = {
  467. ctx: component_context,
  468. deps: null,
  469. effects: null,
  470. equals,
  471. f: flags,
  472. fn,
  473. reactions: null,
  474. rv: 0,
  475. v: (
  476. /** @type {V} */
  477. null
  478. ),
  479. wv: 0,
  480. parent: parent_derived ?? active_effect
  481. };
  482. return signal;
  483. }
  484. // @__NO_SIDE_EFFECTS__
  485. function user_derived(fn) {
  486. const d = /* @__PURE__ */ derived(fn);
  487. push_reaction_value(d);
  488. return d;
  489. }
  490. // @__NO_SIDE_EFFECTS__
  491. function derived_safe_equal(fn) {
  492. const signal = /* @__PURE__ */ derived(fn);
  493. signal.equals = safe_equals;
  494. return signal;
  495. }
  496. function destroy_derived_effects(derived2) {
  497. var effects = derived2.effects;
  498. if (effects !== null) {
  499. derived2.effects = null;
  500. for (var i2 = 0; i2 < effects.length; i2 += 1) {
  501. destroy_effect(
  502. /** @type {Effect} */
  503. effects[i2]
  504. );
  505. }
  506. }
  507. }
  508. function get_derived_parent_effect(derived2) {
  509. var parent = derived2.parent;
  510. while (parent !== null) {
  511. if ((parent.f & DERIVED) === 0) {
  512. return (
  513. /** @type {Effect} */
  514. parent
  515. );
  516. }
  517. parent = parent.parent;
  518. }
  519. return null;
  520. }
  521. function execute_derived(derived2) {
  522. var value;
  523. var prev_active_effect = active_effect;
  524. set_active_effect(get_derived_parent_effect(derived2));
  525. {
  526. try {
  527. destroy_derived_effects(derived2);
  528. value = update_reaction(derived2);
  529. } finally {
  530. set_active_effect(prev_active_effect);
  531. }
  532. }
  533. return value;
  534. }
  535. function update_derived(derived2) {
  536. var value = execute_derived(derived2);
  537. var status = (skip_reaction || (derived2.f & UNOWNED) !== 0) && derived2.deps !== null ? MAYBE_DIRTY : CLEAN;
  538. set_signal_status(derived2, status);
  539. if (!derived2.equals(value)) {
  540. derived2.v = value;
  541. derived2.wv = increment_write_version();
  542. }
  543. }
  544. const old_values = /* @__PURE__ */ new Map();
  545. function source(v2, stack) {
  546. var signal = {
  547. f: 0,
  548. // TODO ideally we could skip this altogether, but it causes type errors
  549. v: v2,
  550. reactions: null,
  551. equals,
  552. rv: 0,
  553. wv: 0
  554. };
  555. return signal;
  556. }
  557. // @__NO_SIDE_EFFECTS__
  558. function state(v2, stack) {
  559. const s = source(v2);
  560. push_reaction_value(s);
  561. return s;
  562. }
  563. // @__NO_SIDE_EFFECTS__
  564. function mutable_source(initial_value, immutable = false) {
  565. var _a2;
  566. const s = source(initial_value);
  567. if (!immutable) {
  568. s.equals = safe_equals;
  569. }
  570. if (legacy_mode_flag && component_context !== null && component_context.l !== null) {
  571. ((_a2 = component_context.l).s ?? (_a2.s = [])).push(s);
  572. }
  573. return s;
  574. }
  575. function set(source2, value, should_proxy = false) {
  576. if (active_reaction !== null && !untracking && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT)) !== 0 && !(reaction_sources == null ? void 0 : reaction_sources.includes(source2))) {
  577. state_unsafe_mutation();
  578. }
  579. let new_value = should_proxy ? proxy(value) : value;
  580. return internal_set(source2, new_value);
  581. }
  582. function internal_set(source2, value) {
  583. if (!source2.equals(value)) {
  584. var old_value = source2.v;
  585. if (is_destroying_effect) {
  586. old_values.set(source2, value);
  587. } else {
  588. old_values.set(source2, old_value);
  589. }
  590. source2.v = value;
  591. if ((source2.f & DERIVED) !== 0) {
  592. if ((source2.f & DIRTY) !== 0) {
  593. execute_derived(
  594. /** @type {Derived} */
  595. source2
  596. );
  597. }
  598. set_signal_status(source2, (source2.f & UNOWNED) === 0 ? CLEAN : MAYBE_DIRTY);
  599. }
  600. source2.wv = increment_write_version();
  601. mark_reactions(source2, DIRTY);
  602. if (is_runes() && active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) {
  603. if (untracked_writes === null) {
  604. set_untracked_writes([source2]);
  605. } else {
  606. untracked_writes.push(source2);
  607. }
  608. }
  609. }
  610. return value;
  611. }
  612. function mark_reactions(signal, status) {
  613. var reactions = signal.reactions;
  614. if (reactions === null) return;
  615. var runes = is_runes();
  616. var length = reactions.length;
  617. for (var i2 = 0; i2 < length; i2++) {
  618. var reaction = reactions[i2];
  619. var flags = reaction.f;
  620. if ((flags & DIRTY) !== 0) continue;
  621. if (!runes && reaction === active_effect) continue;
  622. set_signal_status(reaction, status);
  623. if ((flags & (CLEAN | UNOWNED)) !== 0) {
  624. if ((flags & DERIVED) !== 0) {
  625. mark_reactions(
  626. /** @type {Derived} */
  627. reaction,
  628. MAYBE_DIRTY
  629. );
  630. } else {
  631. schedule_effect(
  632. /** @type {Effect} */
  633. reaction
  634. );
  635. }
  636. }
  637. }
  638. }
  639. let hydrating = false;
  640. var $window;
  641. var is_firefox;
  642. var first_child_getter;
  643. var next_sibling_getter;
  644. function init_operations() {
  645. if ($window !== void 0) {
  646. return;
  647. }
  648. $window = window;
  649. is_firefox = /Firefox/.test(navigator.userAgent);
  650. var element_prototype = Element.prototype;
  651. var node_prototype = Node.prototype;
  652. var text_prototype = Text.prototype;
  653. first_child_getter = get_descriptor(node_prototype, "firstChild").get;
  654. next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
  655. if (is_extensible(element_prototype)) {
  656. element_prototype.__click = void 0;
  657. element_prototype.__className = void 0;
  658. element_prototype.__attributes = null;
  659. element_prototype.__style = void 0;
  660. element_prototype.__e = void 0;
  661. }
  662. if (is_extensible(text_prototype)) {
  663. text_prototype.__t = void 0;
  664. }
  665. }
  666. function create_text(value = "") {
  667. return document.createTextNode(value);
  668. }
  669. // @__NO_SIDE_EFFECTS__
  670. function get_first_child(node) {
  671. return first_child_getter.call(node);
  672. }
  673. // @__NO_SIDE_EFFECTS__
  674. function get_next_sibling(node) {
  675. return next_sibling_getter.call(node);
  676. }
  677. function child(node, is_text) {
  678. {
  679. return /* @__PURE__ */ get_first_child(node);
  680. }
  681. }
  682. function first_child(fragment, is_text) {
  683. {
  684. var first = (
  685. /** @type {DocumentFragment} */
  686. /* @__PURE__ */ get_first_child(
  687. /** @type {Node} */
  688. fragment
  689. )
  690. );
  691. if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first);
  692. return first;
  693. }
  694. }
  695. function sibling(node, count = 1, is_text = false) {
  696. let next_sibling = node;
  697. while (count--) {
  698. next_sibling = /** @type {TemplateNode} */
  699. /* @__PURE__ */ get_next_sibling(next_sibling);
  700. }
  701. {
  702. return next_sibling;
  703. }
  704. }
  705. function clear_text_content(node) {
  706. node.textContent = "";
  707. }
  708. function validate_effect(rune) {
  709. if (active_effect === null && active_reaction === null) {
  710. effect_orphan();
  711. }
  712. if (active_reaction !== null && (active_reaction.f & UNOWNED) !== 0 && active_effect === null) {
  713. effect_in_unowned_derived();
  714. }
  715. if (is_destroying_effect) {
  716. effect_in_teardown();
  717. }
  718. }
  719. function push_effect(effect2, parent_effect) {
  720. var parent_last = parent_effect.last;
  721. if (parent_last === null) {
  722. parent_effect.last = parent_effect.first = effect2;
  723. } else {
  724. parent_last.next = effect2;
  725. effect2.prev = parent_last;
  726. parent_effect.last = effect2;
  727. }
  728. }
  729. function create_effect(type, fn, sync, push2 = true) {
  730. var parent = active_effect;
  731. var effect2 = {
  732. ctx: component_context,
  733. deps: null,
  734. nodes_start: null,
  735. nodes_end: null,
  736. f: type | DIRTY,
  737. first: null,
  738. fn,
  739. last: null,
  740. next: null,
  741. parent,
  742. prev: null,
  743. teardown: null,
  744. transitions: null,
  745. wv: 0
  746. };
  747. if (sync) {
  748. try {
  749. update_effect(effect2);
  750. effect2.f |= EFFECT_RAN;
  751. } catch (e2) {
  752. destroy_effect(effect2);
  753. throw e2;
  754. }
  755. } else if (fn !== null) {
  756. schedule_effect(effect2);
  757. }
  758. var inert = sync && effect2.deps === null && effect2.first === null && effect2.nodes_start === null && effect2.teardown === null && (effect2.f & (EFFECT_HAS_DERIVED | BOUNDARY_EFFECT)) === 0;
  759. if (!inert && push2) {
  760. if (parent !== null) {
  761. push_effect(effect2, parent);
  762. }
  763. if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0) {
  764. var derived2 = (
  765. /** @type {Derived} */
  766. active_reaction
  767. );
  768. (derived2.effects ?? (derived2.effects = [])).push(effect2);
  769. }
  770. }
  771. return effect2;
  772. }
  773. function effect_tracking() {
  774. return active_reaction !== null && !untracking;
  775. }
  776. function teardown(fn) {
  777. const effect2 = create_effect(RENDER_EFFECT, null, false);
  778. set_signal_status(effect2, CLEAN);
  779. effect2.teardown = fn;
  780. return effect2;
  781. }
  782. function user_effect(fn) {
  783. validate_effect();
  784. var defer = active_effect !== null && (active_effect.f & BRANCH_EFFECT) !== 0 && component_context !== null && !component_context.m;
  785. if (defer) {
  786. var context = (
  787. /** @type {ComponentContext} */
  788. component_context
  789. );
  790. (context.e ?? (context.e = [])).push({
  791. fn,
  792. effect: active_effect,
  793. reaction: active_reaction
  794. });
  795. } else {
  796. var signal = effect(fn);
  797. return signal;
  798. }
  799. }
  800. function user_pre_effect(fn) {
  801. validate_effect();
  802. return render_effect(fn);
  803. }
  804. function component_root(fn) {
  805. const effect2 = create_effect(ROOT_EFFECT, fn, true);
  806. return (options = {}) => {
  807. return new Promise((fulfil) => {
  808. if (options.outro) {
  809. pause_effect(effect2, () => {
  810. destroy_effect(effect2);
  811. fulfil(void 0);
  812. });
  813. } else {
  814. destroy_effect(effect2);
  815. fulfil(void 0);
  816. }
  817. });
  818. };
  819. }
  820. function effect(fn) {
  821. return create_effect(EFFECT, fn, false);
  822. }
  823. function render_effect(fn) {
  824. return create_effect(RENDER_EFFECT, fn, true);
  825. }
  826. function template_effect(fn, thunks = [], d = derived) {
  827. const deriveds = thunks.map(d);
  828. const effect2 = () => fn(...deriveds.map(get));
  829. return block(effect2);
  830. }
  831. function block(fn, flags = 0) {
  832. return create_effect(RENDER_EFFECT | BLOCK_EFFECT | flags, fn, true);
  833. }
  834. function branch(fn, push2 = true) {
  835. return create_effect(RENDER_EFFECT | BRANCH_EFFECT, fn, true, push2);
  836. }
  837. function execute_effect_teardown(effect2) {
  838. var teardown2 = effect2.teardown;
  839. if (teardown2 !== null) {
  840. const previously_destroying_effect = is_destroying_effect;
  841. const previous_reaction = active_reaction;
  842. set_is_destroying_effect(true);
  843. set_active_reaction(null);
  844. try {
  845. teardown2.call(null);
  846. } finally {
  847. set_is_destroying_effect(previously_destroying_effect);
  848. set_active_reaction(previous_reaction);
  849. }
  850. }
  851. }
  852. function destroy_effect_children(signal, remove_dom = false) {
  853. var effect2 = signal.first;
  854. signal.first = signal.last = null;
  855. while (effect2 !== null) {
  856. var next2 = effect2.next;
  857. if ((effect2.f & ROOT_EFFECT) !== 0) {
  858. effect2.parent = null;
  859. } else {
  860. destroy_effect(effect2, remove_dom);
  861. }
  862. effect2 = next2;
  863. }
  864. }
  865. function destroy_block_effect_children(signal) {
  866. var effect2 = signal.first;
  867. while (effect2 !== null) {
  868. var next2 = effect2.next;
  869. if ((effect2.f & BRANCH_EFFECT) === 0) {
  870. destroy_effect(effect2);
  871. }
  872. effect2 = next2;
  873. }
  874. }
  875. function destroy_effect(effect2, remove_dom = true) {
  876. var removed = false;
  877. if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes_start !== null) {
  878. remove_effect_dom(
  879. effect2.nodes_start,
  880. /** @type {TemplateNode} */
  881. effect2.nodes_end
  882. );
  883. removed = true;
  884. }
  885. destroy_effect_children(effect2, remove_dom && !removed);
  886. remove_reactions(effect2, 0);
  887. set_signal_status(effect2, DESTROYED);
  888. var transitions = effect2.transitions;
  889. if (transitions !== null) {
  890. for (const transition of transitions) {
  891. transition.stop();
  892. }
  893. }
  894. execute_effect_teardown(effect2);
  895. var parent = effect2.parent;
  896. if (parent !== null && parent.first !== null) {
  897. unlink_effect(effect2);
  898. }
  899. effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes_start = effect2.nodes_end = null;
  900. }
  901. function remove_effect_dom(node, end) {
  902. while (node !== null) {
  903. var next2 = node === end ? null : (
  904. /** @type {TemplateNode} */
  905. /* @__PURE__ */ get_next_sibling(node)
  906. );
  907. node.remove();
  908. node = next2;
  909. }
  910. }
  911. function unlink_effect(effect2) {
  912. var parent = effect2.parent;
  913. var prev = effect2.prev;
  914. var next2 = effect2.next;
  915. if (prev !== null) prev.next = next2;
  916. if (next2 !== null) next2.prev = prev;
  917. if (parent !== null) {
  918. if (parent.first === effect2) parent.first = next2;
  919. if (parent.last === effect2) parent.last = prev;
  920. }
  921. }
  922. function pause_effect(effect2, callback) {
  923. var transitions = [];
  924. pause_children(effect2, transitions, true);
  925. run_out_transitions(transitions, () => {
  926. destroy_effect(effect2);
  927. if (callback) callback();
  928. });
  929. }
  930. function run_out_transitions(transitions, fn) {
  931. var remaining = transitions.length;
  932. if (remaining > 0) {
  933. var check = () => --remaining || fn();
  934. for (var transition of transitions) {
  935. transition.out(check);
  936. }
  937. } else {
  938. fn();
  939. }
  940. }
  941. function pause_children(effect2, transitions, local) {
  942. if ((effect2.f & INERT) !== 0) return;
  943. effect2.f ^= INERT;
  944. if (effect2.transitions !== null) {
  945. for (const transition of effect2.transitions) {
  946. if (transition.is_global || local) {
  947. transitions.push(transition);
  948. }
  949. }
  950. }
  951. var child2 = effect2.first;
  952. while (child2 !== null) {
  953. var sibling2 = child2.next;
  954. var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
  955. pause_children(child2, transitions, transparent ? local : false);
  956. child2 = sibling2;
  957. }
  958. }
  959. function resume_effect(effect2) {
  960. resume_children(effect2, true);
  961. }
  962. function resume_children(effect2, local) {
  963. if ((effect2.f & INERT) === 0) return;
  964. effect2.f ^= INERT;
  965. if ((effect2.f & CLEAN) === 0) {
  966. effect2.f ^= CLEAN;
  967. }
  968. if (check_dirtiness(effect2)) {
  969. set_signal_status(effect2, DIRTY);
  970. schedule_effect(effect2);
  971. }
  972. var child2 = effect2.first;
  973. while (child2 !== null) {
  974. var sibling2 = child2.next;
  975. var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
  976. resume_children(child2, transparent ? local : false);
  977. child2 = sibling2;
  978. }
  979. if (effect2.transitions !== null) {
  980. for (const transition of effect2.transitions) {
  981. if (transition.is_global || local) {
  982. transition.in();
  983. }
  984. }
  985. }
  986. }
  987. let micro_tasks = [];
  988. let idle_tasks = [];
  989. function run_micro_tasks() {
  990. var tasks = micro_tasks;
  991. micro_tasks = [];
  992. run_all(tasks);
  993. }
  994. function run_idle_tasks() {
  995. var tasks = idle_tasks;
  996. idle_tasks = [];
  997. run_all(tasks);
  998. }
  999. function queue_micro_task(fn) {
  1000. if (micro_tasks.length === 0) {
  1001. queueMicrotask(run_micro_tasks);
  1002. }
  1003. micro_tasks.push(fn);
  1004. }
  1005. function flush_tasks() {
  1006. if (micro_tasks.length > 0) {
  1007. run_micro_tasks();
  1008. }
  1009. if (idle_tasks.length > 0) {
  1010. run_idle_tasks();
  1011. }
  1012. }
  1013. let is_throwing_error = false;
  1014. let is_flushing = false;
  1015. let last_scheduled_effect = null;
  1016. let is_updating_effect = false;
  1017. let is_destroying_effect = false;
  1018. function set_is_destroying_effect(value) {
  1019. is_destroying_effect = value;
  1020. }
  1021. let queued_root_effects = [];
  1022. let active_reaction = null;
  1023. let untracking = false;
  1024. function set_active_reaction(reaction) {
  1025. active_reaction = reaction;
  1026. }
  1027. let active_effect = null;
  1028. function set_active_effect(effect2) {
  1029. active_effect = effect2;
  1030. }
  1031. let reaction_sources = null;
  1032. function push_reaction_value(value) {
  1033. if (active_reaction !== null && active_reaction.f & EFFECT_IS_UPDATING) {
  1034. if (reaction_sources === null) {
  1035. reaction_sources = [value];
  1036. } else {
  1037. reaction_sources.push(value);
  1038. }
  1039. }
  1040. }
  1041. let new_deps = null;
  1042. let skipped_deps = 0;
  1043. let untracked_writes = null;
  1044. function set_untracked_writes(value) {
  1045. untracked_writes = value;
  1046. }
  1047. let write_version = 1;
  1048. let read_version = 0;
  1049. let skip_reaction = false;
  1050. function increment_write_version() {
  1051. return ++write_version;
  1052. }
  1053. function check_dirtiness(reaction) {
  1054. var _a2;
  1055. var flags = reaction.f;
  1056. if ((flags & DIRTY) !== 0) {
  1057. return true;
  1058. }
  1059. if ((flags & MAYBE_DIRTY) !== 0) {
  1060. var dependencies = reaction.deps;
  1061. var is_unowned = (flags & UNOWNED) !== 0;
  1062. if (dependencies !== null) {
  1063. var i2;
  1064. var dependency;
  1065. var is_disconnected = (flags & DISCONNECTED) !== 0;
  1066. var is_unowned_connected = is_unowned && active_effect !== null && !skip_reaction;
  1067. var length = dependencies.length;
  1068. if (is_disconnected || is_unowned_connected) {
  1069. var derived2 = (
  1070. /** @type {Derived} */
  1071. reaction
  1072. );
  1073. var parent = derived2.parent;
  1074. for (i2 = 0; i2 < length; i2++) {
  1075. dependency = dependencies[i2];
  1076. if (is_disconnected || !((_a2 = dependency == null ? void 0 : dependency.reactions) == null ? void 0 : _a2.includes(derived2))) {
  1077. (dependency.reactions ?? (dependency.reactions = [])).push(derived2);
  1078. }
  1079. }
  1080. if (is_disconnected) {
  1081. derived2.f ^= DISCONNECTED;
  1082. }
  1083. if (is_unowned_connected && parent !== null && (parent.f & UNOWNED) === 0) {
  1084. derived2.f ^= UNOWNED;
  1085. }
  1086. }
  1087. for (i2 = 0; i2 < length; i2++) {
  1088. dependency = dependencies[i2];
  1089. if (check_dirtiness(
  1090. /** @type {Derived} */
  1091. dependency
  1092. )) {
  1093. update_derived(
  1094. /** @type {Derived} */
  1095. dependency
  1096. );
  1097. }
  1098. if (dependency.wv > reaction.wv) {
  1099. return true;
  1100. }
  1101. }
  1102. }
  1103. if (!is_unowned || active_effect !== null && !skip_reaction) {
  1104. set_signal_status(reaction, CLEAN);
  1105. }
  1106. }
  1107. return false;
  1108. }
  1109. function propagate_error(error, effect2) {
  1110. var current = effect2;
  1111. while (current !== null) {
  1112. if ((current.f & BOUNDARY_EFFECT) !== 0) {
  1113. try {
  1114. current.fn(error);
  1115. return;
  1116. } catch {
  1117. current.f ^= BOUNDARY_EFFECT;
  1118. }
  1119. }
  1120. current = current.parent;
  1121. }
  1122. is_throwing_error = false;
  1123. throw error;
  1124. }
  1125. function should_rethrow_error(effect2) {
  1126. return (effect2.f & DESTROYED) === 0 && (effect2.parent === null || (effect2.parent.f & BOUNDARY_EFFECT) === 0);
  1127. }
  1128. function handle_error(error, effect2, previous_effect, component_context2) {
  1129. if (is_throwing_error) {
  1130. if (previous_effect === null) {
  1131. is_throwing_error = false;
  1132. }
  1133. if (should_rethrow_error(effect2)) {
  1134. throw error;
  1135. }
  1136. return;
  1137. }
  1138. if (previous_effect !== null) {
  1139. is_throwing_error = true;
  1140. }
  1141. propagate_error(error, effect2);
  1142. if (should_rethrow_error(effect2)) {
  1143. throw error;
  1144. }
  1145. }
  1146. function schedule_possible_effect_self_invalidation(signal, effect2, root2 = true) {
  1147. var reactions = signal.reactions;
  1148. if (reactions === null) return;
  1149. for (var i2 = 0; i2 < reactions.length; i2++) {
  1150. var reaction = reactions[i2];
  1151. if (reaction_sources == null ? void 0 : reaction_sources.includes(signal)) continue;
  1152. if ((reaction.f & DERIVED) !== 0) {
  1153. schedule_possible_effect_self_invalidation(
  1154. /** @type {Derived} */
  1155. reaction,
  1156. effect2,
  1157. false
  1158. );
  1159. } else if (effect2 === reaction) {
  1160. if (root2) {
  1161. set_signal_status(reaction, DIRTY);
  1162. } else if ((reaction.f & CLEAN) !== 0) {
  1163. set_signal_status(reaction, MAYBE_DIRTY);
  1164. }
  1165. schedule_effect(
  1166. /** @type {Effect} */
  1167. reaction
  1168. );
  1169. }
  1170. }
  1171. }
  1172. function update_reaction(reaction) {
  1173. var _a2;
  1174. var previous_deps = new_deps;
  1175. var previous_skipped_deps = skipped_deps;
  1176. var previous_untracked_writes = untracked_writes;
  1177. var previous_reaction = active_reaction;
  1178. var previous_skip_reaction = skip_reaction;
  1179. var previous_reaction_sources = reaction_sources;
  1180. var previous_component_context = component_context;
  1181. var previous_untracking = untracking;
  1182. var flags = reaction.f;
  1183. new_deps = /** @type {null | Value[]} */
  1184. null;
  1185. skipped_deps = 0;
  1186. untracked_writes = null;
  1187. skip_reaction = (flags & UNOWNED) !== 0 && (untracking || !is_updating_effect || active_reaction === null);
  1188. active_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;
  1189. reaction_sources = null;
  1190. set_component_context(reaction.ctx);
  1191. untracking = false;
  1192. read_version++;
  1193. reaction.f |= EFFECT_IS_UPDATING;
  1194. try {
  1195. var result = (
  1196. /** @type {Function} */
  1197. (0, reaction.fn)()
  1198. );
  1199. var deps = reaction.deps;
  1200. if (new_deps !== null) {
  1201. var i2;
  1202. remove_reactions(reaction, skipped_deps);
  1203. if (deps !== null && skipped_deps > 0) {
  1204. deps.length = skipped_deps + new_deps.length;
  1205. for (i2 = 0; i2 < new_deps.length; i2++) {
  1206. deps[skipped_deps + i2] = new_deps[i2];
  1207. }
  1208. } else {
  1209. reaction.deps = deps = new_deps;
  1210. }
  1211. if (!skip_reaction) {
  1212. for (i2 = skipped_deps; i2 < deps.length; i2++) {
  1213. ((_a2 = deps[i2]).reactions ?? (_a2.reactions = [])).push(reaction);
  1214. }
  1215. }
  1216. } else if (deps !== null && skipped_deps < deps.length) {
  1217. remove_reactions(reaction, skipped_deps);
  1218. deps.length = skipped_deps;
  1219. }
  1220. if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) {
  1221. for (i2 = 0; i2 < /** @type {Source[]} */
  1222. untracked_writes.length; i2++) {
  1223. schedule_possible_effect_self_invalidation(
  1224. untracked_writes[i2],
  1225. /** @type {Effect} */
  1226. reaction
  1227. );
  1228. }
  1229. }
  1230. if (previous_reaction !== null && previous_reaction !== reaction) {
  1231. read_version++;
  1232. if (untracked_writes !== null) {
  1233. if (previous_untracked_writes === null) {
  1234. previous_untracked_writes = untracked_writes;
  1235. } else {
  1236. previous_untracked_writes.push(.../** @type {Source[]} */
  1237. untracked_writes);
  1238. }
  1239. }
  1240. }
  1241. return result;
  1242. } finally {
  1243. new_deps = previous_deps;
  1244. skipped_deps = previous_skipped_deps;
  1245. untracked_writes = previous_untracked_writes;
  1246. active_reaction = previous_reaction;
  1247. skip_reaction = previous_skip_reaction;
  1248. reaction_sources = previous_reaction_sources;
  1249. set_component_context(previous_component_context);
  1250. untracking = previous_untracking;
  1251. reaction.f ^= EFFECT_IS_UPDATING;
  1252. }
  1253. }
  1254. function remove_reaction(signal, dependency) {
  1255. let reactions = dependency.reactions;
  1256. if (reactions !== null) {
  1257. var index = index_of.call(reactions, signal);
  1258. if (index !== -1) {
  1259. var new_length = reactions.length - 1;
  1260. if (new_length === 0) {
  1261. reactions = dependency.reactions = null;
  1262. } else {
  1263. reactions[index] = reactions[new_length];
  1264. reactions.pop();
  1265. }
  1266. }
  1267. }
  1268. if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear
  1269. // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`
  1270. // allows us to skip the expensive work of disconnecting and immediately reconnecting it
  1271. (new_deps === null || !new_deps.includes(dependency))) {
  1272. set_signal_status(dependency, MAYBE_DIRTY);
  1273. if ((dependency.f & (UNOWNED | DISCONNECTED)) === 0) {
  1274. dependency.f ^= DISCONNECTED;
  1275. }
  1276. destroy_derived_effects(
  1277. /** @type {Derived} **/
  1278. dependency
  1279. );
  1280. remove_reactions(
  1281. /** @type {Derived} **/
  1282. dependency,
  1283. 0
  1284. );
  1285. }
  1286. }
  1287. function remove_reactions(signal, start_index) {
  1288. var dependencies = signal.deps;
  1289. if (dependencies === null) return;
  1290. for (var i2 = start_index; i2 < dependencies.length; i2++) {
  1291. remove_reaction(signal, dependencies[i2]);
  1292. }
  1293. }
  1294. function update_effect(effect2) {
  1295. var flags = effect2.f;
  1296. if ((flags & DESTROYED) !== 0) {
  1297. return;
  1298. }
  1299. set_signal_status(effect2, CLEAN);
  1300. var previous_effect = active_effect;
  1301. var previous_component_context = component_context;
  1302. var was_updating_effect = is_updating_effect;
  1303. active_effect = effect2;
  1304. is_updating_effect = true;
  1305. try {
  1306. if ((flags & BLOCK_EFFECT) !== 0) {
  1307. destroy_block_effect_children(effect2);
  1308. } else {
  1309. destroy_effect_children(effect2);
  1310. }
  1311. execute_effect_teardown(effect2);
  1312. var teardown2 = update_reaction(effect2);
  1313. effect2.teardown = typeof teardown2 === "function" ? teardown2 : null;
  1314. effect2.wv = write_version;
  1315. var deps = effect2.deps;
  1316. var dep;
  1317. if (DEV && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && deps !== null) ;
  1318. if (DEV) ;
  1319. } catch (error) {
  1320. handle_error(error, effect2, previous_effect, previous_component_context || effect2.ctx);
  1321. } finally {
  1322. is_updating_effect = was_updating_effect;
  1323. active_effect = previous_effect;
  1324. }
  1325. }
  1326. function infinite_loop_guard() {
  1327. try {
  1328. effect_update_depth_exceeded();
  1329. } catch (error) {
  1330. if (last_scheduled_effect !== null) {
  1331. {
  1332. handle_error(error, last_scheduled_effect, null);
  1333. }
  1334. } else {
  1335. throw error;
  1336. }
  1337. }
  1338. }
  1339. function flush_queued_root_effects() {
  1340. var was_updating_effect = is_updating_effect;
  1341. try {
  1342. var flush_count = 0;
  1343. is_updating_effect = true;
  1344. while (queued_root_effects.length > 0) {
  1345. if (flush_count++ > 1e3) {
  1346. infinite_loop_guard();
  1347. }
  1348. var root_effects = queued_root_effects;
  1349. var length = root_effects.length;
  1350. queued_root_effects = [];
  1351. for (var i2 = 0; i2 < length; i2++) {
  1352. var collected_effects = process_effects(root_effects[i2]);
  1353. flush_queued_effects(collected_effects);
  1354. }
  1355. old_values.clear();
  1356. }
  1357. } finally {
  1358. is_flushing = false;
  1359. is_updating_effect = was_updating_effect;
  1360. last_scheduled_effect = null;
  1361. }
  1362. }
  1363. function flush_queued_effects(effects) {
  1364. var length = effects.length;
  1365. if (length === 0) return;
  1366. for (var i2 = 0; i2 < length; i2++) {
  1367. var effect2 = effects[i2];
  1368. if ((effect2.f & (DESTROYED | INERT)) === 0) {
  1369. try {
  1370. if (check_dirtiness(effect2)) {
  1371. update_effect(effect2);
  1372. if (effect2.deps === null && effect2.first === null && effect2.nodes_start === null) {
  1373. if (effect2.teardown === null) {
  1374. unlink_effect(effect2);
  1375. } else {
  1376. effect2.fn = null;
  1377. }
  1378. }
  1379. }
  1380. } catch (error) {
  1381. handle_error(error, effect2, null, effect2.ctx);
  1382. }
  1383. }
  1384. }
  1385. }
  1386. function schedule_effect(signal) {
  1387. if (!is_flushing) {
  1388. is_flushing = true;
  1389. queueMicrotask(flush_queued_root_effects);
  1390. }
  1391. var effect2 = last_scheduled_effect = signal;
  1392. while (effect2.parent !== null) {
  1393. effect2 = effect2.parent;
  1394. var flags = effect2.f;
  1395. if ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {
  1396. if ((flags & CLEAN) === 0) return;
  1397. effect2.f ^= CLEAN;
  1398. }
  1399. }
  1400. queued_root_effects.push(effect2);
  1401. }
  1402. function process_effects(root2) {
  1403. var effects = [];
  1404. var effect2 = root2;
  1405. while (effect2 !== null) {
  1406. var flags = effect2.f;
  1407. var is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
  1408. var is_skippable_branch = is_branch && (flags & CLEAN) !== 0;
  1409. if (!is_skippable_branch && (flags & INERT) === 0) {
  1410. if ((flags & EFFECT) !== 0) {
  1411. effects.push(effect2);
  1412. } else if (is_branch) {
  1413. effect2.f ^= CLEAN;
  1414. } else {
  1415. try {
  1416. if (check_dirtiness(effect2)) {
  1417. update_effect(effect2);
  1418. }
  1419. } catch (error) {
  1420. handle_error(error, effect2, null, effect2.ctx);
  1421. }
  1422. }
  1423. var child2 = effect2.first;
  1424. if (child2 !== null) {
  1425. effect2 = child2;
  1426. continue;
  1427. }
  1428. }
  1429. var parent = effect2.parent;
  1430. effect2 = effect2.next;
  1431. while (effect2 === null && parent !== null) {
  1432. effect2 = parent.next;
  1433. parent = parent.parent;
  1434. }
  1435. }
  1436. return effects;
  1437. }
  1438. function flushSync(fn) {
  1439. var result;
  1440. while (true) {
  1441. flush_tasks();
  1442. if (queued_root_effects.length === 0) {
  1443. return (
  1444. /** @type {T} */
  1445. result
  1446. );
  1447. }
  1448. is_flushing = true;
  1449. flush_queued_root_effects();
  1450. }
  1451. }
  1452. async function tick() {
  1453. await Promise.resolve();
  1454. flushSync();
  1455. }
  1456. function get(signal) {
  1457. var flags = signal.f;
  1458. var is_derived = (flags & DERIVED) !== 0;
  1459. if (active_reaction !== null && !untracking) {
  1460. if (!(reaction_sources == null ? void 0 : reaction_sources.includes(signal))) {
  1461. var deps = active_reaction.deps;
  1462. if (signal.rv < read_version) {
  1463. signal.rv = read_version;
  1464. if (new_deps === null && deps !== null && deps[skipped_deps] === signal) {
  1465. skipped_deps++;
  1466. } else if (new_deps === null) {
  1467. new_deps = [signal];
  1468. } else if (!skip_reaction || !new_deps.includes(signal)) {
  1469. new_deps.push(signal);
  1470. }
  1471. }
  1472. }
  1473. } else if (is_derived && /** @type {Derived} */
  1474. signal.deps === null && /** @type {Derived} */
  1475. signal.effects === null) {
  1476. var derived2 = (
  1477. /** @type {Derived} */
  1478. signal
  1479. );
  1480. var parent = derived2.parent;
  1481. if (parent !== null && (parent.f & UNOWNED) === 0) {
  1482. derived2.f ^= UNOWNED;
  1483. }
  1484. }
  1485. if (is_derived) {
  1486. derived2 = /** @type {Derived} */
  1487. signal;
  1488. if (check_dirtiness(derived2)) {
  1489. update_derived(derived2);
  1490. }
  1491. }
  1492. if (is_destroying_effect && old_values.has(signal)) {
  1493. return old_values.get(signal);
  1494. }
  1495. return signal.v;
  1496. }
  1497. function untrack(fn) {
  1498. var previous_untracking = untracking;
  1499. try {
  1500. untracking = true;
  1501. return fn();
  1502. } finally {
  1503. untracking = previous_untracking;
  1504. }
  1505. }
  1506. const STATUS_MASK = -7169;
  1507. function set_signal_status(signal, status) {
  1508. signal.f = signal.f & STATUS_MASK | status;
  1509. }
  1510. function deep_read_state(value) {
  1511. if (typeof value !== "object" || !value || value instanceof EventTarget) {
  1512. return;
  1513. }
  1514. if (STATE_SYMBOL in value) {
  1515. deep_read(value);
  1516. } else if (!Array.isArray(value)) {
  1517. for (let key in value) {
  1518. const prop2 = value[key];
  1519. if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) {
  1520. deep_read(prop2);
  1521. }
  1522. }
  1523. }
  1524. }
  1525. function deep_read(value, visited = /* @__PURE__ */ new Set()) {
  1526. if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements
  1527. !(value instanceof EventTarget) && !visited.has(value)) {
  1528. visited.add(value);
  1529. if (value instanceof Date) {
  1530. value.getTime();
  1531. }
  1532. for (let key in value) {
  1533. try {
  1534. deep_read(value[key], visited);
  1535. } catch (e2) {
  1536. }
  1537. }
  1538. const proto = get_prototype_of(value);
  1539. if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) {
  1540. const descriptors = get_descriptors(proto);
  1541. for (let key in descriptors) {
  1542. const get2 = descriptors[key].get;
  1543. if (get2) {
  1544. try {
  1545. get2.call(value);
  1546. } catch (e2) {
  1547. }
  1548. }
  1549. }
  1550. }
  1551. }
  1552. }
  1553. function is_capture_event(name) {
  1554. return name.endsWith("capture") && name !== "gotpointercapture" && name !== "lostpointercapture";
  1555. }
  1556. const DELEGATED_EVENTS = [
  1557. "beforeinput",
  1558. "click",
  1559. "change",
  1560. "dblclick",
  1561. "contextmenu",
  1562. "focusin",
  1563. "focusout",
  1564. "input",
  1565. "keydown",
  1566. "keyup",
  1567. "mousedown",
  1568. "mousemove",
  1569. "mouseout",
  1570. "mouseover",
  1571. "mouseup",
  1572. "pointerdown",
  1573. "pointermove",
  1574. "pointerout",
  1575. "pointerover",
  1576. "pointerup",
  1577. "touchend",
  1578. "touchmove",
  1579. "touchstart"
  1580. ];
  1581. function is_delegated(event_name) {
  1582. return DELEGATED_EVENTS.includes(event_name);
  1583. }
  1584. const ATTRIBUTE_ALIASES = {
  1585. // no `class: 'className'` because we handle that separately
  1586. formnovalidate: "formNoValidate",
  1587. ismap: "isMap",
  1588. nomodule: "noModule",
  1589. playsinline: "playsInline",
  1590. readonly: "readOnly",
  1591. defaultvalue: "defaultValue",
  1592. defaultchecked: "defaultChecked",
  1593. srcobject: "srcObject",
  1594. novalidate: "noValidate",
  1595. allowfullscreen: "allowFullscreen",
  1596. disablepictureinpicture: "disablePictureInPicture",
  1597. disableremoteplayback: "disableRemotePlayback"
  1598. };
  1599. function normalize_attribute(name) {
  1600. name = name.toLowerCase();
  1601. return ATTRIBUTE_ALIASES[name] ?? name;
  1602. }
  1603. const PASSIVE_EVENTS = ["touchstart", "touchmove"];
  1604. function is_passive_event(name) {
  1605. return PASSIVE_EVENTS.includes(name);
  1606. }
  1607. function autofocus(dom, value) {
  1608. if (value) {
  1609. const body = document.body;
  1610. dom.autofocus = true;
  1611. queue_micro_task(() => {
  1612. if (document.activeElement === body) {
  1613. dom.focus();
  1614. }
  1615. });
  1616. }
  1617. }
  1618. function without_reactive_context(fn) {
  1619. var previous_reaction = active_reaction;
  1620. var previous_effect = active_effect;
  1621. set_active_reaction(null);
  1622. set_active_effect(null);
  1623. try {
  1624. return fn();
  1625. } finally {
  1626. set_active_reaction(previous_reaction);
  1627. set_active_effect(previous_effect);
  1628. }
  1629. }
  1630. const all_registered_events = /* @__PURE__ */ new Set();
  1631. const root_event_handles = /* @__PURE__ */ new Set();
  1632. function create_event(event_name, dom, handler, options = {}) {
  1633. function target_handler(event2) {
  1634. if (!options.capture) {
  1635. handle_event_propagation.call(dom, event2);
  1636. }
  1637. if (!event2.cancelBubble) {
  1638. return without_reactive_context(() => {
  1639. return handler == null ? void 0 : handler.call(this, event2);
  1640. });
  1641. }
  1642. }
  1643. if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
  1644. queue_micro_task(() => {
  1645. dom.addEventListener(event_name, target_handler, options);
  1646. });
  1647. } else {
  1648. dom.addEventListener(event_name, target_handler, options);
  1649. }
  1650. return target_handler;
  1651. }
  1652. function on(element, type, handler, options = {}) {
  1653. var target_handler = create_event(type, element, handler, options);
  1654. return () => {
  1655. element.removeEventListener(type, target_handler, options);
  1656. };
  1657. }
  1658. function event(event_name, dom, handler, capture, passive) {
  1659. var options = { capture, passive };
  1660. var target_handler = create_event(event_name, dom, handler, options);
  1661. if (dom === document.body || dom === window || dom === document) {
  1662. teardown(() => {
  1663. dom.removeEventListener(event_name, target_handler, options);
  1664. });
  1665. }
  1666. }
  1667. function delegate(events) {
  1668. for (var i2 = 0; i2 < events.length; i2++) {
  1669. all_registered_events.add(events[i2]);
  1670. }
  1671. for (var fn of root_event_handles) {
  1672. fn(events);
  1673. }
  1674. }
  1675. function handle_event_propagation(event2) {
  1676. var _a2;
  1677. var handler_element = this;
  1678. var owner_document = (
  1679. /** @type {Node} */
  1680. handler_element.ownerDocument
  1681. );
  1682. var event_name = event2.type;
  1683. var path = ((_a2 = event2.composedPath) == null ? void 0 : _a2.call(event2)) || [];
  1684. var current_target = (
  1685. /** @type {null | Element} */
  1686. path[0] || event2.target
  1687. );
  1688. var path_idx = 0;
  1689. var handled_at = event2.__root;
  1690. if (handled_at) {
  1691. var at_idx = path.indexOf(handled_at);
  1692. if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */
  1693. window)) {
  1694. event2.__root = handler_element;
  1695. return;
  1696. }
  1697. var handler_idx = path.indexOf(handler_element);
  1698. if (handler_idx === -1) {
  1699. return;
  1700. }
  1701. if (at_idx <= handler_idx) {
  1702. path_idx = at_idx;
  1703. }
  1704. }
  1705. current_target = /** @type {Element} */
  1706. path[path_idx] || event2.target;
  1707. if (current_target === handler_element) return;
  1708. define_property(event2, "currentTarget", {
  1709. configurable: true,
  1710. get() {
  1711. return current_target || owner_document;
  1712. }
  1713. });
  1714. var previous_reaction = active_reaction;
  1715. var previous_effect = active_effect;
  1716. set_active_reaction(null);
  1717. set_active_effect(null);
  1718. try {
  1719. var throw_error;
  1720. var other_errors = [];
  1721. while (current_target !== null) {
  1722. var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */
  1723. current_target.host || null;
  1724. try {
  1725. var delegated = current_target["__" + event_name];
  1726. if (delegated != null && (!/** @type {any} */
  1727. current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well
  1728. // -> the target could not have been disabled because it emits the event in the first place
  1729. event2.target === current_target)) {
  1730. if (is_array(delegated)) {
  1731. var [fn, ...data] = delegated;
  1732. fn.apply(current_target, [event2, ...data]);
  1733. } else {
  1734. delegated.call(current_target, event2);
  1735. }
  1736. }
  1737. } catch (error) {
  1738. if (throw_error) {
  1739. other_errors.push(error);
  1740. } else {
  1741. throw_error = error;
  1742. }
  1743. }
  1744. if (event2.cancelBubble || parent_element === handler_element || parent_element === null) {
  1745. break;
  1746. }
  1747. current_target = parent_element;
  1748. }
  1749. if (throw_error) {
  1750. for (let error of other_errors) {
  1751. queueMicrotask(() => {
  1752. throw error;
  1753. });
  1754. }
  1755. throw throw_error;
  1756. }
  1757. } finally {
  1758. event2.__root = handler_element;
  1759. delete event2.currentTarget;
  1760. set_active_reaction(previous_reaction);
  1761. set_active_effect(previous_effect);
  1762. }
  1763. }
  1764. function create_fragment_from_html(html) {
  1765. var elem = document.createElement("template");
  1766. elem.innerHTML = html;
  1767. return elem.content;
  1768. }
  1769. function assign_nodes(start, end) {
  1770. var effect2 = (
  1771. /** @type {Effect} */
  1772. active_effect
  1773. );
  1774. if (effect2.nodes_start === null) {
  1775. effect2.nodes_start = start;
  1776. effect2.nodes_end = end;
  1777. }
  1778. }
  1779. // @__NO_SIDE_EFFECTS__
  1780. function template(content, flags) {
  1781. var is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;
  1782. var use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;
  1783. var node;
  1784. var has_start = !content.startsWith("<!>");
  1785. return () => {
  1786. if (node === void 0) {
  1787. node = create_fragment_from_html(has_start ? content : "<!>" + content);
  1788. if (!is_fragment) node = /** @type {Node} */
  1789. /* @__PURE__ */ get_first_child(node);
  1790. }
  1791. var clone = (
  1792. /** @type {TemplateNode} */
  1793. use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)
  1794. );
  1795. if (is_fragment) {
  1796. var start = (
  1797. /** @type {TemplateNode} */
  1798. /* @__PURE__ */ get_first_child(clone)
  1799. );
  1800. var end = (
  1801. /** @type {TemplateNode} */
  1802. clone.lastChild
  1803. );
  1804. assign_nodes(start, end);
  1805. } else {
  1806. assign_nodes(clone, clone);
  1807. }
  1808. return clone;
  1809. };
  1810. }
  1811. // @__NO_SIDE_EFFECTS__
  1812. function ns_template(content, flags, ns = "svg") {
  1813. var has_start = !content.startsWith("<!>");
  1814. var wrapped = `<${ns}>${has_start ? content : "<!>" + content}</${ns}>`;
  1815. var node;
  1816. return () => {
  1817. if (!node) {
  1818. var fragment = (
  1819. /** @type {DocumentFragment} */
  1820. create_fragment_from_html(wrapped)
  1821. );
  1822. var root2 = (
  1823. /** @type {Element} */
  1824. /* @__PURE__ */ get_first_child(fragment)
  1825. );
  1826. {
  1827. node = /** @type {Element} */
  1828. /* @__PURE__ */ get_first_child(root2);
  1829. }
  1830. }
  1831. var clone = (
  1832. /** @type {TemplateNode} */
  1833. node.cloneNode(true)
  1834. );
  1835. {
  1836. assign_nodes(clone, clone);
  1837. }
  1838. return clone;
  1839. };
  1840. }
  1841. function text(value = "") {
  1842. {
  1843. var t = create_text(value + "");
  1844. assign_nodes(t, t);
  1845. return t;
  1846. }
  1847. }
  1848. function comment() {
  1849. var frag = document.createDocumentFragment();
  1850. var start = document.createComment("");
  1851. var anchor = create_text();
  1852. frag.append(start, anchor);
  1853. assign_nodes(start, anchor);
  1854. return frag;
  1855. }
  1856. function append(anchor, dom) {
  1857. if (anchor === null) {
  1858. return;
  1859. }
  1860. anchor.before(
  1861. /** @type {Node} */
  1862. dom
  1863. );
  1864. }
  1865. function set_text(text2, value) {
  1866. var str = value == null ? "" : typeof value === "object" ? value + "" : value;
  1867. if (str !== (text2.__t ?? (text2.__t = text2.nodeValue))) {
  1868. text2.__t = str;
  1869. text2.nodeValue = str + "";
  1870. }
  1871. }
  1872. function mount(component2, options) {
  1873. return _mount(component2, options);
  1874. }
  1875. const document_listeners = /* @__PURE__ */ new Map();
  1876. function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) {
  1877. init_operations();
  1878. var registered_events = /* @__PURE__ */ new Set();
  1879. var event_handle = (events2) => {
  1880. for (var i2 = 0; i2 < events2.length; i2++) {
  1881. var event_name = events2[i2];
  1882. if (registered_events.has(event_name)) continue;
  1883. registered_events.add(event_name);
  1884. var passive = is_passive_event(event_name);
  1885. target.addEventListener(event_name, handle_event_propagation, { passive });
  1886. var n = document_listeners.get(event_name);
  1887. if (n === void 0) {
  1888. document.addEventListener(event_name, handle_event_propagation, { passive });
  1889. document_listeners.set(event_name, 1);
  1890. } else {
  1891. document_listeners.set(event_name, n + 1);
  1892. }
  1893. }
  1894. };
  1895. event_handle(array_from(all_registered_events));
  1896. root_event_handles.add(event_handle);
  1897. var component2 = void 0;
  1898. var unmount = component_root(() => {
  1899. var anchor_node = anchor ?? target.appendChild(create_text());
  1900. branch(() => {
  1901. if (context) {
  1902. push({});
  1903. var ctx = (
  1904. /** @type {ComponentContext} */
  1905. component_context
  1906. );
  1907. ctx.c = context;
  1908. }
  1909. if (events) {
  1910. props.$$events = events;
  1911. }
  1912. component2 = Component(anchor_node, props) || {};
  1913. if (context) {
  1914. pop();
  1915. }
  1916. });
  1917. return () => {
  1918. var _a2;
  1919. for (var event_name of registered_events) {
  1920. target.removeEventListener(event_name, handle_event_propagation);
  1921. var n = (
  1922. /** @type {number} */
  1923. document_listeners.get(event_name)
  1924. );
  1925. if (--n === 0) {
  1926. document.removeEventListener(event_name, handle_event_propagation);
  1927. document_listeners.delete(event_name);
  1928. } else {
  1929. document_listeners.set(event_name, n);
  1930. }
  1931. }
  1932. root_event_handles.delete(event_handle);
  1933. if (anchor_node !== anchor) {
  1934. (_a2 = anchor_node.parentNode) == null ? void 0 : _a2.removeChild(anchor_node);
  1935. }
  1936. };
  1937. });
  1938. mounted_components.set(component2, unmount);
  1939. return component2;
  1940. }
  1941. let mounted_components = /* @__PURE__ */ new WeakMap();
  1942. function if_block(node, fn, [root_index, hydrate_index] = [0, 0]) {
  1943. var anchor = node;
  1944. var consequent_effect = null;
  1945. var alternate_effect = null;
  1946. var condition = UNINITIALIZED;
  1947. var flags = root_index > 0 ? EFFECT_TRANSPARENT : 0;
  1948. var has_branch = false;
  1949. const set_branch = (fn2, flag = true) => {
  1950. has_branch = true;
  1951. update_branch(flag, fn2);
  1952. };
  1953. const update_branch = (new_condition, fn2) => {
  1954. if (condition === (condition = new_condition)) return;
  1955. if (condition) {
  1956. if (consequent_effect) {
  1957. resume_effect(consequent_effect);
  1958. } else if (fn2) {
  1959. consequent_effect = branch(() => fn2(anchor));
  1960. }
  1961. if (alternate_effect) {
  1962. pause_effect(alternate_effect, () => {
  1963. alternate_effect = null;
  1964. });
  1965. }
  1966. } else {
  1967. if (alternate_effect) {
  1968. resume_effect(alternate_effect);
  1969. } else if (fn2) {
  1970. alternate_effect = branch(() => fn2(anchor, [root_index + 1, hydrate_index]));
  1971. }
  1972. if (consequent_effect) {
  1973. pause_effect(consequent_effect, () => {
  1974. consequent_effect = null;
  1975. });
  1976. }
  1977. }
  1978. };
  1979. block(() => {
  1980. has_branch = false;
  1981. fn(set_branch);
  1982. if (!has_branch) {
  1983. update_branch(null, null);
  1984. }
  1985. }, flags);
  1986. }
  1987. function pause_effects(state2, items, controlled_anchor, items_map) {
  1988. var transitions = [];
  1989. var length = items.length;
  1990. for (var i2 = 0; i2 < length; i2++) {
  1991. pause_children(items[i2].e, transitions, true);
  1992. }
  1993. var is_controlled = length > 0 && transitions.length === 0 && controlled_anchor !== null;
  1994. if (is_controlled) {
  1995. var parent_node = (
  1996. /** @type {Element} */
  1997. /** @type {Element} */
  1998. controlled_anchor.parentNode
  1999. );
  2000. clear_text_content(parent_node);
  2001. parent_node.append(
  2002. /** @type {Element} */
  2003. controlled_anchor
  2004. );
  2005. items_map.clear();
  2006. link(state2, items[0].prev, items[length - 1].next);
  2007. }
  2008. run_out_transitions(transitions, () => {
  2009. for (var i3 = 0; i3 < length; i3++) {
  2010. var item = items[i3];
  2011. if (!is_controlled) {
  2012. items_map.delete(item.k);
  2013. link(state2, item.prev, item.next);
  2014. }
  2015. destroy_effect(item.e, !is_controlled);
  2016. }
  2017. });
  2018. }
  2019. function each(node, flags, get_collection, get_key, render_fn, fallback_fn = null) {
  2020. var anchor = node;
  2021. var state2 = { flags, items: /* @__PURE__ */ new Map(), first: null };
  2022. var is_controlled = (flags & EACH_IS_CONTROLLED) !== 0;
  2023. if (is_controlled) {
  2024. var parent_node = (
  2025. /** @type {Element} */
  2026. node
  2027. );
  2028. anchor = parent_node.appendChild(create_text());
  2029. }
  2030. var fallback = null;
  2031. var was_empty = false;
  2032. var each_array = /* @__PURE__ */ derived_safe_equal(() => {
  2033. var collection = get_collection();
  2034. return is_array(collection) ? collection : collection == null ? [] : array_from(collection);
  2035. });
  2036. block(() => {
  2037. var array = get(each_array);
  2038. var length = array.length;
  2039. if (was_empty && length === 0) {
  2040. return;
  2041. }
  2042. was_empty = length === 0;
  2043. {
  2044. reconcile(array, state2, anchor, render_fn, flags, get_key, get_collection);
  2045. }
  2046. if (fallback_fn !== null) {
  2047. if (length === 0) {
  2048. if (fallback) {
  2049. resume_effect(fallback);
  2050. } else {
  2051. fallback = branch(() => fallback_fn(anchor));
  2052. }
  2053. } else if (fallback !== null) {
  2054. pause_effect(fallback, () => {
  2055. fallback = null;
  2056. });
  2057. }
  2058. }
  2059. get(each_array);
  2060. });
  2061. }
  2062. function reconcile(array, state2, anchor, render_fn, flags, get_key, get_collection) {
  2063. var _a2, _b, _c, _d;
  2064. var is_animated = (flags & EACH_IS_ANIMATED) !== 0;
  2065. var should_update = (flags & (EACH_ITEM_REACTIVE | EACH_INDEX_REACTIVE)) !== 0;
  2066. var length = array.length;
  2067. var items = state2.items;
  2068. var first = state2.first;
  2069. var current = first;
  2070. var seen;
  2071. var prev = null;
  2072. var to_animate;
  2073. var matched = [];
  2074. var stashed = [];
  2075. var value;
  2076. var key;
  2077. var item;
  2078. var i2;
  2079. if (is_animated) {
  2080. for (i2 = 0; i2 < length; i2 += 1) {
  2081. value = array[i2];
  2082. key = get_key(value, i2);
  2083. item = items.get(key);
  2084. if (item !== void 0) {
  2085. (_a2 = item.a) == null ? void 0 : _a2.measure();
  2086. (to_animate ?? (to_animate = /* @__PURE__ */ new Set())).add(item);
  2087. }
  2088. }
  2089. }
  2090. for (i2 = 0; i2 < length; i2 += 1) {
  2091. value = array[i2];
  2092. key = get_key(value, i2);
  2093. item = items.get(key);
  2094. if (item === void 0) {
  2095. var child_anchor = current ? (
  2096. /** @type {TemplateNode} */
  2097. current.e.nodes_start
  2098. ) : anchor;
  2099. prev = create_item(
  2100. child_anchor,
  2101. state2,
  2102. prev,
  2103. prev === null ? state2.first : prev.next,
  2104. value,
  2105. key,
  2106. i2,
  2107. render_fn,
  2108. flags,
  2109. get_collection
  2110. );
  2111. items.set(key, prev);
  2112. matched = [];
  2113. stashed = [];
  2114. current = prev.next;
  2115. continue;
  2116. }
  2117. if (should_update) {
  2118. update_item(item, value, i2, flags);
  2119. }
  2120. if ((item.e.f & INERT) !== 0) {
  2121. resume_effect(item.e);
  2122. if (is_animated) {
  2123. (_b = item.a) == null ? void 0 : _b.unfix();
  2124. (to_animate ?? (to_animate = /* @__PURE__ */ new Set())).delete(item);
  2125. }
  2126. }
  2127. if (item !== current) {
  2128. if (seen !== void 0 && seen.has(item)) {
  2129. if (matched.length < stashed.length) {
  2130. var start = stashed[0];
  2131. var j;
  2132. prev = start.prev;
  2133. var a2 = matched[0];
  2134. var b = matched[matched.length - 1];
  2135. for (j = 0; j < matched.length; j += 1) {
  2136. move(matched[j], start, anchor);
  2137. }
  2138. for (j = 0; j < stashed.length; j += 1) {
  2139. seen.delete(stashed[j]);
  2140. }
  2141. link(state2, a2.prev, b.next);
  2142. link(state2, prev, a2);
  2143. link(state2, b, start);
  2144. current = start;
  2145. prev = b;
  2146. i2 -= 1;
  2147. matched = [];
  2148. stashed = [];
  2149. } else {
  2150. seen.delete(item);
  2151. move(item, current, anchor);
  2152. link(state2, item.prev, item.next);
  2153. link(state2, item, prev === null ? state2.first : prev.next);
  2154. link(state2, prev, item);
  2155. prev = item;
  2156. }
  2157. continue;
  2158. }
  2159. matched = [];
  2160. stashed = [];
  2161. while (current !== null && current.k !== key) {
  2162. if ((current.e.f & INERT) === 0) {
  2163. (seen ?? (seen = /* @__PURE__ */ new Set())).add(current);
  2164. }
  2165. stashed.push(current);
  2166. current = current.next;
  2167. }
  2168. if (current === null) {
  2169. continue;
  2170. }
  2171. item = current;
  2172. }
  2173. matched.push(item);
  2174. prev = item;
  2175. current = item.next;
  2176. }
  2177. if (current !== null || seen !== void 0) {
  2178. var to_destroy = seen === void 0 ? [] : array_from(seen);
  2179. while (current !== null) {
  2180. if ((current.e.f & INERT) === 0) {
  2181. to_destroy.push(current);
  2182. }
  2183. current = current.next;
  2184. }
  2185. var destroy_length = to_destroy.length;
  2186. if (destroy_length > 0) {
  2187. var controlled_anchor = (flags & EACH_IS_CONTROLLED) !== 0 && length === 0 ? anchor : null;
  2188. if (is_animated) {
  2189. for (i2 = 0; i2 < destroy_length; i2 += 1) {
  2190. (_c = to_destroy[i2].a) == null ? void 0 : _c.measure();
  2191. }
  2192. for (i2 = 0; i2 < destroy_length; i2 += 1) {
  2193. (_d = to_destroy[i2].a) == null ? void 0 : _d.fix();
  2194. }
  2195. }
  2196. pause_effects(state2, to_destroy, controlled_anchor, items);
  2197. }
  2198. }
  2199. if (is_animated) {
  2200. queue_micro_task(() => {
  2201. var _a3;
  2202. if (to_animate === void 0) return;
  2203. for (item of to_animate) {
  2204. (_a3 = item.a) == null ? void 0 : _a3.apply();
  2205. }
  2206. });
  2207. }
  2208. active_effect.first = state2.first && state2.first.e;
  2209. active_effect.last = prev && prev.e;
  2210. }
  2211. function update_item(item, value, index, type) {
  2212. if ((type & EACH_ITEM_REACTIVE) !== 0) {
  2213. internal_set(item.v, value);
  2214. }
  2215. if ((type & EACH_INDEX_REACTIVE) !== 0) {
  2216. internal_set(
  2217. /** @type {Value<number>} */
  2218. item.i,
  2219. index
  2220. );
  2221. } else {
  2222. item.i = index;
  2223. }
  2224. }
  2225. function create_item(anchor, state2, prev, next2, value, key, index, render_fn, flags, get_collection) {
  2226. var reactive = (flags & EACH_ITEM_REACTIVE) !== 0;
  2227. var mutable = (flags & EACH_ITEM_IMMUTABLE) === 0;
  2228. var v2 = reactive ? mutable ? /* @__PURE__ */ mutable_source(value) : source(value) : value;
  2229. var i2 = (flags & EACH_INDEX_REACTIVE) === 0 ? index : source(index);
  2230. var item = {
  2231. i: i2,
  2232. v: v2,
  2233. k: key,
  2234. a: null,
  2235. // @ts-expect-error
  2236. e: null,
  2237. prev,
  2238. next: next2
  2239. };
  2240. try {
  2241. item.e = branch(() => render_fn(anchor, v2, i2, get_collection), hydrating);
  2242. item.e.prev = prev && prev.e;
  2243. item.e.next = next2 && next2.e;
  2244. if (prev === null) {
  2245. state2.first = item;
  2246. } else {
  2247. prev.next = item;
  2248. prev.e.next = item.e;
  2249. }
  2250. if (next2 !== null) {
  2251. next2.prev = item;
  2252. next2.e.prev = item.e;
  2253. }
  2254. return item;
  2255. } finally {
  2256. }
  2257. }
  2258. function move(item, next2, anchor) {
  2259. var end = item.next ? (
  2260. /** @type {TemplateNode} */
  2261. item.next.e.nodes_start
  2262. ) : anchor;
  2263. var dest = next2 ? (
  2264. /** @type {TemplateNode} */
  2265. next2.e.nodes_start
  2266. ) : anchor;
  2267. var node = (
  2268. /** @type {TemplateNode} */
  2269. item.e.nodes_start
  2270. );
  2271. while (node !== end) {
  2272. var next_node = (
  2273. /** @type {TemplateNode} */
  2274. /* @__PURE__ */ get_next_sibling(node)
  2275. );
  2276. dest.before(node);
  2277. node = next_node;
  2278. }
  2279. }
  2280. function link(state2, prev, next2) {
  2281. if (prev === null) {
  2282. state2.first = next2;
  2283. } else {
  2284. prev.next = next2;
  2285. prev.e.next = next2 && next2.e;
  2286. }
  2287. if (next2 !== null) {
  2288. next2.prev = prev;
  2289. next2.e.prev = prev && prev.e;
  2290. }
  2291. }
  2292. function snippet(node, get_snippet, ...args) {
  2293. var anchor = node;
  2294. var snippet2 = noop;
  2295. var snippet_effect;
  2296. block(() => {
  2297. if (snippet2 === (snippet2 = get_snippet())) return;
  2298. if (snippet_effect) {
  2299. destroy_effect(snippet_effect);
  2300. snippet_effect = null;
  2301. }
  2302. snippet_effect = branch(() => (
  2303. /** @type {SnippetFn} */
  2304. snippet2(anchor, ...args)
  2305. ));
  2306. }, EFFECT_TRANSPARENT);
  2307. }
  2308. function component(node, get_component, render_fn) {
  2309. var anchor = node;
  2310. var component2;
  2311. var effect2;
  2312. block(() => {
  2313. if (component2 === (component2 = get_component())) return;
  2314. if (effect2) {
  2315. pause_effect(effect2);
  2316. effect2 = null;
  2317. }
  2318. if (component2) {
  2319. effect2 = branch(() => render_fn(anchor, component2));
  2320. }
  2321. }, EFFECT_TRANSPARENT);
  2322. }
  2323. function r(e2) {
  2324. var t, f, n = "";
  2325. if ("string" == typeof e2 || "number" == typeof e2) n += e2;
  2326. else if ("object" == typeof e2) if (Array.isArray(e2)) {
  2327. var o2 = e2.length;
  2328. for (t = 0; t < o2; t++) e2[t] && (f = r(e2[t])) && (n && (n += " "), n += f);
  2329. } else for (f in e2) e2[f] && (n && (n += " "), n += f);
  2330. return n;
  2331. }
  2332. function clsx$1() {
  2333. for (var e2, t, f = 0, n = "", o2 = arguments.length; f < o2; f++) (e2 = arguments[f]) && (t = r(e2)) && (n && (n += " "), n += t);
  2334. return n;
  2335. }
  2336. function clsx(value) {
  2337. if (typeof value === "object") {
  2338. return clsx$1(value);
  2339. } else {
  2340. return value ?? "";
  2341. }
  2342. }
  2343. const whitespace = [..." \n\r\f \v\uFEFF"];
  2344. function to_class(value, hash, directives) {
  2345. var classname = value == null ? "" : "" + value;
  2346. if (hash) {
  2347. classname = classname ? classname + " " + hash : hash;
  2348. }
  2349. if (directives) {
  2350. for (var key in directives) {
  2351. if (directives[key]) {
  2352. classname = classname ? classname + " " + key : key;
  2353. } else if (classname.length) {
  2354. var len = key.length;
  2355. var a2 = 0;
  2356. while ((a2 = classname.indexOf(key, a2)) >= 0) {
  2357. var b = a2 + len;
  2358. if ((a2 === 0 || whitespace.includes(classname[a2 - 1])) && (b === classname.length || whitespace.includes(classname[b]))) {
  2359. classname = (a2 === 0 ? "" : classname.substring(0, a2)) + classname.substring(b + 1);
  2360. } else {
  2361. a2 = b;
  2362. }
  2363. }
  2364. }
  2365. }
  2366. }
  2367. return classname === "" ? null : classname;
  2368. }
  2369. function append_styles(styles, important = false) {
  2370. var separator = important ? " !important;" : ";";
  2371. var css = "";
  2372. for (var key in styles) {
  2373. var value = styles[key];
  2374. if (value != null && value !== "") {
  2375. css += " " + key + ": " + value + separator;
  2376. }
  2377. }
  2378. return css;
  2379. }
  2380. function to_css_name(name) {
  2381. if (name[0] !== "-" || name[1] !== "-") {
  2382. return name.toLowerCase();
  2383. }
  2384. return name;
  2385. }
  2386. function to_style(value, styles) {
  2387. if (styles) {
  2388. var new_style = "";
  2389. var normal_styles;
  2390. var important_styles;
  2391. if (Array.isArray(styles)) {
  2392. normal_styles = styles[0];
  2393. important_styles = styles[1];
  2394. } else {
  2395. normal_styles = styles;
  2396. }
  2397. if (value) {
  2398. value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim();
  2399. var in_str = false;
  2400. var in_apo = 0;
  2401. var in_comment = false;
  2402. var reserved_names = [];
  2403. if (normal_styles) {
  2404. reserved_names.push(...Object.keys(normal_styles).map(to_css_name));
  2405. }
  2406. if (important_styles) {
  2407. reserved_names.push(...Object.keys(important_styles).map(to_css_name));
  2408. }
  2409. var start_index = 0;
  2410. var name_index = -1;
  2411. const len = value.length;
  2412. for (var i2 = 0; i2 < len; i2++) {
  2413. var c2 = value[i2];
  2414. if (in_comment) {
  2415. if (c2 === "/" && value[i2 - 1] === "*") {
  2416. in_comment = false;
  2417. }
  2418. } else if (in_str) {
  2419. if (in_str === c2) {
  2420. in_str = false;
  2421. }
  2422. } else if (c2 === "/" && value[i2 + 1] === "*") {
  2423. in_comment = true;
  2424. } else if (c2 === '"' || c2 === "'") {
  2425. in_str = c2;
  2426. } else if (c2 === "(") {
  2427. in_apo++;
  2428. } else if (c2 === ")") {
  2429. in_apo--;
  2430. }
  2431. if (!in_comment && in_str === false && in_apo === 0) {
  2432. if (c2 === ":" && name_index === -1) {
  2433. name_index = i2;
  2434. } else if (c2 === ";" || i2 === len - 1) {
  2435. if (name_index !== -1) {
  2436. var name = to_css_name(value.substring(start_index, name_index).trim());
  2437. if (!reserved_names.includes(name)) {
  2438. if (c2 !== ";") {
  2439. i2++;
  2440. }
  2441. var property = value.substring(start_index, i2).trim();
  2442. new_style += " " + property + ";";
  2443. }
  2444. }
  2445. start_index = i2 + 1;
  2446. name_index = -1;
  2447. }
  2448. }
  2449. }
  2450. }
  2451. if (normal_styles) {
  2452. new_style += append_styles(normal_styles);
  2453. }
  2454. if (important_styles) {
  2455. new_style += append_styles(important_styles, true);
  2456. }
  2457. new_style = new_style.trim();
  2458. return new_style === "" ? null : new_style;
  2459. }
  2460. return value == null ? null : String(value);
  2461. }
  2462. function set_class(dom, is_html, value, hash, prev_classes, next_classes) {
  2463. var prev = dom.__className;
  2464. if (prev !== value || prev === void 0) {
  2465. var next_class_name = to_class(value, hash, next_classes);
  2466. {
  2467. if (next_class_name == null) {
  2468. dom.removeAttribute("class");
  2469. } else if (is_html) {
  2470. dom.className = next_class_name;
  2471. } else {
  2472. dom.setAttribute("class", next_class_name);
  2473. }
  2474. }
  2475. dom.__className = value;
  2476. } else if (next_classes && prev_classes !== next_classes) {
  2477. for (var key in next_classes) {
  2478. var is_present = !!next_classes[key];
  2479. if (prev_classes == null || is_present !== !!prev_classes[key]) {
  2480. dom.classList.toggle(key, is_present);
  2481. }
  2482. }
  2483. }
  2484. return next_classes;
  2485. }
  2486. function update_styles(dom, prev = {}, next2, priority) {
  2487. for (var key in next2) {
  2488. var value = next2[key];
  2489. if (prev[key] !== value) {
  2490. if (next2[key] == null) {
  2491. dom.style.removeProperty(key);
  2492. } else {
  2493. dom.style.setProperty(key, value, priority);
  2494. }
  2495. }
  2496. }
  2497. }
  2498. function set_style(dom, value, prev_styles, next_styles) {
  2499. var prev = dom.__style;
  2500. if (prev !== value) {
  2501. var next_style_attr = to_style(value, next_styles);
  2502. {
  2503. if (next_style_attr == null) {
  2504. dom.removeAttribute("style");
  2505. } else {
  2506. dom.style.cssText = next_style_attr;
  2507. }
  2508. }
  2509. dom.__style = value;
  2510. } else if (next_styles) {
  2511. if (Array.isArray(next_styles)) {
  2512. update_styles(dom, prev_styles == null ? void 0 : prev_styles[0], next_styles[0]);
  2513. update_styles(dom, prev_styles == null ? void 0 : prev_styles[1], next_styles[1], "important");
  2514. } else {
  2515. update_styles(dom, prev_styles, next_styles);
  2516. }
  2517. }
  2518. return next_styles;
  2519. }
  2520. const CLASS = Symbol("class");
  2521. const STYLE = Symbol("style");
  2522. const IS_CUSTOM_ELEMENT = Symbol("is custom element");
  2523. const IS_HTML = Symbol("is html");
  2524. function set_selected(element, selected) {
  2525. if (selected) {
  2526. if (!element.hasAttribute("selected")) {
  2527. element.setAttribute("selected", "");
  2528. }
  2529. } else {
  2530. element.removeAttribute("selected");
  2531. }
  2532. }
  2533. function set_attribute(element, attribute, value, skip_warning) {
  2534. var attributes = get_attributes(element);
  2535. if (attributes[attribute] === (attributes[attribute] = value)) return;
  2536. if (attribute === "loading") {
  2537. element[LOADING_ATTR_SYMBOL] = value;
  2538. }
  2539. if (value == null) {
  2540. element.removeAttribute(attribute);
  2541. } else if (typeof value !== "string" && get_setters(element).includes(attribute)) {
  2542. element[attribute] = value;
  2543. } else {
  2544. element.setAttribute(attribute, value);
  2545. }
  2546. }
  2547. function set_attributes(element, prev, next2, css_hash, skip_warning = false) {
  2548. var attributes = get_attributes(element);
  2549. var is_custom_element = attributes[IS_CUSTOM_ELEMENT];
  2550. var preserve_attribute_case = !attributes[IS_HTML];
  2551. var current = prev || {};
  2552. var is_option_element = element.tagName === "OPTION";
  2553. for (var key in prev) {
  2554. if (!(key in next2)) {
  2555. next2[key] = null;
  2556. }
  2557. }
  2558. if (next2.class) {
  2559. next2.class = clsx(next2.class);
  2560. } else if (css_hash || next2[CLASS]) {
  2561. next2.class = null;
  2562. }
  2563. if (next2[STYLE]) {
  2564. next2.style ?? (next2.style = null);
  2565. }
  2566. var setters = get_setters(element);
  2567. for (const key2 in next2) {
  2568. let value = next2[key2];
  2569. if (is_option_element && key2 === "value" && value == null) {
  2570. element.value = element.__value = "";
  2571. current[key2] = value;
  2572. continue;
  2573. }
  2574. if (key2 === "class") {
  2575. var is_html = element.namespaceURI === "http://www.w3.org/1999/xhtml";
  2576. set_class(element, is_html, value, css_hash, prev == null ? void 0 : prev[CLASS], next2[CLASS]);
  2577. current[key2] = value;
  2578. current[CLASS] = next2[CLASS];
  2579. continue;
  2580. }
  2581. if (key2 === "style") {
  2582. set_style(element, value, prev == null ? void 0 : prev[STYLE], next2[STYLE]);
  2583. current[key2] = value;
  2584. current[STYLE] = next2[STYLE];
  2585. continue;
  2586. }
  2587. var prev_value = current[key2];
  2588. if (value === prev_value) continue;
  2589. current[key2] = value;
  2590. var prefix = key2[0] + key2[1];
  2591. if (prefix === "$$") continue;
  2592. if (prefix === "on") {
  2593. const opts = {};
  2594. const event_handle_key = "$$" + key2;
  2595. let event_name = key2.slice(2);
  2596. var delegated = is_delegated(event_name);
  2597. if (is_capture_event(event_name)) {
  2598. event_name = event_name.slice(0, -7);
  2599. opts.capture = true;
  2600. }
  2601. if (!delegated && prev_value) {
  2602. if (value != null) continue;
  2603. element.removeEventListener(event_name, current[event_handle_key], opts);
  2604. current[event_handle_key] = null;
  2605. }
  2606. if (value != null) {
  2607. if (!delegated) {
  2608. let handle = function(evt) {
  2609. current[key2].call(this, evt);
  2610. };
  2611. current[event_handle_key] = create_event(event_name, element, handle, opts);
  2612. } else {
  2613. element[`__${event_name}`] = value;
  2614. delegate([event_name]);
  2615. }
  2616. } else if (delegated) {
  2617. element[`__${event_name}`] = void 0;
  2618. }
  2619. } else if (key2 === "style") {
  2620. set_attribute(element, key2, value);
  2621. } else if (key2 === "autofocus") {
  2622. autofocus(
  2623. /** @type {HTMLElement} */
  2624. element,
  2625. Boolean(value)
  2626. );
  2627. } else if (!is_custom_element && (key2 === "__value" || key2 === "value" && value != null)) {
  2628. element.value = element.__value = value;
  2629. } else if (key2 === "selected" && is_option_element) {
  2630. set_selected(
  2631. /** @type {HTMLOptionElement} */
  2632. element,
  2633. value
  2634. );
  2635. } else {
  2636. var name = key2;
  2637. if (!preserve_attribute_case) {
  2638. name = normalize_attribute(name);
  2639. }
  2640. var is_default = name === "defaultValue" || name === "defaultChecked";
  2641. if (value == null && !is_custom_element && !is_default) {
  2642. attributes[key2] = null;
  2643. if (name === "value" || name === "checked") {
  2644. let input = (
  2645. /** @type {HTMLInputElement} */
  2646. element
  2647. );
  2648. const use_default = prev === void 0;
  2649. if (name === "value") {
  2650. let previous = input.defaultValue;
  2651. input.removeAttribute(name);
  2652. input.defaultValue = previous;
  2653. input.value = input.__value = use_default ? previous : null;
  2654. } else {
  2655. let previous = input.defaultChecked;
  2656. input.removeAttribute(name);
  2657. input.defaultChecked = previous;
  2658. input.checked = use_default ? previous : false;
  2659. }
  2660. } else {
  2661. element.removeAttribute(key2);
  2662. }
  2663. } else if (is_default || setters.includes(name) && (is_custom_element || typeof value !== "string")) {
  2664. element[name] = value;
  2665. } else if (typeof value !== "function") {
  2666. set_attribute(element, name, value);
  2667. }
  2668. }
  2669. }
  2670. return current;
  2671. }
  2672. function get_attributes(element) {
  2673. return (
  2674. /** @type {Record<string | symbol, unknown>} **/
  2675. // @ts-expect-error
  2676. element.__attributes ?? (element.__attributes = {
  2677. [IS_CUSTOM_ELEMENT]: element.nodeName.includes("-"),
  2678. [IS_HTML]: element.namespaceURI === NAMESPACE_HTML
  2679. })
  2680. );
  2681. }
  2682. var setters_cache = /* @__PURE__ */ new Map();
  2683. function get_setters(element) {
  2684. var setters = setters_cache.get(element.nodeName);
  2685. if (setters) return setters;
  2686. setters_cache.set(element.nodeName, setters = []);
  2687. var descriptors;
  2688. var proto = element;
  2689. var element_proto = Element.prototype;
  2690. while (element_proto !== proto) {
  2691. descriptors = get_descriptors(proto);
  2692. for (var key in descriptors) {
  2693. if (descriptors[key].set) {
  2694. setters.push(key);
  2695. }
  2696. }
  2697. proto = get_prototype_of(proto);
  2698. }
  2699. return setters;
  2700. }
  2701. function is_bound_this(bound_value, element_or_component) {
  2702. return bound_value === element_or_component || (bound_value == null ? void 0 : bound_value[STATE_SYMBOL]) === element_or_component;
  2703. }
  2704. function bind_this(element_or_component = {}, update, get_value, get_parts) {
  2705. effect(() => {
  2706. var old_parts;
  2707. var parts;
  2708. render_effect(() => {
  2709. old_parts = parts;
  2710. parts = [];
  2711. untrack(() => {
  2712. if (element_or_component !== get_value(...parts)) {
  2713. update(element_or_component, ...parts);
  2714. if (old_parts && is_bound_this(get_value(...old_parts), element_or_component)) {
  2715. update(null, ...old_parts);
  2716. }
  2717. }
  2718. });
  2719. });
  2720. return () => {
  2721. queue_micro_task(() => {
  2722. if (parts && is_bound_this(get_value(...parts), element_or_component)) {
  2723. update(null, ...parts);
  2724. }
  2725. });
  2726. };
  2727. });
  2728. return element_or_component;
  2729. }
  2730. function init(immutable = false) {
  2731. const context = (
  2732. /** @type {ComponentContextLegacy} */
  2733. component_context
  2734. );
  2735. const callbacks = context.l.u;
  2736. if (!callbacks) return;
  2737. let props = () => deep_read_state(context.s);
  2738. if (immutable) {
  2739. let version = 0;
  2740. let prev = (
  2741. /** @type {Record<string, any>} */
  2742. {}
  2743. );
  2744. const d = /* @__PURE__ */ derived(() => {
  2745. let changed = false;
  2746. const props2 = context.s;
  2747. for (const key in props2) {
  2748. if (props2[key] !== prev[key]) {
  2749. prev[key] = props2[key];
  2750. changed = true;
  2751. }
  2752. }
  2753. if (changed) version++;
  2754. return version;
  2755. });
  2756. props = () => get(d);
  2757. }
  2758. if (callbacks.b.length) {
  2759. user_pre_effect(() => {
  2760. observe_all(context, props);
  2761. run_all(callbacks.b);
  2762. });
  2763. }
  2764. user_effect(() => {
  2765. const fns = untrack(() => callbacks.m.map(run));
  2766. return () => {
  2767. for (const fn of fns) {
  2768. if (typeof fn === "function") {
  2769. fn();
  2770. }
  2771. }
  2772. };
  2773. });
  2774. if (callbacks.a.length) {
  2775. user_effect(() => {
  2776. observe_all(context, props);
  2777. run_all(callbacks.a);
  2778. });
  2779. }
  2780. }
  2781. function observe_all(context, props) {
  2782. if (context.l.s) {
  2783. for (const signal of context.l.s) get(signal);
  2784. }
  2785. props();
  2786. }
  2787. let is_store_binding = false;
  2788. function capture_store_binding(fn) {
  2789. var previous_is_store_binding = is_store_binding;
  2790. try {
  2791. is_store_binding = false;
  2792. return [fn(), is_store_binding];
  2793. } finally {
  2794. is_store_binding = previous_is_store_binding;
  2795. }
  2796. }
  2797. const rest_props_handler = {
  2798. get(target, key) {
  2799. if (target.exclude.includes(key)) return;
  2800. return target.props[key];
  2801. },
  2802. set(target, key) {
  2803. return false;
  2804. },
  2805. getOwnPropertyDescriptor(target, key) {
  2806. if (target.exclude.includes(key)) return;
  2807. if (key in target.props) {
  2808. return {
  2809. enumerable: true,
  2810. configurable: true,
  2811. value: target.props[key]
  2812. };
  2813. }
  2814. },
  2815. has(target, key) {
  2816. if (target.exclude.includes(key)) return false;
  2817. return key in target.props;
  2818. },
  2819. ownKeys(target) {
  2820. return Reflect.ownKeys(target.props).filter((key) => !target.exclude.includes(key));
  2821. }
  2822. };
  2823. // @__NO_SIDE_EFFECTS__
  2824. function rest_props(props, exclude, name) {
  2825. return new Proxy(
  2826. { props, exclude },
  2827. rest_props_handler
  2828. );
  2829. }
  2830. const spread_props_handler = {
  2831. get(target, key) {
  2832. let i2 = target.props.length;
  2833. while (i2--) {
  2834. let p = target.props[i2];
  2835. if (is_function(p)) p = p();
  2836. if (typeof p === "object" && p !== null && key in p) return p[key];
  2837. }
  2838. },
  2839. set(target, key, value) {
  2840. let i2 = target.props.length;
  2841. while (i2--) {
  2842. let p = target.props[i2];
  2843. if (is_function(p)) p = p();
  2844. const desc = get_descriptor(p, key);
  2845. if (desc && desc.set) {
  2846. desc.set(value);
  2847. return true;
  2848. }
  2849. }
  2850. return false;
  2851. },
  2852. getOwnPropertyDescriptor(target, key) {
  2853. let i2 = target.props.length;
  2854. while (i2--) {
  2855. let p = target.props[i2];
  2856. if (is_function(p)) p = p();
  2857. if (typeof p === "object" && p !== null && key in p) {
  2858. const descriptor = get_descriptor(p, key);
  2859. if (descriptor && !descriptor.configurable) {
  2860. descriptor.configurable = true;
  2861. }
  2862. return descriptor;
  2863. }
  2864. }
  2865. },
  2866. has(target, key) {
  2867. if (key === STATE_SYMBOL || key === LEGACY_PROPS) return false;
  2868. for (let p of target.props) {
  2869. if (is_function(p)) p = p();
  2870. if (p != null && key in p) return true;
  2871. }
  2872. return false;
  2873. },
  2874. ownKeys(target) {
  2875. const keys = [];
  2876. for (let p of target.props) {
  2877. if (is_function(p)) p = p();
  2878. for (const key in p) {
  2879. if (!keys.includes(key)) keys.push(key);
  2880. }
  2881. }
  2882. return keys;
  2883. }
  2884. };
  2885. function spread_props(...props) {
  2886. return new Proxy({ props }, spread_props_handler);
  2887. }
  2888. function has_destroyed_component_ctx(current_value) {
  2889. var _a2;
  2890. return ((_a2 = current_value.ctx) == null ? void 0 : _a2.d) ?? false;
  2891. }
  2892. function prop(props, key, flags, fallback) {
  2893. var _a2;
  2894. var immutable = (flags & PROPS_IS_IMMUTABLE) !== 0;
  2895. var runes = !legacy_mode_flag || (flags & PROPS_IS_RUNES) !== 0;
  2896. var bindable = (flags & PROPS_IS_BINDABLE) !== 0;
  2897. var lazy = (flags & PROPS_IS_LAZY_INITIAL) !== 0;
  2898. var is_store_sub = false;
  2899. var prop_value;
  2900. if (bindable) {
  2901. [prop_value, is_store_sub] = capture_store_binding(() => (
  2902. /** @type {V} */
  2903. props[key]
  2904. ));
  2905. } else {
  2906. prop_value = /** @type {V} */
  2907. props[key];
  2908. }
  2909. var is_entry_props = STATE_SYMBOL in props || LEGACY_PROPS in props;
  2910. 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;
  2911. var fallback_value = (
  2912. /** @type {V} */
  2913. fallback
  2914. );
  2915. var fallback_dirty = true;
  2916. var fallback_used = false;
  2917. var get_fallback = () => {
  2918. fallback_used = true;
  2919. if (fallback_dirty) {
  2920. fallback_dirty = false;
  2921. if (lazy) {
  2922. fallback_value = untrack(
  2923. /** @type {() => V} */
  2924. fallback
  2925. );
  2926. } else {
  2927. fallback_value = /** @type {V} */
  2928. fallback;
  2929. }
  2930. }
  2931. return fallback_value;
  2932. };
  2933. if (prop_value === void 0 && fallback !== void 0) {
  2934. if (setter && runes) {
  2935. props_invalid_value();
  2936. }
  2937. prop_value = get_fallback();
  2938. if (setter) setter(prop_value);
  2939. }
  2940. var getter;
  2941. if (runes) {
  2942. getter = () => {
  2943. var value = (
  2944. /** @type {V} */
  2945. props[key]
  2946. );
  2947. if (value === void 0) return get_fallback();
  2948. fallback_dirty = true;
  2949. fallback_used = false;
  2950. return value;
  2951. };
  2952. } else {
  2953. var derived_getter = (immutable ? derived : derived_safe_equal)(
  2954. () => (
  2955. /** @type {V} */
  2956. props[key]
  2957. )
  2958. );
  2959. derived_getter.f |= LEGACY_DERIVED_PROP;
  2960. getter = () => {
  2961. var value = get(derived_getter);
  2962. if (value !== void 0) fallback_value = /** @type {V} */
  2963. void 0;
  2964. return value === void 0 ? fallback_value : value;
  2965. };
  2966. }
  2967. if ((flags & PROPS_IS_UPDATED) === 0) {
  2968. return getter;
  2969. }
  2970. if (setter) {
  2971. var legacy_parent = props.$$legacy;
  2972. return function(value, mutation) {
  2973. if (arguments.length > 0) {
  2974. if (!runes || !mutation || legacy_parent || is_store_sub) {
  2975. setter(mutation ? getter() : value);
  2976. }
  2977. return value;
  2978. } else {
  2979. return getter();
  2980. }
  2981. };
  2982. }
  2983. var from_child = false;
  2984. var inner_current_value = /* @__PURE__ */ mutable_source(prop_value);
  2985. var current_value = /* @__PURE__ */ derived(() => {
  2986. var parent_value = getter();
  2987. var child_value = get(inner_current_value);
  2988. if (from_child) {
  2989. from_child = false;
  2990. return child_value;
  2991. }
  2992. return inner_current_value.v = parent_value;
  2993. });
  2994. if (bindable) {
  2995. get(current_value);
  2996. }
  2997. if (!immutable) current_value.equals = safe_equals;
  2998. return function(value, mutation) {
  2999. if (arguments.length > 0) {
  3000. const new_value = mutation ? get(current_value) : runes && bindable ? proxy(value) : value;
  3001. if (!current_value.equals(new_value)) {
  3002. from_child = true;
  3003. set(inner_current_value, new_value);
  3004. if (fallback_used && fallback_value !== void 0) {
  3005. fallback_value = new_value;
  3006. }
  3007. if (has_destroyed_component_ctx(current_value)) {
  3008. return value;
  3009. }
  3010. untrack(() => get(current_value));
  3011. }
  3012. return value;
  3013. }
  3014. if (has_destroyed_component_ctx(current_value)) {
  3015. return current_value.v;
  3016. }
  3017. return get(current_value);
  3018. };
  3019. }
  3020. function onMount(fn) {
  3021. if (component_context === null) {
  3022. lifecycle_outside_component();
  3023. }
  3024. if (legacy_mode_flag && component_context.l !== null) {
  3025. init_update_callbacks(component_context).m.push(fn);
  3026. } else {
  3027. user_effect(() => {
  3028. const cleanup = untrack(fn);
  3029. if (typeof cleanup === "function") return (
  3030. /** @type {() => void} */
  3031. cleanup
  3032. );
  3033. });
  3034. }
  3035. }
  3036. function init_update_callbacks(context) {
  3037. var l = (
  3038. /** @type {ComponentContextLegacy} */
  3039. context.l
  3040. );
  3041. return l.u ?? (l.u = { a: [], b: [], m: [] });
  3042. }
  3043. const PUBLIC_VERSION = "5";
  3044. if (typeof window !== "undefined") {
  3045. ((_a = window.__svelte ?? (window.__svelte = {})).v ?? (_a.v = /* @__PURE__ */ new Set())).add(PUBLIC_VERSION);
  3046. }
  3047. enable_legacy_mode_flag();
  3048. const bars = Array(12).fill(0);
  3049. var root_1$4 = /* @__PURE__ */ template(`<div class="sonner-loading-bar"></div>`);
  3050. var root$9 = /* @__PURE__ */ template(`<div><div class="sonner-spinner"></div></div>`);
  3051. function Loader($$anchor, $$props) {
  3052. push($$props, true);
  3053. var div = root$9();
  3054. var div_1 = child(div);
  3055. each(div_1, 23, () => bars, (_, i2) => `spinner-bar-${i2}`, ($$anchor2, _) => {
  3056. var div_2 = root_1$4();
  3057. append($$anchor2, div_2);
  3058. });
  3059. template_effect(
  3060. ($0) => {
  3061. set_class(div, 1, $0);
  3062. set_attribute(div, "data-visible", $$props.visible);
  3063. },
  3064. [
  3065. () => clsx(["sonner-loading-wrapper", $$props.class].filter(Boolean).join(" "))
  3066. ]
  3067. );
  3068. append($$anchor, div);
  3069. pop();
  3070. }
  3071. function cn(...classes) {
  3072. return classes.filter(Boolean).join(" ");
  3073. }
  3074. const isBrowser = typeof document !== "undefined";
  3075. const defaultWindow = typeof window !== "undefined" ? window : void 0;
  3076. function getActiveElement(document2) {
  3077. let activeElement = document2.activeElement;
  3078. while (activeElement == null ? void 0 : activeElement.shadowRoot) {
  3079. const node = activeElement.shadowRoot.activeElement;
  3080. if (node === activeElement)
  3081. break;
  3082. else
  3083. activeElement = node;
  3084. }
  3085. return activeElement;
  3086. }
  3087. function increment(source2) {
  3088. set(source2, source2.v + 1);
  3089. }
  3090. function createSubscriber(start) {
  3091. let subscribers = 0;
  3092. let version = source(0);
  3093. let stop;
  3094. return () => {
  3095. if (effect_tracking()) {
  3096. get(version);
  3097. render_effect(() => {
  3098. if (subscribers === 0) {
  3099. stop = untrack(() => start(() => increment(version)));
  3100. }
  3101. subscribers += 1;
  3102. return () => {
  3103. tick().then(() => {
  3104. subscribers -= 1;
  3105. if (subscribers === 0) {
  3106. stop == null ? void 0 : stop();
  3107. stop = void 0;
  3108. }
  3109. });
  3110. };
  3111. });
  3112. }
  3113. };
  3114. }
  3115. class ActiveElement {
  3116. constructor(options = {}) {
  3117. __privateAdd(this, _document);
  3118. __privateAdd(this, _subscribe);
  3119. const {
  3120. window: window2 = defaultWindow,
  3121. document: document2 = window2 == null ? void 0 : window2.document
  3122. } = options;
  3123. if (window2 === void 0) return;
  3124. __privateSet(this, _document, document2);
  3125. __privateSet(this, _subscribe, createSubscriber((update) => {
  3126. const cleanupFocusIn = on(window2, "focusin", update);
  3127. const cleanupFocusOut = on(window2, "focusout", update);
  3128. return () => {
  3129. cleanupFocusIn();
  3130. cleanupFocusOut();
  3131. };
  3132. }));
  3133. }
  3134. get current() {
  3135. var _a2;
  3136. (_a2 = __privateGet(this, _subscribe)) == null ? void 0 : _a2.call(this);
  3137. if (!__privateGet(this, _document)) return null;
  3138. return getActiveElement(__privateGet(this, _document));
  3139. }
  3140. }
  3141. _document = new WeakMap();
  3142. _subscribe = new WeakMap();
  3143. new ActiveElement();
  3144. class Context {
  3145. /**
  3146. * @param name The name of the context.
  3147. * This is used for generating the context key and error messages.
  3148. */
  3149. constructor(name) {
  3150. __privateAdd(this, _name);
  3151. __privateAdd(this, _key);
  3152. __privateSet(this, _name, name);
  3153. __privateSet(this, _key, Symbol(name));
  3154. }
  3155. /**
  3156. * The key used to get and set the context.
  3157. *
  3158. * It is not recommended to use this value directly.
  3159. * Instead, use the methods provided by this class.
  3160. */
  3161. get key() {
  3162. return __privateGet(this, _key);
  3163. }
  3164. /**
  3165. * Checks whether this has been set in the context of a parent component.
  3166. *
  3167. * Must be called during component initialisation.
  3168. */
  3169. exists() {
  3170. return hasContext(__privateGet(this, _key));
  3171. }
  3172. /**
  3173. * Retrieves the context that belongs to the closest parent component.
  3174. *
  3175. * Must be called during component initialisation.
  3176. *
  3177. * @throws An error if the context does not exist.
  3178. */
  3179. get() {
  3180. const context = getContext(__privateGet(this, _key));
  3181. if (context === void 0) {
  3182. throw new Error(`Context "${__privateGet(this, _name)}" not found`);
  3183. }
  3184. return context;
  3185. }
  3186. /**
  3187. * Retrieves the context that belongs to the closest parent component,
  3188. * or the given fallback value if the context does not exist.
  3189. *
  3190. * Must be called during component initialisation.
  3191. */
  3192. getOr(fallback) {
  3193. const context = getContext(__privateGet(this, _key));
  3194. if (context === void 0) {
  3195. return fallback;
  3196. }
  3197. return context;
  3198. }
  3199. /**
  3200. * Associates the given value with the current component and returns it.
  3201. *
  3202. * Must be called during component initialisation.
  3203. */
  3204. set(context) {
  3205. return setContext(__privateGet(this, _key), context);
  3206. }
  3207. }
  3208. _name = new WeakMap();
  3209. _key = new WeakMap();
  3210. const sonnerContext = new Context("<Toaster/>");
  3211. let toastsCounter = 0;
  3212. class ToastState {
  3213. constructor() {
  3214. __privateAdd(this, _toasts, /* @__PURE__ */ state(proxy([])));
  3215. __privateAdd(this, _heights, /* @__PURE__ */ state(proxy([])));
  3216. __privateAdd(this, _findToastIdx, (id) => {
  3217. const idx = this.toasts.findIndex((toast2) => toast2.id === id);
  3218. if (idx === -1) return null;
  3219. return idx;
  3220. });
  3221. __publicField(this, "addToast", (data) => {
  3222. if (!isBrowser) return;
  3223. this.toasts.unshift(data);
  3224. });
  3225. __publicField(this, "updateToast", ({ id, data, type, message }) => {
  3226. const toastIdx = this.toasts.findIndex((toast2) => toast2.id === id);
  3227. const toastToUpdate = this.toasts[toastIdx];
  3228. this.toasts[toastIdx] = {
  3229. ...toastToUpdate,
  3230. ...data,
  3231. id,
  3232. title: message,
  3233. type,
  3234. updated: true
  3235. };
  3236. });
  3237. __publicField(this, "create", (data) => {
  3238. var _a2;
  3239. const { message, ...rest } = data;
  3240. const id = typeof (data == null ? void 0 : data.id) === "number" || data.id && ((_a2 = data.id) == null ? void 0 : _a2.length) > 0 ? data.id : toastsCounter++;
  3241. const dismissable = data.dismissable === void 0 ? true : data.dismissable;
  3242. const type = data.type === void 0 ? "default" : data.type;
  3243. const alreadyExists = this.toasts.find((toast2) => toast2.id === id);
  3244. if (alreadyExists) {
  3245. this.updateToast({ id, data, type, message, dismissable });
  3246. } else {
  3247. this.addToast({
  3248. ...rest,
  3249. id,
  3250. title: message,
  3251. dismissable,
  3252. type
  3253. });
  3254. }
  3255. return id;
  3256. });
  3257. __publicField(this, "dismiss", (id) => {
  3258. if (id === void 0) {
  3259. this.toasts = this.toasts.map((toast2) => ({ ...toast2, dismiss: true }));
  3260. return;
  3261. }
  3262. const toastIdx = this.toasts.findIndex((toast2) => toast2.id === id);
  3263. if (this.toasts[toastIdx]) {
  3264. this.toasts[toastIdx] = { ...this.toasts[toastIdx], dismiss: true };
  3265. }
  3266. return id;
  3267. });
  3268. __publicField(this, "remove", (id) => {
  3269. if (id === void 0) {
  3270. this.toasts = [];
  3271. return;
  3272. }
  3273. const toastIdx = __privateGet(this, _findToastIdx).call(this, id);
  3274. if (toastIdx === null) return;
  3275. this.toasts.splice(toastIdx, 1);
  3276. return id;
  3277. });
  3278. __publicField(this, "message", (message, data) => {
  3279. return this.create({ ...data, type: "default", message });
  3280. });
  3281. __publicField(this, "error", (message, data) => {
  3282. return this.create({ ...data, type: "error", message });
  3283. });
  3284. __publicField(this, "success", (message, data) => {
  3285. return this.create({ ...data, type: "success", message });
  3286. });
  3287. __publicField(this, "info", (message, data) => {
  3288. return this.create({ ...data, type: "info", message });
  3289. });
  3290. __publicField(this, "warning", (message, data) => {
  3291. return this.create({ ...data, type: "warning", message });
  3292. });
  3293. __publicField(this, "loading", (message, data) => {
  3294. return this.create({ ...data, type: "loading", message });
  3295. });
  3296. __publicField(this, "promise", (promise, data) => {
  3297. if (!data) {
  3298. return;
  3299. }
  3300. let id = void 0;
  3301. if (data.loading !== void 0) {
  3302. id = this.create({
  3303. ...data,
  3304. promise,
  3305. type: "loading",
  3306. message: typeof data.loading === "string" ? data.loading : data.loading()
  3307. });
  3308. }
  3309. const p = promise instanceof Promise ? promise : promise();
  3310. let shouldDismiss = id !== void 0;
  3311. p.then((response) => {
  3312. if (typeof response === "object" && response && "ok" in response && typeof response.ok === "boolean" && !response.ok) {
  3313. shouldDismiss = false;
  3314. const message = constructPromiseErrorMessage(response);
  3315. this.create({ id, type: "error", message });
  3316. } else if (data.success !== void 0) {
  3317. shouldDismiss = false;
  3318. const message = typeof data.success === "function" ? data.success(response) : data.success;
  3319. this.create({ id, type: "success", message });
  3320. }
  3321. }).catch((error) => {
  3322. if (data.error !== void 0) {
  3323. shouldDismiss = false;
  3324. const message = typeof data.error === "function" ? data.error(error) : data.error;
  3325. this.create({ id, type: "error", message });
  3326. }
  3327. }).finally(() => {
  3328. var _a2;
  3329. if (shouldDismiss) {
  3330. this.dismiss(id);
  3331. id = void 0;
  3332. }
  3333. (_a2 = data.finally) == null ? void 0 : _a2.call(data);
  3334. });
  3335. return id;
  3336. });
  3337. __publicField(this, "custom", (component2, data) => {
  3338. const id = (data == null ? void 0 : data.id) || toastsCounter++;
  3339. this.create({ component: component2, id, ...data });
  3340. return id;
  3341. });
  3342. __publicField(this, "removeHeight", (id) => {
  3343. this.heights = this.heights.filter((height) => height.toastId !== id);
  3344. });
  3345. __publicField(this, "setHeight", (data) => {
  3346. const toastIdx = __privateGet(this, _findToastIdx).call(this, data.toastId);
  3347. if (toastIdx === null) {
  3348. this.heights.push(data);
  3349. return;
  3350. }
  3351. this.heights[toastIdx] = data;
  3352. });
  3353. __publicField(this, "reset", () => {
  3354. this.toasts = [];
  3355. this.heights = [];
  3356. });
  3357. }
  3358. get toasts() {
  3359. return get(__privateGet(this, _toasts));
  3360. }
  3361. set toasts(value) {
  3362. set(__privateGet(this, _toasts), value, true);
  3363. }
  3364. get heights() {
  3365. return get(__privateGet(this, _heights));
  3366. }
  3367. set heights(value) {
  3368. set(__privateGet(this, _heights), value, true);
  3369. }
  3370. }
  3371. _toasts = new WeakMap();
  3372. _heights = new WeakMap();
  3373. _findToastIdx = new WeakMap();
  3374. function constructPromiseErrorMessage(response) {
  3375. if (response && typeof response === "object" && "status" in response) {
  3376. return `HTTP error! Status: ${response.status}`;
  3377. }
  3378. return `Error! ${response}`;
  3379. }
  3380. const toastState = new ToastState();
  3381. function toastFunction(message, data) {
  3382. return toastState.create({ message, ...data });
  3383. }
  3384. class SonnerState {
  3385. constructor() {
  3386. __privateAdd(this, _activeToasts, /* @__PURE__ */ user_derived(() => toastState.toasts.filter((toast2) => !toast2.dismiss)));
  3387. }
  3388. get toasts() {
  3389. return get(__privateGet(this, _activeToasts));
  3390. }
  3391. }
  3392. _activeToasts = new WeakMap();
  3393. const basicToast = toastFunction;
  3394. const toast = Object.assign(basicToast, {
  3395. success: toastState.success,
  3396. info: toastState.info,
  3397. warning: toastState.warning,
  3398. error: toastState.error,
  3399. custom: toastState.custom,
  3400. message: toastState.message,
  3401. promise: toastState.promise,
  3402. dismiss: toastState.dismiss,
  3403. loading: toastState.loading,
  3404. getActiveToasts: () => {
  3405. return toastState.toasts.filter((toast2) => !toast2.dismiss);
  3406. }
  3407. });
  3408. function isAction(action) {
  3409. return action.label !== void 0;
  3410. }
  3411. function useDocumentHidden() {
  3412. let current = /* @__PURE__ */ state(proxy(typeof document !== "undefined" ? document.hidden : false));
  3413. user_effect(() => {
  3414. return on(document, "visibilitychange", () => {
  3415. set(current, document.hidden, true);
  3416. });
  3417. });
  3418. return {
  3419. get current() {
  3420. return get(current);
  3421. }
  3422. };
  3423. }
  3424. const TOAST_LIFETIME$1 = 4e3;
  3425. const GAP$1 = 14;
  3426. const SWIPE_THRESHOLD = 45;
  3427. const TIME_BEFORE_UNMOUNT = 200;
  3428. const SCALE_MULTIPLIER = 0.05;
  3429. const DEFAULT_TOAST_CLASSES = {
  3430. toast: "",
  3431. title: "",
  3432. description: "",
  3433. loader: "",
  3434. closeButton: "",
  3435. cancelButton: "",
  3436. actionButton: "",
  3437. action: "",
  3438. warning: "",
  3439. error: "",
  3440. success: "",
  3441. default: "",
  3442. info: "",
  3443. loading: ""
  3444. };
  3445. function getDefaultSwipeDirections(position) {
  3446. const [y2, x] = position.split("-");
  3447. const directions = [];
  3448. if (y2) {
  3449. directions.push(y2);
  3450. }
  3451. if (x) {
  3452. directions.push(x);
  3453. }
  3454. return directions;
  3455. }
  3456. function getDampening(delta) {
  3457. const factor = Math.abs(delta) / 20;
  3458. return 1 / (1.5 + factor);
  3459. }
  3460. var root_2$2 = /* @__PURE__ */ template(`<div><!></div>`);
  3461. var on_click = (_, disabled, dismissable, deleteToast, $$props) => {
  3462. var _a2, _b;
  3463. if (get(disabled) || !get(dismissable)) return;
  3464. deleteToast();
  3465. (_b = (_a2 = $$props.toast).onDismiss) == null ? void 0 : _b.call(_a2, $$props.toast);
  3466. };
  3467. var root_4 = /* @__PURE__ */ template(`<button data-close-button=""><!></button>`);
  3468. var root_7 = /* @__PURE__ */ template(`<div data-icon=""><!> <!></div>`);
  3469. var root_24 = /* @__PURE__ */ template(`<div data-description=""><!></div>`);
  3470. var on_click_1 = (event2, $$props, dismissable, deleteToast) => {
  3471. var _a2, _b;
  3472. if (!isAction($$props.toast.cancel)) return;
  3473. if (!get(dismissable)) return;
  3474. (_b = (_a2 = $$props.toast.cancel) == null ? void 0 : _a2.onClick) == null ? void 0 : _b.call(_a2, event2);
  3475. deleteToast();
  3476. };
  3477. var root_30 = /* @__PURE__ */ template(`<button data-button="" data-cancel=""> </button>`);
  3478. var on_click_2 = (event2, $$props, deleteToast) => {
  3479. var _a2;
  3480. if (!isAction($$props.toast.action)) return;
  3481. (_a2 = $$props.toast.action) == null ? void 0 : _a2.onClick(event2);
  3482. if (event2.defaultPrevented) return;
  3483. deleteToast();
  3484. };
  3485. var root_34 = /* @__PURE__ */ template(`<button data-button=""> </button>`);
  3486. var root_6 = /* @__PURE__ */ template(`<!> <div data-content=""><div data-title=""><!></div> <!></div> <!> <!>`, 1);
  3487. var root$8 = /* @__PURE__ */ template(`<li data-sonner-toast=""><!> <!></li>`);
  3488. function Toast($$anchor, $$props) {
  3489. push($$props, true);
  3490. const LoadingIcon = ($$anchor2) => {
  3491. var fragment = comment();
  3492. var node = first_child(fragment);
  3493. {
  3494. var consequent = ($$anchor3) => {
  3495. var div = root_2$2();
  3496. var node_1 = child(div);
  3497. snippet(node_1, () => $$props.loadingIcon);
  3498. template_effect(
  3499. ($0) => {
  3500. set_class(div, 1, $0);
  3501. set_attribute(div, "data-visible", get(toastType) === "loading");
  3502. },
  3503. [
  3504. () => {
  3505. var _a2, _b, _c;
  3506. 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"));
  3507. }
  3508. ]
  3509. );
  3510. append($$anchor3, div);
  3511. };
  3512. var alternate = ($$anchor3) => {
  3513. const expression = /* @__PURE__ */ user_derived(() => {
  3514. var _a2, _b;
  3515. return cn((_a2 = get(classes)) == null ? void 0 : _a2.loader, (_b = $$props.toast.classes) == null ? void 0 : _b.loader);
  3516. });
  3517. const expression_1 = /* @__PURE__ */ user_derived(() => get(toastType) === "loading");
  3518. Loader($$anchor3, {
  3519. get class() {
  3520. return get(expression);
  3521. },
  3522. get visible() {
  3523. return get(expression_1);
  3524. }
  3525. });
  3526. };
  3527. if_block(node, ($$render) => {
  3528. if ($$props.loadingIcon) $$render(consequent);
  3529. else $$render(alternate, false);
  3530. });
  3531. }
  3532. append($$anchor2, fragment);
  3533. };
  3534. 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);
  3535. const defaultClasses = { ...DEFAULT_TOAST_CLASSES };
  3536. let mounted = /* @__PURE__ */ state(false);
  3537. let removed = /* @__PURE__ */ state(false);
  3538. let swiping = /* @__PURE__ */ state(false);
  3539. let swipeOut = /* @__PURE__ */ state(false);
  3540. let isSwiped = /* @__PURE__ */ state(false);
  3541. let offsetBeforeRemove = /* @__PURE__ */ state(0);
  3542. let initialHeight = /* @__PURE__ */ state(0);
  3543. let remainingTime = $$props.toast.duration || $$props.duration || TOAST_LIFETIME$1;
  3544. let toastRef = /* @__PURE__ */ state(void 0);
  3545. let swipeDirection = /* @__PURE__ */ state(null);
  3546. let swipeOutDirection = /* @__PURE__ */ state(null);
  3547. const isFront = /* @__PURE__ */ user_derived(() => $$props.index === 0);
  3548. const isVisible = /* @__PURE__ */ user_derived(() => $$props.index + 1 <= $$props.visibleToasts);
  3549. const toastType = /* @__PURE__ */ user_derived(() => $$props.toast.type);
  3550. const dismissable = /* @__PURE__ */ user_derived(() => $$props.toast.dismissable !== false);
  3551. const toastClass = /* @__PURE__ */ user_derived(() => $$props.toast.class || "");
  3552. const toastDescriptionClass = /* @__PURE__ */ user_derived(() => $$props.toast.descriptionClass || "");
  3553. const heightIndex = /* @__PURE__ */ user_derived(() => toastState.heights.findIndex((height) => height.toastId === $$props.toast.id) || 0);
  3554. const closeButton = /* @__PURE__ */ user_derived(() => $$props.toast.closeButton ?? $$props.closeButton);
  3555. const duration = /* @__PURE__ */ user_derived(() => $$props.toast.duration ?? $$props.duration ?? TOAST_LIFETIME$1);
  3556. let pointerStart = null;
  3557. const coords = /* @__PURE__ */ user_derived(() => $$props.position.split("-"));
  3558. const toastsHeightBefore = /* @__PURE__ */ user_derived(() => toastState.heights.reduce(
  3559. (prev, curr, reducerIndex) => {
  3560. if (reducerIndex >= get(heightIndex)) return prev;
  3561. return prev + curr.height;
  3562. },
  3563. 0
  3564. ));
  3565. const isDocumentHidden = useDocumentHidden();
  3566. const invert = /* @__PURE__ */ user_derived(() => $$props.toast.invert || $$props.invert);
  3567. const disabled = /* @__PURE__ */ user_derived(() => get(toastType) === "loading");
  3568. const classes = /* @__PURE__ */ user_derived(() => ({ ...defaultClasses, ...$$props.classes }));
  3569. const toastTitle = /* @__PURE__ */ user_derived(() => $$props.toast.title);
  3570. const toastDescription = /* @__PURE__ */ user_derived(() => $$props.toast.description);
  3571. let closeTimerStartTime = /* @__PURE__ */ state(0);
  3572. let lastCloseTimerStartTime = /* @__PURE__ */ state(0);
  3573. const offset = /* @__PURE__ */ user_derived(() => Math.round(get(heightIndex) * GAP$1 + get(toastsHeightBefore)));
  3574. user_effect(() => {
  3575. get(toastTitle);
  3576. get(toastDescription);
  3577. let scale;
  3578. if ($$props.expanded || $$props.expandByDefault) {
  3579. scale = 1;
  3580. } else {
  3581. scale = 1 - $$props.index * SCALE_MULTIPLIER;
  3582. }
  3583. const toastEl = untrack(() => get(toastRef));
  3584. if (toastEl === void 0) return;
  3585. toastEl.style.setProperty("height", "auto");
  3586. const offsetHeight = toastEl.offsetHeight;
  3587. const rectHeight = toastEl.getBoundingClientRect().height;
  3588. const scaledRectHeight = Math.round(rectHeight / scale + Number.EPSILON & 100) / 100;
  3589. toastEl.style.removeProperty("height");
  3590. let finalHeight;
  3591. if (Math.abs(scaledRectHeight - offsetHeight) < 1) {
  3592. finalHeight = scaledRectHeight;
  3593. } else {
  3594. finalHeight = offsetHeight;
  3595. }
  3596. set(initialHeight, finalHeight, true);
  3597. toastState.setHeight({
  3598. toastId: $$props.toast.id,
  3599. height: finalHeight
  3600. });
  3601. });
  3602. function deleteToast() {
  3603. set(removed, true);
  3604. set(offsetBeforeRemove, get(offset), true);
  3605. toastState.removeHeight($$props.toast.id);
  3606. setTimeout(
  3607. () => {
  3608. toastState.remove($$props.toast.id);
  3609. },
  3610. TIME_BEFORE_UNMOUNT
  3611. );
  3612. }
  3613. let timeoutId;
  3614. const isPromiseLoadingOrInfiniteDuration = /* @__PURE__ */ user_derived(() => $$props.toast.promise && get(toastType) === "loading" || $$props.toast.duration === Number.POSITIVE_INFINITY);
  3615. function startTimer() {
  3616. set(closeTimerStartTime, (/* @__PURE__ */ new Date()).getTime(), true);
  3617. timeoutId = setTimeout(
  3618. () => {
  3619. var _a2, _b;
  3620. (_b = (_a2 = $$props.toast).onAutoClose) == null ? void 0 : _b.call(_a2, $$props.toast);
  3621. deleteToast();
  3622. },
  3623. remainingTime
  3624. );
  3625. }
  3626. function pauseTimer() {
  3627. if (get(lastCloseTimerStartTime) < get(closeTimerStartTime)) {
  3628. const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - get(closeTimerStartTime);
  3629. remainingTime = remainingTime - elapsedTime;
  3630. }
  3631. set(lastCloseTimerStartTime, (/* @__PURE__ */ new Date()).getTime(), true);
  3632. }
  3633. user_effect(() => {
  3634. if ($$props.toast.updated) {
  3635. clearTimeout(timeoutId);
  3636. remainingTime = get(duration);
  3637. startTimer();
  3638. }
  3639. });
  3640. user_effect(() => {
  3641. if (!get(isPromiseLoadingOrInfiniteDuration)) {
  3642. if ($$props.expanded || $$props.interacting || isDocumentHidden.current) {
  3643. pauseTimer();
  3644. } else {
  3645. startTimer();
  3646. }
  3647. }
  3648. return () => clearTimeout(timeoutId);
  3649. });
  3650. onMount(() => {
  3651. var _a2;
  3652. set(mounted, true);
  3653. const height = (_a2 = get(toastRef)) == null ? void 0 : _a2.getBoundingClientRect().height;
  3654. set(initialHeight, height, true);
  3655. toastState.setHeight({ toastId: $$props.toast.id, height });
  3656. return () => {
  3657. toastState.removeHeight($$props.toast.id);
  3658. };
  3659. });
  3660. user_effect(() => {
  3661. if ($$props.toast.delete) {
  3662. deleteToast();
  3663. }
  3664. });
  3665. const handlePointerDown = (event2) => {
  3666. if (get(disabled)) return;
  3667. set(offsetBeforeRemove, get(offset), true);
  3668. const target = event2.target;
  3669. target.setPointerCapture(event2.pointerId);
  3670. if (target.tagName === "BUTTON") return;
  3671. set(swiping, true);
  3672. pointerStart = { x: event2.clientX, y: event2.clientY };
  3673. };
  3674. const handlePointerUp = () => {
  3675. var _a2, _b, _c, _d, _e, _f;
  3676. if (get(swipeOut) || !get(dismissable)) return;
  3677. pointerStart = null;
  3678. const swipeAmountX = Number(((_a2 = get(toastRef)) == null ? void 0 : _a2.style.getPropertyValue("--swipe-amount-x").replace("px", "")) || 0);
  3679. const swipeAmountY = Number(((_b = get(toastRef)) == null ? void 0 : _b.style.getPropertyValue("--swipe-amount-y").replace("px", "")) || 0);
  3680. const timeTaken = (/* @__PURE__ */ new Date()).getTime() - 0;
  3681. const swipeAmount = get(swipeDirection) === "x" ? swipeAmountX : swipeAmountY;
  3682. const velocity = Math.abs(swipeAmount) / timeTaken;
  3683. if (Math.abs(swipeAmount) >= SWIPE_THRESHOLD || velocity > 0.11) {
  3684. set(offsetBeforeRemove, get(offset), true);
  3685. (_d = (_c = $$props.toast).onDismiss) == null ? void 0 : _d.call(_c, $$props.toast);
  3686. if (get(swipeDirection) === "x") {
  3687. set(swipeOutDirection, swipeAmountX > 0 ? "right" : "left", true);
  3688. } else {
  3689. set(swipeOutDirection, swipeAmountY > 0 ? "down" : "up", true);
  3690. }
  3691. deleteToast();
  3692. set(swipeOut, true);
  3693. return;
  3694. } else {
  3695. (_e = get(toastRef)) == null ? void 0 : _e.style.setProperty("--swipe-amount-x", "0px");
  3696. (_f = get(toastRef)) == null ? void 0 : _f.style.setProperty("--swipe-amount-y", "0px");
  3697. }
  3698. set(isSwiped, false);
  3699. set(swiping, false);
  3700. set(swipeDirection, null);
  3701. };
  3702. const handlePointerMove = (event2) => {
  3703. var _a2, _b, _c;
  3704. if (!pointerStart || !get(dismissable)) return;
  3705. const isHighlighted = (((_a2 = window.getSelection()) == null ? void 0 : _a2.toString().length) ?? -1) > 0;
  3706. if (isHighlighted) return;
  3707. const yDelta = event2.clientY - pointerStart.y;
  3708. const xDelta = event2.clientX - pointerStart.x;
  3709. const swipeDirections = $$props.swipeDirections ?? getDefaultSwipeDirections($$props.position);
  3710. if (!get(swipeDirection) && (Math.abs(xDelta) > 1 || Math.abs(yDelta) > 1)) {
  3711. set(swipeDirection, Math.abs(xDelta) > Math.abs(yDelta) ? "x" : "y", true);
  3712. }
  3713. let swipeAmount = { x: 0, y: 0 };
  3714. if (get(swipeDirection) === "y") {
  3715. if (swipeDirections.includes("top") || swipeDirections.includes("bottom")) {
  3716. if (swipeDirections.includes("top") && yDelta < 0 || swipeDirections.includes("bottom") && yDelta > 0) {
  3717. swipeAmount.y = yDelta;
  3718. } else {
  3719. const dampenedDelta = yDelta * getDampening(yDelta);
  3720. swipeAmount.y = Math.abs(dampenedDelta) < Math.abs(yDelta) ? dampenedDelta : yDelta;
  3721. }
  3722. }
  3723. } else if (get(swipeDirection) === "x") {
  3724. if (swipeDirections.includes("left") || swipeDirections.includes("right")) {
  3725. if (swipeDirections.includes("left") && xDelta < 0 || swipeDirections.includes("right") && xDelta > 0) {
  3726. swipeAmount.x = xDelta;
  3727. } else {
  3728. const dampenedDelta = xDelta * getDampening(xDelta);
  3729. swipeAmount.x = Math.abs(dampenedDelta) < Math.abs(xDelta) ? dampenedDelta : xDelta;
  3730. }
  3731. }
  3732. }
  3733. if (Math.abs(swipeAmount.x) > 0 || Math.abs(swipeAmount.y) > 0) {
  3734. set(isSwiped, true);
  3735. }
  3736. (_b = get(toastRef)) == null ? void 0 : _b.style.setProperty("--swipe-amount-x", `${swipeAmount.x}px`);
  3737. (_c = get(toastRef)) == null ? void 0 : _c.style.setProperty("--swipe-amount-y", `${swipeAmount.y}px`);
  3738. };
  3739. const handleDragEnd = () => {
  3740. set(swiping, false);
  3741. set(swipeDirection, null);
  3742. pointerStart = null;
  3743. };
  3744. const icon = /* @__PURE__ */ user_derived(() => {
  3745. if ($$props.toast.icon) return $$props.toast.icon;
  3746. if (get(toastType) === "success") return $$props.successIcon;
  3747. if (get(toastType) === "error") return $$props.errorIcon;
  3748. if (get(toastType) === "warning") return $$props.warningIcon;
  3749. if (get(toastType) === "info") return $$props.infoIcon;
  3750. if (get(toastType) === "loading") return $$props.loadingIcon;
  3751. return null;
  3752. });
  3753. var li = root$8();
  3754. set_attribute(li, "tabindex", 0);
  3755. let styles;
  3756. li.__pointermove = handlePointerMove;
  3757. li.__pointerup = handlePointerUp;
  3758. li.__pointerdown = handlePointerDown;
  3759. var node_2 = child(li);
  3760. {
  3761. var consequent_1 = ($$anchor2) => {
  3762. var button = root_4();
  3763. button.__click = [
  3764. on_click,
  3765. disabled,
  3766. dismissable,
  3767. deleteToast,
  3768. $$props
  3769. ];
  3770. var node_3 = child(button);
  3771. snippet(node_3, () => $$props.closeIcon ?? noop);
  3772. template_effect(
  3773. ($0) => {
  3774. set_attribute(button, "aria-label", $$props.closeButtonAriaLabel);
  3775. set_attribute(button, "data-disabled", get(disabled));
  3776. set_class(button, 1, $0);
  3777. },
  3778. [
  3779. () => {
  3780. var _a2, _b, _c;
  3781. 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));
  3782. }
  3783. ]
  3784. );
  3785. append($$anchor2, button);
  3786. };
  3787. if_block(node_2, ($$render) => {
  3788. if (get(closeButton) && !$$props.toast.component && get(toastType) !== "loading" && $$props.closeIcon !== null) $$render(consequent_1);
  3789. });
  3790. }
  3791. var node_4 = sibling(node_2, 2);
  3792. {
  3793. var consequent_2 = ($$anchor2) => {
  3794. var fragment_2 = comment();
  3795. const Component = /* @__PURE__ */ user_derived(() => $$props.toast.component);
  3796. var node_5 = first_child(fragment_2);
  3797. component(node_5, () => get(Component), ($$anchor3, $$component) => {
  3798. $$component($$anchor3, spread_props(() => $$props.toast.componentProps, { closeToast: deleteToast }));
  3799. });
  3800. append($$anchor2, fragment_2);
  3801. };
  3802. var alternate_1 = ($$anchor2) => {
  3803. var fragment_3 = root_6();
  3804. var node_6 = first_child(fragment_3);
  3805. {
  3806. var consequent_11 = ($$anchor3) => {
  3807. var div_1 = root_7();
  3808. var node_7 = child(div_1);
  3809. {
  3810. var consequent_4 = ($$anchor4) => {
  3811. var fragment_4 = comment();
  3812. var node_8 = first_child(fragment_4);
  3813. {
  3814. var consequent_3 = ($$anchor5) => {
  3815. var fragment_5 = comment();
  3816. var node_9 = first_child(fragment_5);
  3817. component(node_9, () => $$props.toast.icon, ($$anchor6, $$component) => {
  3818. $$component($$anchor6, {});
  3819. });
  3820. append($$anchor5, fragment_5);
  3821. };
  3822. var alternate_2 = ($$anchor5) => {
  3823. LoadingIcon($$anchor5);
  3824. };
  3825. if_block(node_8, ($$render) => {
  3826. if ($$props.toast.icon) $$render(consequent_3);
  3827. else $$render(alternate_2, false);
  3828. });
  3829. }
  3830. append($$anchor4, fragment_4);
  3831. };
  3832. if_block(node_7, ($$render) => {
  3833. if ($$props.toast.promise || get(toastType) === "loading") $$render(consequent_4);
  3834. });
  3835. }
  3836. var node_10 = sibling(node_7, 2);
  3837. {
  3838. var consequent_10 = ($$anchor4) => {
  3839. var fragment_7 = comment();
  3840. var node_11 = first_child(fragment_7);
  3841. {
  3842. var consequent_5 = ($$anchor5) => {
  3843. var fragment_8 = comment();
  3844. var node_12 = first_child(fragment_8);
  3845. component(node_12, () => $$props.toast.icon, ($$anchor6, $$component) => {
  3846. $$component($$anchor6, {});
  3847. });
  3848. append($$anchor5, fragment_8);
  3849. };
  3850. var alternate_3 = ($$anchor5, $$elseif) => {
  3851. {
  3852. var consequent_6 = ($$anchor6) => {
  3853. var fragment_9 = comment();
  3854. var node_13 = first_child(fragment_9);
  3855. snippet(node_13, () => $$props.successIcon ?? noop);
  3856. append($$anchor6, fragment_9);
  3857. };
  3858. var alternate_4 = ($$anchor6, $$elseif2) => {
  3859. {
  3860. var consequent_7 = ($$anchor7) => {
  3861. var fragment_10 = comment();
  3862. var node_14 = first_child(fragment_10);
  3863. snippet(node_14, () => $$props.errorIcon ?? noop);
  3864. append($$anchor7, fragment_10);
  3865. };
  3866. var alternate_5 = ($$anchor7, $$elseif3) => {
  3867. {
  3868. var consequent_8 = ($$anchor8) => {
  3869. var fragment_11 = comment();
  3870. var node_15 = first_child(fragment_11);
  3871. snippet(node_15, () => $$props.warningIcon ?? noop);
  3872. append($$anchor8, fragment_11);
  3873. };
  3874. var alternate_6 = ($$anchor8, $$elseif4) => {
  3875. {
  3876. var consequent_9 = ($$anchor9) => {
  3877. var fragment_12 = comment();
  3878. var node_16 = first_child(fragment_12);
  3879. snippet(node_16, () => $$props.infoIcon ?? noop);
  3880. append($$anchor9, fragment_12);
  3881. };
  3882. if_block(
  3883. $$anchor8,
  3884. ($$render) => {
  3885. if (get(toastType) === "info") $$render(consequent_9);
  3886. },
  3887. $$elseif4
  3888. );
  3889. }
  3890. };
  3891. if_block(
  3892. $$anchor7,
  3893. ($$render) => {
  3894. if (get(toastType) === "warning") $$render(consequent_8);
  3895. else $$render(alternate_6, false);
  3896. },
  3897. $$elseif3
  3898. );
  3899. }
  3900. };
  3901. if_block(
  3902. $$anchor6,
  3903. ($$render) => {
  3904. if (get(toastType) === "error") $$render(consequent_7);
  3905. else $$render(alternate_5, false);
  3906. },
  3907. $$elseif2
  3908. );
  3909. }
  3910. };
  3911. if_block(
  3912. $$anchor5,
  3913. ($$render) => {
  3914. if (get(toastType) === "success") $$render(consequent_6);
  3915. else $$render(alternate_4, false);
  3916. },
  3917. $$elseif
  3918. );
  3919. }
  3920. };
  3921. if_block(node_11, ($$render) => {
  3922. if ($$props.toast.icon) $$render(consequent_5);
  3923. else $$render(alternate_3, false);
  3924. });
  3925. }
  3926. append($$anchor4, fragment_7);
  3927. };
  3928. if_block(node_10, ($$render) => {
  3929. if ($$props.toast.type !== "loading") $$render(consequent_10);
  3930. });
  3931. }
  3932. template_effect(($0) => set_class(div_1, 1, $0), [
  3933. () => {
  3934. var _a2, _b, _c;
  3935. 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));
  3936. }
  3937. ]);
  3938. append($$anchor3, div_1);
  3939. };
  3940. if_block(node_6, ($$render) => {
  3941. if ((get(toastType) || $$props.toast.icon || $$props.toast.promise) && $$props.toast.icon !== null && (get(icon) !== null || $$props.toast.icon)) $$render(consequent_11);
  3942. });
  3943. }
  3944. var div_2 = sibling(node_6, 2);
  3945. var div_3 = child(div_2);
  3946. var node_17 = child(div_3);
  3947. {
  3948. var consequent_13 = ($$anchor3) => {
  3949. var fragment_13 = comment();
  3950. var node_18 = first_child(fragment_13);
  3951. {
  3952. var consequent_12 = ($$anchor4) => {
  3953. var fragment_14 = comment();
  3954. const Title = /* @__PURE__ */ user_derived(() => $$props.toast.title);
  3955. var node_19 = first_child(fragment_14);
  3956. component(node_19, () => get(Title), ($$anchor5, $$component) => {
  3957. $$component($$anchor5, spread_props(() => $$props.toast.componentProps));
  3958. });
  3959. append($$anchor4, fragment_14);
  3960. };
  3961. var alternate_7 = ($$anchor4) => {
  3962. var text$1 = text();
  3963. template_effect(() => set_text(text$1, $$props.toast.title));
  3964. append($$anchor4, text$1);
  3965. };
  3966. if_block(node_18, ($$render) => {
  3967. if (typeof $$props.toast.title !== "string") $$render(consequent_12);
  3968. else $$render(alternate_7, false);
  3969. });
  3970. }
  3971. append($$anchor3, fragment_13);
  3972. };
  3973. if_block(node_17, ($$render) => {
  3974. if ($$props.toast.title) $$render(consequent_13);
  3975. });
  3976. }
  3977. var node_20 = sibling(div_3, 2);
  3978. {
  3979. var consequent_15 = ($$anchor3) => {
  3980. var div_4 = root_24();
  3981. var node_21 = child(div_4);
  3982. {
  3983. var consequent_14 = ($$anchor4) => {
  3984. var fragment_16 = comment();
  3985. const Description = /* @__PURE__ */ user_derived(() => $$props.toast.description);
  3986. var node_22 = first_child(fragment_16);
  3987. component(node_22, () => get(Description), ($$anchor5, $$component) => {
  3988. $$component($$anchor5, spread_props(() => $$props.toast.componentProps));
  3989. });
  3990. append($$anchor4, fragment_16);
  3991. };
  3992. var alternate_8 = ($$anchor4) => {
  3993. var text_1 = text();
  3994. template_effect(() => set_text(text_1, $$props.toast.description));
  3995. append($$anchor4, text_1);
  3996. };
  3997. if_block(node_21, ($$render) => {
  3998. if (typeof $$props.toast.description !== "string") $$render(consequent_14);
  3999. else $$render(alternate_8, false);
  4000. });
  4001. }
  4002. template_effect(($0) => set_class(div_4, 1, $0), [
  4003. () => {
  4004. var _a2, _b;
  4005. return clsx(cn(descriptionClass(), get(toastDescriptionClass), (_a2 = get(classes)) == null ? void 0 : _a2.description, (_b = $$props.toast.classes) == null ? void 0 : _b.description));
  4006. }
  4007. ]);
  4008. append($$anchor3, div_4);
  4009. };
  4010. if_block(node_20, ($$render) => {
  4011. if ($$props.toast.description) $$render(consequent_15);
  4012. });
  4013. }
  4014. var node_23 = sibling(div_2, 2);
  4015. {
  4016. var consequent_18 = ($$anchor3) => {
  4017. var fragment_18 = comment();
  4018. var node_24 = first_child(fragment_18);
  4019. {
  4020. var consequent_16 = ($$anchor4) => {
  4021. var fragment_19 = comment();
  4022. var node_25 = first_child(fragment_19);
  4023. component(node_25, () => $$props.toast.cancel, ($$anchor5, $$component) => {
  4024. $$component($$anchor5, {});
  4025. });
  4026. append($$anchor4, fragment_19);
  4027. };
  4028. var alternate_9 = ($$anchor4, $$elseif) => {
  4029. {
  4030. var consequent_17 = ($$anchor5) => {
  4031. var button_1 = root_30();
  4032. button_1.__click = [
  4033. on_click_1,
  4034. $$props,
  4035. dismissable,
  4036. deleteToast
  4037. ];
  4038. var text_2 = child(button_1);
  4039. template_effect(
  4040. ($0) => {
  4041. set_style(button_1, $$props.toast.cancelButtonStyle ?? cancelButtonStyle());
  4042. set_class(button_1, 1, $0);
  4043. set_text(text_2, $$props.toast.cancel.label);
  4044. },
  4045. [
  4046. () => {
  4047. var _a2, _b, _c;
  4048. 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));
  4049. }
  4050. ]
  4051. );
  4052. append($$anchor5, button_1);
  4053. };
  4054. if_block(
  4055. $$anchor4,
  4056. ($$render) => {
  4057. if (isAction($$props.toast.cancel)) $$render(consequent_17);
  4058. },
  4059. $$elseif
  4060. );
  4061. }
  4062. };
  4063. if_block(node_24, ($$render) => {
  4064. if (typeof $$props.toast.cancel === "function") $$render(consequent_16);
  4065. else $$render(alternate_9, false);
  4066. });
  4067. }
  4068. append($$anchor3, fragment_18);
  4069. };
  4070. if_block(node_23, ($$render) => {
  4071. if ($$props.toast.cancel) $$render(consequent_18);
  4072. });
  4073. }
  4074. var node_26 = sibling(node_23, 2);
  4075. {
  4076. var consequent_21 = ($$anchor3) => {
  4077. var fragment_20 = comment();
  4078. var node_27 = first_child(fragment_20);
  4079. {
  4080. var consequent_19 = ($$anchor4) => {
  4081. var fragment_21 = comment();
  4082. var node_28 = first_child(fragment_21);
  4083. component(node_28, () => $$props.toast.action, ($$anchor5, $$component) => {
  4084. $$component($$anchor5, {});
  4085. });
  4086. append($$anchor4, fragment_21);
  4087. };
  4088. var alternate_10 = ($$anchor4, $$elseif) => {
  4089. {
  4090. var consequent_20 = ($$anchor5) => {
  4091. var button_2 = root_34();
  4092. button_2.__click = [on_click_2, $$props, deleteToast];
  4093. var text_3 = child(button_2);
  4094. template_effect(
  4095. ($0) => {
  4096. set_style(button_2, $$props.toast.actionButtonStyle ?? actionButtonStyle());
  4097. set_class(button_2, 1, $0);
  4098. set_text(text_3, $$props.toast.action.label);
  4099. },
  4100. [
  4101. () => {
  4102. var _a2, _b, _c;
  4103. 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));
  4104. }
  4105. ]
  4106. );
  4107. append($$anchor5, button_2);
  4108. };
  4109. if_block(
  4110. $$anchor4,
  4111. ($$render) => {
  4112. if (isAction($$props.toast.action)) $$render(consequent_20);
  4113. },
  4114. $$elseif
  4115. );
  4116. }
  4117. };
  4118. if_block(node_27, ($$render) => {
  4119. if (typeof $$props.toast.action === "function") $$render(consequent_19);
  4120. else $$render(alternate_10, false);
  4121. });
  4122. }
  4123. append($$anchor3, fragment_20);
  4124. };
  4125. if_block(node_26, ($$render) => {
  4126. if ($$props.toast.action) $$render(consequent_21);
  4127. });
  4128. }
  4129. template_effect(($0) => set_class(div_3, 1, $0), [
  4130. () => {
  4131. var _a2, _b, _c;
  4132. 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));
  4133. }
  4134. ]);
  4135. append($$anchor2, fragment_3);
  4136. };
  4137. if_block(node_4, ($$render) => {
  4138. if ($$props.toast.component) $$render(consequent_2);
  4139. else $$render(alternate_1, false);
  4140. });
  4141. }
  4142. bind_this(li, ($$value) => set(toastRef, $$value), () => get(toastRef));
  4143. template_effect(
  4144. ($0, $1, $2) => {
  4145. set_class(li, 1, $0);
  4146. set_attribute(li, "data-rich-colors", $$props.toast.richColors ?? defaultRichColors());
  4147. set_attribute(li, "data-styled", !($$props.toast.component || $$props.toast.unstyled || unstyled()));
  4148. set_attribute(li, "data-mounted", get(mounted));
  4149. set_attribute(li, "data-promise", $1);
  4150. set_attribute(li, "data-swiped", get(isSwiped));
  4151. set_attribute(li, "data-removed", get(removed));
  4152. set_attribute(li, "data-visible", get(isVisible));
  4153. set_attribute(li, "data-y-position", get(coords)[0]);
  4154. set_attribute(li, "data-x-position", get(coords)[1]);
  4155. set_attribute(li, "data-index", $$props.index);
  4156. set_attribute(li, "data-front", get(isFront));
  4157. set_attribute(li, "data-swiping", get(swiping));
  4158. set_attribute(li, "data-dismissable", get(dismissable));
  4159. set_attribute(li, "data-type", get(toastType));
  4160. set_attribute(li, "data-invert", get(invert));
  4161. set_attribute(li, "data-swipe-out", get(swipeOut));
  4162. set_attribute(li, "data-swipe-direction", get(swipeOutDirection));
  4163. set_attribute(li, "data-expanded", $2);
  4164. styles = set_style(li, `${$$props.style} ${$$props.toast.style}`, styles, {
  4165. "--index": $$props.index,
  4166. "--toasts-before": $$props.index,
  4167. "--z-index": toastState.toasts.length - $$props.index,
  4168. "--offset": `${get(removed) ? get(offsetBeforeRemove) : get(offset)}px`,
  4169. "--initial-height": $$props.expandByDefault ? "auto" : `${get(initialHeight)}px`
  4170. });
  4171. },
  4172. [
  4173. () => {
  4174. var _a2, _b, _c, _d, _e, _f;
  4175. 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)]));
  4176. },
  4177. () => Boolean($$props.toast.promise),
  4178. () => Boolean($$props.expanded || $$props.expandByDefault && get(mounted))
  4179. ]
  4180. );
  4181. event("dragend", li, handleDragEnd);
  4182. append($$anchor, li);
  4183. pop();
  4184. }
  4185. delegate([
  4186. "pointermove",
  4187. "pointerup",
  4188. "pointerdown",
  4189. "click"
  4190. ]);
  4191. var root$7 = /* @__PURE__ */ ns_template(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" height="20" width="20" data-sonner-success-icon=""><path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z" clip-rule="evenodd"></path></svg>`);
  4192. function SuccessIcon($$anchor) {
  4193. var svg = root$7();
  4194. append($$anchor, svg);
  4195. }
  4196. var root$6 = /* @__PURE__ */ ns_template(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" height="20" width="20" data-sonner-error-icon=""><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd"></path></svg>`);
  4197. function ErrorIcon($$anchor) {
  4198. var svg = root$6();
  4199. append($$anchor, svg);
  4200. }
  4201. var root$5 = /* @__PURE__ */ ns_template(`<svg viewBox="0 0 64 64" fill="currentColor" height="20" width="20" data-sonner-warning-icon="" xmlns="http://www.w3.org/2000/svg"><path d="M32.427,7.987c2.183,0.124 4,1.165 5.096,3.281l17.936,36.208c1.739,3.66 -0.954,8.585 -5.373,8.656l-36.119,0c-4.022,-0.064 -7.322,-4.631 -5.352,-8.696l18.271,-36.207c0.342,-0.65 0.498,-0.838 0.793,-1.179c1.186,-1.375 2.483,-2.111 4.748,-2.063Zm-0.295,3.997c-0.687,0.034 -1.316,0.419 -1.659,1.017c-6.312,11.979 -12.397,24.081 -18.301,36.267c-0.546,1.225 0.391,2.797 1.762,2.863c12.06,0.195 24.125,0.195 36.185,0c1.325,-0.064 2.321,-1.584 1.769,-2.85c-5.793,-12.184 -11.765,-24.286 -17.966,-36.267c-0.366,-0.651 -0.903,-1.042 -1.79,-1.03Z"></path><path d="M33.631,40.581l-3.348,0l-0.368,-16.449l4.1,0l-0.384,16.449Zm-3.828,5.03c0,-0.609 0.197,-1.113 0.592,-1.514c0.396,-0.4 0.935,-0.601 1.618,-0.601c0.684,0 1.223,0.201 1.618,0.601c0.395,0.401 0.593,0.905 0.593,1.514c0,0.587 -0.193,1.078 -0.577,1.473c-0.385,0.395 -0.929,0.593 -1.634,0.593c-0.705,0 -1.249,-0.198 -1.634,-0.593c-0.384,-0.395 -0.576,-0.886 -0.576,-1.473Z"></path></svg>`);
  4202. function WarningIcon($$anchor) {
  4203. var svg = root$5();
  4204. append($$anchor, svg);
  4205. }
  4206. var root$4 = /* @__PURE__ */ ns_template(`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" height="20" width="20" data-sonner-info-icon=""><path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z" clip-rule="evenodd"></path></svg>`);
  4207. function InfoIcon($$anchor) {
  4208. var svg = root$4();
  4209. append($$anchor, svg);
  4210. }
  4211. var root$3 = /* @__PURE__ */ ns_template(`<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" data-sonner-close-icon=""><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`);
  4212. function CloseIcon($$anchor) {
  4213. var svg = root$3();
  4214. append($$anchor, svg);
  4215. }
  4216. const VISIBLE_TOASTS_AMOUNT = 3;
  4217. const VIEWPORT_OFFSET = "24px";
  4218. const MOBILE_VIEWPORT_OFFSET = "16px";
  4219. const TOAST_LIFETIME = 4e3;
  4220. const TOAST_WIDTH = 356;
  4221. const GAP = 14;
  4222. const DARK = "dark";
  4223. const LIGHT = "light";
  4224. function getOffsetObject(defaultOffset, mobileOffset) {
  4225. const styles = {};
  4226. [defaultOffset, mobileOffset].forEach((offset, index) => {
  4227. const isMobile = index === 1;
  4228. const prefix = isMobile ? "--mobile-offset" : "--offset";
  4229. const defaultValue = isMobile ? MOBILE_VIEWPORT_OFFSET : VIEWPORT_OFFSET;
  4230. function assignAll(offset2) {
  4231. ["top", "right", "bottom", "left"].forEach((key) => {
  4232. styles[`${prefix}-${key}`] = typeof offset2 === "number" ? `${offset2}px` : offset2;
  4233. });
  4234. }
  4235. if (typeof offset === "number" || typeof offset === "string") {
  4236. assignAll(offset);
  4237. } else if (typeof offset === "object") {
  4238. ["top", "right", "bottom", "left"].forEach((key) => {
  4239. const value = offset[key];
  4240. if (value === void 0) {
  4241. styles[`${prefix}-${key}`] = defaultValue;
  4242. } else {
  4243. styles[`${prefix}-${key}`] = typeof value === "number" ? `${value}px` : value;
  4244. }
  4245. });
  4246. } else {
  4247. assignAll(defaultValue);
  4248. }
  4249. });
  4250. return styles;
  4251. }
  4252. var root_2$1 = /* @__PURE__ */ template(`<ol></ol>`);
  4253. var root$2 = /* @__PURE__ */ template(`<section aria-live="polite" aria-relevant="additions text" aria-atomic="false" class="svelte-xsmi9t"><!></section>`);
  4254. function Toaster($$anchor, $$props) {
  4255. push($$props, true);
  4256. function getInitialTheme(t) {
  4257. if (t !== "system") return t;
  4258. if (typeof window !== "undefined") {
  4259. if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
  4260. return DARK;
  4261. }
  4262. return LIGHT;
  4263. }
  4264. return LIGHT;
  4265. }
  4266. function getDocumentDirection() {
  4267. if (typeof window === "undefined") return "ltr";
  4268. if (typeof document === "undefined") return "ltr";
  4269. const dirAttribute = document.documentElement.getAttribute("dir");
  4270. if (dirAttribute === "auto" || !dirAttribute) {
  4271. return window.getComputedStyle(document.documentElement).direction;
  4272. }
  4273. return dirAttribute;
  4274. }
  4275. 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, [
  4276. "$$slots",
  4277. "$$events",
  4278. "$$legacy",
  4279. "invert",
  4280. "position",
  4281. "hotkey",
  4282. "expand",
  4283. "closeButton",
  4284. "offset",
  4285. "mobileOffset",
  4286. "theme",
  4287. "richColors",
  4288. "duration",
  4289. "visibleToasts",
  4290. "toastOptions",
  4291. "dir",
  4292. "gap",
  4293. "loadingIcon",
  4294. "successIcon",
  4295. "errorIcon",
  4296. "warningIcon",
  4297. "closeIcon",
  4298. "infoIcon",
  4299. "containerAriaLabel",
  4300. "class",
  4301. "closeButtonAriaLabel"
  4302. ]);
  4303. const possiblePositions = /* @__PURE__ */ user_derived(() => Array.from(new Set([
  4304. position(),
  4305. ...toastState.toasts.filter((toast2) => toast2.position).map((toast2) => toast2.position)
  4306. ].filter(Boolean))));
  4307. let expanded = /* @__PURE__ */ state(false);
  4308. let interacting = /* @__PURE__ */ state(false);
  4309. let actualTheme = /* @__PURE__ */ state(proxy(getInitialTheme(theme())));
  4310. let listRef = /* @__PURE__ */ state(void 0);
  4311. let lastFocusedElementRef = /* @__PURE__ */ state(null);
  4312. let isFocusWithin = /* @__PURE__ */ state(false);
  4313. const hotkeyLabel = /* @__PURE__ */ user_derived(() => hotkey().join("+").replace(/Key/g, "").replace(/Digit/g, ""));
  4314. user_effect(() => {
  4315. if (toastState.toasts.length <= 1) {
  4316. set(expanded, false);
  4317. }
  4318. });
  4319. user_effect(() => {
  4320. const toastsToDismiss = toastState.toasts.filter((toast2) => toast2.dismiss && !toast2.delete);
  4321. if (toastsToDismiss.length > 0) {
  4322. const updatedToasts = toastState.toasts.map((toast2) => {
  4323. const matchingToast = toastsToDismiss.find((dismissToast) => dismissToast.id === toast2.id);
  4324. if (matchingToast) {
  4325. return { ...toast2, delete: true };
  4326. }
  4327. return toast2;
  4328. });
  4329. toastState.toasts = updatedToasts;
  4330. }
  4331. });
  4332. user_effect(() => {
  4333. return () => {
  4334. if (get(listRef) && get(lastFocusedElementRef)) {
  4335. get(lastFocusedElementRef).focus({ preventScroll: true });
  4336. set(lastFocusedElementRef, null);
  4337. set(isFocusWithin, false);
  4338. }
  4339. };
  4340. });
  4341. onMount(() => {
  4342. toastState.reset();
  4343. const handleKeydown = (event2) => {
  4344. var _a2, _b;
  4345. const isHotkeyPressed = hotkey().every((key) => (
  4346. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  4347. event2[key] || event2.code === key
  4348. ));
  4349. if (isHotkeyPressed) {
  4350. set(expanded, true);
  4351. (_a2 = get(listRef)) == null ? void 0 : _a2.focus();
  4352. }
  4353. if (event2.code === "Escape" && (document.activeElement === get(listRef) || ((_b = get(listRef)) == null ? void 0 : _b.contains(document.activeElement)))) {
  4354. set(expanded, false);
  4355. }
  4356. };
  4357. document.addEventListener("keydown", handleKeydown);
  4358. return () => {
  4359. document.removeEventListener("keydown", handleKeydown);
  4360. };
  4361. });
  4362. user_effect(() => {
  4363. if (theme() !== "system") {
  4364. set(actualTheme, theme());
  4365. }
  4366. if (typeof window !== "undefined") {
  4367. if (theme() === "system") {
  4368. if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
  4369. set(actualTheme, DARK);
  4370. } else {
  4371. set(actualTheme, LIGHT);
  4372. }
  4373. }
  4374. const mediaQueryList = window.matchMedia("(prefers-color-scheme: dark)");
  4375. const changeHandler = ({ matches }) => {
  4376. set(actualTheme, matches ? DARK : LIGHT, true);
  4377. };
  4378. if ("addEventListener" in mediaQueryList) {
  4379. mediaQueryList.addEventListener("change", changeHandler);
  4380. } else {
  4381. mediaQueryList.addListener(changeHandler);
  4382. }
  4383. }
  4384. });
  4385. const handleBlur = (event2) => {
  4386. if (get(isFocusWithin) && !event2.currentTarget.contains(event2.relatedTarget)) {
  4387. set(isFocusWithin, false);
  4388. if (get(lastFocusedElementRef)) {
  4389. get(lastFocusedElementRef).focus({ preventScroll: true });
  4390. set(lastFocusedElementRef, null);
  4391. }
  4392. }
  4393. };
  4394. const handleFocus = (event2) => {
  4395. const isNotDismissable = event2.target instanceof HTMLElement && event2.target.dataset.dismissable === "false";
  4396. if (isNotDismissable) return;
  4397. if (!get(isFocusWithin)) {
  4398. set(isFocusWithin, true);
  4399. set(lastFocusedElementRef, event2.relatedTarget, true);
  4400. }
  4401. };
  4402. const handlePointerDown = (event2) => {
  4403. const isNotDismissable = event2.target instanceof HTMLElement && event2.target.dataset.dismissable === "false";
  4404. if (isNotDismissable) return;
  4405. set(interacting, true);
  4406. };
  4407. const handleMouseEnter = () => {
  4408. set(expanded, true);
  4409. };
  4410. const handleMouseLeave = () => {
  4411. if (!get(interacting)) {
  4412. set(expanded, false);
  4413. }
  4414. };
  4415. const handleMouseMove = () => {
  4416. set(expanded, true);
  4417. };
  4418. const handleDragEnd = () => {
  4419. set(expanded, false);
  4420. };
  4421. const handlePointerUp = () => {
  4422. set(interacting, false);
  4423. };
  4424. sonnerContext.set(new SonnerState());
  4425. var section = root$2();
  4426. set_attribute(section, "tabindex", -1);
  4427. var node = child(section);
  4428. {
  4429. var consequent_10 = ($$anchor2) => {
  4430. var fragment = comment();
  4431. var node_1 = first_child(fragment);
  4432. each(node_1, 18, () => get(possiblePositions), (position2) => position2, ($$anchor3, position2, index, $$array) => {
  4433. var ol = root_2$1();
  4434. const computed_const = /* @__PURE__ */ user_derived(() => {
  4435. const [y2, x] = position2.split("-");
  4436. return { y: y2, x };
  4437. });
  4438. const isLifted = /* @__PURE__ */ user_derived(() => get(expanded) && toastState.toasts.length > 1 && !expand());
  4439. const offsetObject = /* @__PURE__ */ user_derived(() => getOffsetObject(offset(), mobileOffset()));
  4440. let attributes;
  4441. each(ol, 23, () => toastState.toasts.filter((toast2) => !toast2.position && get(index) === 0 || toast2.position === position2), (toast2) => toast2.id, ($$anchor4, toast2, index2, $$array_1) => {
  4442. const expression = /* @__PURE__ */ user_derived(() => {
  4443. var _a2;
  4444. return ((_a2 = toastOptions()) == null ? void 0 : _a2.duration) ?? duration();
  4445. });
  4446. const expression_1 = /* @__PURE__ */ user_derived(() => {
  4447. var _a2;
  4448. return ((_a2 = toastOptions()) == null ? void 0 : _a2.class) ?? "";
  4449. });
  4450. const expression_2 = /* @__PURE__ */ user_derived(() => {
  4451. var _a2;
  4452. return ((_a2 = toastOptions()) == null ? void 0 : _a2.descriptionClass) || "";
  4453. });
  4454. const expression_3 = /* @__PURE__ */ user_derived(() => {
  4455. var _a2;
  4456. return ((_a2 = toastOptions()) == null ? void 0 : _a2.style) ?? "";
  4457. });
  4458. const expression_4 = /* @__PURE__ */ user_derived(() => toastOptions().classes || {});
  4459. const expression_5 = /* @__PURE__ */ user_derived(() => toastOptions().unstyled ?? false);
  4460. const expression_6 = /* @__PURE__ */ user_derived(() => {
  4461. var _a2;
  4462. return ((_a2 = toastOptions()) == null ? void 0 : _a2.cancelButtonStyle) ?? "";
  4463. });
  4464. const expression_7 = /* @__PURE__ */ user_derived(() => {
  4465. var _a2;
  4466. return ((_a2 = toastOptions()) == null ? void 0 : _a2.actionButtonStyle) ?? "";
  4467. });
  4468. const expression_8 = /* @__PURE__ */ user_derived(() => {
  4469. var _a2;
  4470. return ((_a2 = toastOptions()) == null ? void 0 : _a2.closeButtonAriaLabel) ?? closeButtonAriaLabel();
  4471. });
  4472. {
  4473. const successIcon = ($$anchor5) => {
  4474. var fragment_2 = comment();
  4475. var node_2 = first_child(fragment_2);
  4476. {
  4477. var consequent = ($$anchor6) => {
  4478. var fragment_3 = comment();
  4479. var node_3 = first_child(fragment_3);
  4480. snippet(node_3, () => $$props.successIcon ?? noop);
  4481. append($$anchor6, fragment_3);
  4482. };
  4483. var alternate = ($$anchor6, $$elseif) => {
  4484. {
  4485. var consequent_1 = ($$anchor7) => {
  4486. SuccessIcon($$anchor7);
  4487. };
  4488. if_block(
  4489. $$anchor6,
  4490. ($$render) => {
  4491. if ($$props.successIcon !== null) $$render(consequent_1);
  4492. },
  4493. $$elseif
  4494. );
  4495. }
  4496. };
  4497. if_block(node_2, ($$render) => {
  4498. if ($$props.successIcon) $$render(consequent);
  4499. else $$render(alternate, false);
  4500. });
  4501. }
  4502. append($$anchor5, fragment_2);
  4503. };
  4504. const errorIcon = ($$anchor5) => {
  4505. var fragment_5 = comment();
  4506. var node_4 = first_child(fragment_5);
  4507. {
  4508. var consequent_2 = ($$anchor6) => {
  4509. var fragment_6 = comment();
  4510. var node_5 = first_child(fragment_6);
  4511. snippet(node_5, () => $$props.errorIcon ?? noop);
  4512. append($$anchor6, fragment_6);
  4513. };
  4514. var alternate_1 = ($$anchor6, $$elseif) => {
  4515. {
  4516. var consequent_3 = ($$anchor7) => {
  4517. ErrorIcon($$anchor7);
  4518. };
  4519. if_block(
  4520. $$anchor6,
  4521. ($$render) => {
  4522. if ($$props.errorIcon !== null) $$render(consequent_3);
  4523. },
  4524. $$elseif
  4525. );
  4526. }
  4527. };
  4528. if_block(node_4, ($$render) => {
  4529. if ($$props.errorIcon) $$render(consequent_2);
  4530. else $$render(alternate_1, false);
  4531. });
  4532. }
  4533. append($$anchor5, fragment_5);
  4534. };
  4535. const warningIcon = ($$anchor5) => {
  4536. var fragment_8 = comment();
  4537. var node_6 = first_child(fragment_8);
  4538. {
  4539. var consequent_4 = ($$anchor6) => {
  4540. var fragment_9 = comment();
  4541. var node_7 = first_child(fragment_9);
  4542. snippet(node_7, () => $$props.warningIcon ?? noop);
  4543. append($$anchor6, fragment_9);
  4544. };
  4545. var alternate_2 = ($$anchor6, $$elseif) => {
  4546. {
  4547. var consequent_5 = ($$anchor7) => {
  4548. WarningIcon($$anchor7);
  4549. };
  4550. if_block(
  4551. $$anchor6,
  4552. ($$render) => {
  4553. if ($$props.warningIcon !== null) $$render(consequent_5);
  4554. },
  4555. $$elseif
  4556. );
  4557. }
  4558. };
  4559. if_block(node_6, ($$render) => {
  4560. if ($$props.warningIcon) $$render(consequent_4);
  4561. else $$render(alternate_2, false);
  4562. });
  4563. }
  4564. append($$anchor5, fragment_8);
  4565. };
  4566. const infoIcon = ($$anchor5) => {
  4567. var fragment_11 = comment();
  4568. var node_8 = first_child(fragment_11);
  4569. {
  4570. var consequent_6 = ($$anchor6) => {
  4571. var fragment_12 = comment();
  4572. var node_9 = first_child(fragment_12);
  4573. snippet(node_9, () => $$props.infoIcon ?? noop);
  4574. append($$anchor6, fragment_12);
  4575. };
  4576. var alternate_3 = ($$anchor6, $$elseif) => {
  4577. {
  4578. var consequent_7 = ($$anchor7) => {
  4579. InfoIcon($$anchor7);
  4580. };
  4581. if_block(
  4582. $$anchor6,
  4583. ($$render) => {
  4584. if ($$props.infoIcon !== null) $$render(consequent_7);
  4585. },
  4586. $$elseif
  4587. );
  4588. }
  4589. };
  4590. if_block(node_8, ($$render) => {
  4591. if ($$props.infoIcon) $$render(consequent_6);
  4592. else $$render(alternate_3, false);
  4593. });
  4594. }
  4595. append($$anchor5, fragment_11);
  4596. };
  4597. const closeIcon = ($$anchor5) => {
  4598. var fragment_14 = comment();
  4599. var node_10 = first_child(fragment_14);
  4600. {
  4601. var consequent_8 = ($$anchor6) => {
  4602. var fragment_15 = comment();
  4603. var node_11 = first_child(fragment_15);
  4604. snippet(node_11, () => $$props.closeIcon ?? noop);
  4605. append($$anchor6, fragment_15);
  4606. };
  4607. var alternate_4 = ($$anchor6, $$elseif) => {
  4608. {
  4609. var consequent_9 = ($$anchor7) => {
  4610. CloseIcon($$anchor7);
  4611. };
  4612. if_block(
  4613. $$anchor6,
  4614. ($$render) => {
  4615. if ($$props.closeIcon !== null) $$render(consequent_9);
  4616. },
  4617. $$elseif
  4618. );
  4619. }
  4620. };
  4621. if_block(node_10, ($$render) => {
  4622. if ($$props.closeIcon) $$render(consequent_8);
  4623. else $$render(alternate_4, false);
  4624. });
  4625. }
  4626. append($$anchor5, fragment_14);
  4627. };
  4628. Toast($$anchor4, {
  4629. get index() {
  4630. return get(index2);
  4631. },
  4632. get toast() {
  4633. return get(toast2);
  4634. },
  4635. get defaultRichColors() {
  4636. return richColors();
  4637. },
  4638. get duration() {
  4639. return get(expression);
  4640. },
  4641. get class() {
  4642. return get(expression_1);
  4643. },
  4644. get descriptionClass() {
  4645. return get(expression_2);
  4646. },
  4647. get invert() {
  4648. return invert();
  4649. },
  4650. get visibleToasts() {
  4651. return visibleToasts();
  4652. },
  4653. get closeButton() {
  4654. return closeButton();
  4655. },
  4656. get interacting() {
  4657. return get(interacting);
  4658. },
  4659. get position() {
  4660. return position2;
  4661. },
  4662. get style() {
  4663. return get(expression_3);
  4664. },
  4665. get classes() {
  4666. return get(expression_4);
  4667. },
  4668. get unstyled() {
  4669. return get(expression_5);
  4670. },
  4671. get cancelButtonStyle() {
  4672. return get(expression_6);
  4673. },
  4674. get actionButtonStyle() {
  4675. return get(expression_7);
  4676. },
  4677. get closeButtonAriaLabel() {
  4678. return get(expression_8);
  4679. },
  4680. get expandByDefault() {
  4681. return expand();
  4682. },
  4683. get expanded() {
  4684. return get(expanded);
  4685. },
  4686. get loadingIcon() {
  4687. return $$props.loadingIcon;
  4688. },
  4689. successIcon,
  4690. errorIcon,
  4691. warningIcon,
  4692. infoIcon,
  4693. closeIcon,
  4694. $$slots: {
  4695. successIcon: true,
  4696. errorIcon: true,
  4697. warningIcon: true,
  4698. infoIcon: true,
  4699. closeIcon: true
  4700. }
  4701. });
  4702. }
  4703. });
  4704. bind_this(ol, ($$value) => set(listRef, $$value), () => get(listRef));
  4705. template_effect(
  4706. ($0) => {
  4707. var _a2;
  4708. attributes = set_attributes(
  4709. ol,
  4710. attributes,
  4711. {
  4712. tabindex: -1,
  4713. dir: $0,
  4714. class: $$props.class,
  4715. "data-sonner-toaster": true,
  4716. "data-sonner-theme": get(actualTheme),
  4717. "data-y-position": get(computed_const).y,
  4718. "data-lifted": get(isLifted),
  4719. "data-x-position": get(computed_const).x,
  4720. style: $$props.style,
  4721. onblur: handleBlur,
  4722. onfocus: handleFocus,
  4723. onmouseenter: handleMouseEnter,
  4724. onmousemove: handleMouseMove,
  4725. onmouseleave: handleMouseLeave,
  4726. ondragend: handleDragEnd,
  4727. onpointerdown: handlePointerDown,
  4728. onpointerup: handlePointerUp,
  4729. ...restProps,
  4730. [STYLE]: {
  4731. "--front-toast-height": `${(_a2 = toastState.heights[0]) == null ? void 0 : _a2.height}px`,
  4732. "--width": `${TOAST_WIDTH}px`,
  4733. "--gap": `${gap()}px`,
  4734. "--offset-top": get(offsetObject)["--offset-top"],
  4735. "--offset-right": get(offsetObject)["--offset-right"],
  4736. "--offset-bottom": get(offsetObject)["--offset-bottom"],
  4737. "--offset-left": get(offsetObject)["--offset-left"],
  4738. "--mobile-offset-top": get(offsetObject)["--mobile-offset-top"],
  4739. "--mobile-offset-right": get(offsetObject)["--mobile-offset-right"],
  4740. "--mobile-offset-bottom": get(offsetObject)["--mobile-offset-bottom"],
  4741. "--mobile-offset-left": get(offsetObject)["--mobile-offset-left"]
  4742. }
  4743. },
  4744. "svelte-xsmi9t"
  4745. );
  4746. ol.dir = ol.dir;
  4747. },
  4748. [
  4749. () => dir() === "auto" ? getDocumentDirection() : dir()
  4750. ]
  4751. );
  4752. append($$anchor3, ol);
  4753. });
  4754. append($$anchor2, fragment);
  4755. };
  4756. if_block(node, ($$render) => {
  4757. if (toastState.toasts.length > 0) $$render(consequent_10);
  4758. });
  4759. }
  4760. template_effect(() => set_attribute(section, "aria-label", `${containerAriaLabel() ?? ""} ${get(hotkeyLabel) ?? ""}`));
  4761. append($$anchor, section);
  4762. pop();
  4763. }
  4764. const CONFIG = {
  4765. APP_NAME: "LeetCode Toolkit",
  4766. EDITORIAL_READER_URL: "https://leetcode-editorial-reader.vercel.app"
  4767. };
  4768. const messageToastTypes = [
  4769. "success",
  4770. "info",
  4771. "warning",
  4772. "error",
  4773. "message",
  4774. "loading"
  4775. ];
  4776. function addPrefix(message) {
  4777. if (typeof message === "string") {
  4778. return `${CONFIG.APP_NAME}: ${message}`;
  4779. }
  4780. return message;
  4781. }
  4782. const prefixToast = new Proxy(toast, {
  4783. // Handle direct function calls: toast('message')
  4784. apply(target, thisArg, args) {
  4785. if (args.length > 0) {
  4786. args[0] = addPrefix(args[0]);
  4787. }
  4788. return Reflect.apply(target, thisArg, args);
  4789. },
  4790. get(target, prop2, receiver) {
  4791. const originalProp = Reflect.get(target, prop2, receiver);
  4792. if (typeof originalProp === "function" && messageToastTypes.includes(prop2.toString())) {
  4793. return (...args) => {
  4794. if (args.length > 0) {
  4795. args[0] = addPrefix(args[0]);
  4796. }
  4797. return originalProp.apply(this, args);
  4798. };
  4799. }
  4800. if (prop2 === "promise") {
  4801. return (...args) => {
  4802. const [promise, data] = args;
  4803. if (!data) return originalProp;
  4804. const prefixedData = {
  4805. ...data,
  4806. loading: typeof data.loading === "string" ? addPrefix(data.loading) : data.loading,
  4807. success: typeof data.success === "string" ? addPrefix(data.success) : data.success,
  4808. error: typeof data.error === "string" ? addPrefix(data.error) : data.error
  4809. };
  4810. return originalProp.call(this, promise, prefixedData);
  4811. };
  4812. }
  4813. return originalProp;
  4814. }
  4815. });
  4816. class GlobalState {
  4817. constructor() {
  4818. __privateAdd(this, _site);
  4819. }
  4820. get site() {
  4821. if (!__privateGet(this, _site)) {
  4822. const hostname = window.location.hostname;
  4823. __privateSet(this, _site, hostname === "leetcode.cn" ? "cn" : "global");
  4824. }
  4825. return __privateGet(this, _site);
  4826. }
  4827. }
  4828. _site = new WeakMap();
  4829. const globalState = new GlobalState();
  4830. var _GM_getResourceText = /* @__PURE__ */ (() => typeof GM_getResourceText != "undefined" ? GM_getResourceText : void 0)();
  4831. var _unsafeWindow = /* @__PURE__ */ (() => typeof unsafeWindow != "undefined" ? unsafeWindow : void 0)();
  4832. class TimeoutError extends Error {
  4833. constructor(item, timeout) {
  4834. super();
  4835. __publicField(this, "name", this.constructor.name);
  4836. this.message = `"${item}" not found within timeout (${timeout}ms)`;
  4837. }
  4838. }
  4839. function find(finderFn, {
  4840. subject = document,
  4841. observerOption = {
  4842. childList: true,
  4843. subtree: true
  4844. },
  4845. timeout = 5e3,
  4846. itemName = "Item"
  4847. }) {
  4848. return new Promise((resolve, reject) => {
  4849. const item = finderFn();
  4850. if (item) return resolve(item);
  4851. let timeoutId;
  4852. const observer = new MutationObserver(() => {
  4853. const item2 = finderFn();
  4854. if (item2) {
  4855. observer.disconnect();
  4856. clearTimeout(timeoutId);
  4857. return resolve(item2);
  4858. }
  4859. });
  4860. observer.observe(subject, observerOption);
  4861. if (timeout > 0) {
  4862. timeoutId = setTimeout(() => {
  4863. observer.disconnect();
  4864. prefixToast.error(
  4865. `${itemName} not found within timeout. Please refresh the page or disable the script.`
  4866. );
  4867. const error = new TimeoutError(itemName, timeout);
  4868. console.error(error);
  4869. return reject(error);
  4870. }, timeout);
  4871. }
  4872. });
  4873. }
  4874. async function findElement(selector, {
  4875. parent = document,
  4876. timeout = 500,
  4877. additionalRule
  4878. } = {}) {
  4879. const element = await find(
  4880. () => {
  4881. const el = parent.querySelector(selector);
  4882. if (additionalRule && el) {
  4883. return additionalRule(el) ? el : null;
  4884. } else {
  4885. return el;
  4886. }
  4887. },
  4888. {
  4889. subject: parent,
  4890. timeout,
  4891. itemName: `Element ${selector}`
  4892. }
  4893. );
  4894. return element;
  4895. }
  4896. const overrideOptions = {
  4897. selectionHighlight: true,
  4898. parameterHints: { enabled: true },
  4899. hover: { enabled: true },
  4900. quickSuggestions: true,
  4901. suggestOnTriggerCharacters: true,
  4902. "bracketPairColorization.enabled": true
  4903. };
  4904. function addIntellisense(editor) {
  4905. const originalUpdateOptions = editor.updateOptions.bind(editor);
  4906. editor.updateOptions = (options) => {
  4907. originalUpdateOptions({
  4908. ...options,
  4909. ...overrideOptions
  4910. });
  4911. };
  4912. }
  4913. async function findMonacoEditor() {
  4914. function getEditor() {
  4915. var _a2;
  4916. return ((_a2 = _unsafeWindow.monaco) == null ? void 0 : _a2.editor.getEditors()[0]) ?? null;
  4917. }
  4918. const editor = find(getEditor, {
  4919. subject: document.head,
  4920. observerOption: { childList: true },
  4921. itemName: "Monaco Editor"
  4922. });
  4923. return editor;
  4924. }
  4925. class ProblemPageState {
  4926. constructor() {
  4927. __publicField(this, "editor", null);
  4928. }
  4929. async patchMonacoEditor() {
  4930. this.editor = await findMonacoEditor();
  4931. this.enableFormatOnSave();
  4932. addIntellisense(this.editor);
  4933. }
  4934. enableFormatOnSave() {
  4935. document.addEventListener("keydown", async (e2) => {
  4936. var _a2, _b;
  4937. if (!(e2.ctrlKey && e2.key === "s")) return;
  4938. try {
  4939. await ((_b = (_a2 = this.editor) == null ? void 0 : _a2.getAction("editor.action.formatDocument")) == null ? void 0 : _b.run());
  4940. } catch (err) {
  4941. console.error(err);
  4942. if (err instanceof Error) {
  4943. toast.error("Failed to format code:" + err.message);
  4944. }
  4945. }
  4946. });
  4947. }
  4948. }
  4949. const problemState = new ProblemPageState();
  4950. function u$1(o2, n, a2) {
  4951. let t = (r2) => o2(r2, ...n);
  4952. return t;
  4953. }
  4954. function u(r2, n, o2) {
  4955. let a2 = r2.length - n.length;
  4956. if (a2 === 0) return r2(...n);
  4957. if (a2 === 1) return u$1(r2, n);
  4958. throw new Error("Wrong number of arguments");
  4959. }
  4960. var o$1 = [" ", `
  4961. `, "\v", "\f", "\r", " ", "…", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "\u2028", "\u2029", " ", " ", " ", "\uFEFF"], c = /* @__PURE__ */ new Set(["-", "_", ...o$1]), i = (r2) => {
  4962. let e2 = [], t = "", u2 = () => {
  4963. t.length > 0 && (e2.push(t), t = "");
  4964. };
  4965. for (let s of r2) {
  4966. if (c.has(s)) {
  4967. u2();
  4968. continue;
  4969. }
  4970. if (/[a-z]$/u.test(t) && /[A-Z]/u.test(s)) u2();
  4971. else if (/[A-Z][A-Z]$/u.test(t) && /[a-z]/u.test(s)) {
  4972. let n = t.slice(-1);
  4973. t = t.slice(0, -1), u2(), t = n;
  4974. } else /\d$/u.test(t) !== /\d/u.test(s) && u2();
  4975. t += s;
  4976. }
  4977. return u2(), e2;
  4978. };
  4979. function a(...e2) {
  4980. return u(o, e2);
  4981. }
  4982. var o = (e2) => i(e2).join("-").toLowerCase();
  4983. function e(o2) {
  4984. return o2 instanceof Promise;
  4985. }
  4986. var root$1 = /* @__PURE__ */ template(`<div><!></div>`);
  4987. function ButtonGroup($$anchor, $$props) {
  4988. let props = /* @__PURE__ */ rest_props($$props, [
  4989. "$$slots",
  4990. "$$events",
  4991. "$$legacy",
  4992. "children"
  4993. ]);
  4994. var div = root$1();
  4995. let attributes;
  4996. var node = child(div);
  4997. snippet(node, () => $$props.children);
  4998. template_effect(() => attributes = set_attributes(div, attributes, { ...props }, "svelte-4mbyk0"));
  4999. append($$anchor, div);
  5000. }
  5001. const mouseClickEvents = ["mousedown", "mouseup", "click"];
  5002. function simulateMouseClickReact(element) {
  5003. mouseClickEvents.forEach(
  5004. (mouseEventType) => element.dispatchEvent(
  5005. new MouseEvent(mouseEventType, {
  5006. view: _unsafeWindow,
  5007. bubbles: true,
  5008. cancelable: true,
  5009. buttons: 1
  5010. })
  5011. )
  5012. );
  5013. }
  5014. const loaderIcon = ($$anchor) => {
  5015. var svg = root_1$3();
  5016. append($$anchor, svg);
  5017. };
  5018. var root_1$3 = /* @__PURE__ */ ns_template(`<svg class="animate-spin" xmlns="http://www.w3.org/2000/svg" width="1rem" height="1rem" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 2v4m4.2 1.8l2.9-2.9M18 12h4m-5.8 4.2l2.9 2.9M12 18v4m-7.1-2.9l2.9-2.9M2 12h4M4.9 4.9l2.9 2.9"></path></svg>`);
  5019. var root_2 = /* @__PURE__ */ template(`<a><!></a>`);
  5020. var root_3 = /* @__PURE__ */ template(`<button><!> <!></button>`);
  5021. function Button($$anchor, $$props) {
  5022. push($$props, true);
  5023. let variant = prop($$props, "variant", 3, "purple"), type = prop($$props, "type", 3, "button"), restProps = /* @__PURE__ */ rest_props($$props, [
  5024. "$$slots",
  5025. "$$events",
  5026. "$$legacy",
  5027. "onclick",
  5028. "children",
  5029. "variant",
  5030. "type",
  5031. "href"
  5032. ]);
  5033. const variants = {
  5034. purple: "--bg: #6c5ce7; --shadow: #a29bfe",
  5035. green: "--bg: #1ba13e; --shadow: #42de6e",
  5036. orange: "--bg: #ffa116; --shadow: #fedd9b"
  5037. };
  5038. let loading = /* @__PURE__ */ state(false);
  5039. async function handleOnClick(e$1) {
  5040. if (!$$props.onclick) return;
  5041. const returnValue = $$props.onclick(e$1);
  5042. if (e(returnValue)) {
  5043. set(loading, true);
  5044. await returnValue;
  5045. set(loading, false);
  5046. }
  5047. }
  5048. var fragment = comment();
  5049. var node = first_child(fragment);
  5050. {
  5051. var consequent = ($$anchor2) => {
  5052. var a2 = root_2();
  5053. let attributes;
  5054. var node_1 = child(a2);
  5055. snippet(node_1, () => $$props.children ?? noop);
  5056. template_effect(() => attributes = set_attributes(
  5057. a2,
  5058. attributes,
  5059. {
  5060. style: variants[variant()],
  5061. href: $$props.href,
  5062. target: "_blank",
  5063. ...restProps
  5064. },
  5065. "svelte-ll0ynk"
  5066. ));
  5067. append($$anchor2, a2);
  5068. };
  5069. var alternate = ($$anchor2) => {
  5070. var button = root_3();
  5071. let attributes_1;
  5072. var node_2 = child(button);
  5073. {
  5074. var consequent_1 = ($$anchor3) => {
  5075. loaderIcon($$anchor3);
  5076. };
  5077. if_block(node_2, ($$render) => {
  5078. if (get(loading)) $$render(consequent_1);
  5079. });
  5080. }
  5081. var node_3 = sibling(node_2, 2);
  5082. snippet(node_3, () => $$props.children ?? noop);
  5083. template_effect(() => attributes_1 = set_attributes(
  5084. button,
  5085. attributes_1,
  5086. {
  5087. style: variants[variant()],
  5088. type: type(),
  5089. disabled: get(loading),
  5090. onclick: handleOnClick,
  5091. ...restProps
  5092. },
  5093. "svelte-ll0ynk"
  5094. ));
  5095. append($$anchor2, button);
  5096. };
  5097. if_block(node, ($$render) => {
  5098. if ($$props.href) $$render(consequent);
  5099. else $$render(alternate, false);
  5100. });
  5101. }
  5102. append($$anchor, fragment);
  5103. pop();
  5104. }
  5105. async function copy(text2, toastId) {
  5106. try {
  5107. await navigator.clipboard.writeText(text2);
  5108. prefixToast.success(
  5109. globalState.site === "cn" ? "复制到剪贴板!" : "Copied to clipboard!",
  5110. {
  5111. id: toastId
  5112. // update an already present toast, if given the id of that toast
  5113. }
  5114. );
  5115. } catch (err) {
  5116. if (err instanceof Error) {
  5117. const errorMessage = globalState.site === "cn" ? "复制失败" : "Failed to copy";
  5118. prefixToast.error(errorMessage + ": " + err.message, {
  5119. id: toastId
  5120. });
  5121. console.error(errorMessage + err);
  5122. } else throw err;
  5123. }
  5124. }
  5125. const getTitle = async () => {
  5126. const descriptionTabButton = (await findElement("#description_tab")).closest(".flexlayout__tab_button");
  5127. if (!(descriptionTabButton == null ? void 0 : descriptionTabButton.classList.contains(".flexlayout__tab_button--selected"))) {
  5128. simulateMouseClickReact(descriptionTabButton);
  5129. }
  5130. return (await findElement(".text-title-large")).textContent ?? "";
  5131. };
  5132. function Copy_title($$anchor, $$props) {
  5133. push($$props, false);
  5134. async function copyTitle() {
  5135. copy(await getTitle());
  5136. }
  5137. init();
  5138. Button($$anchor, {
  5139. onclick: copyTitle,
  5140. children: ($$anchor2, $$slotProps) => {
  5141. var text$1 = text();
  5142. template_effect(() => set_text(text$1, globalState.site === "cn" ? "复制标题" : "Copy Title"));
  5143. append($$anchor2, text$1);
  5144. },
  5145. $$slots: { default: true }
  5146. });
  5147. pop();
  5148. }
  5149. function extend(destination) {
  5150. for (var i2 = 1; i2 < arguments.length; i2++) {
  5151. var source2 = arguments[i2];
  5152. for (var key in source2) {
  5153. if (source2.hasOwnProperty(key)) destination[key] = source2[key];
  5154. }
  5155. }
  5156. return destination;
  5157. }
  5158. function repeat(character, count) {
  5159. return Array(count + 1).join(character);
  5160. }
  5161. function trimLeadingNewlines(string) {
  5162. return string.replace(/^\n*/, "");
  5163. }
  5164. function trimTrailingNewlines(string) {
  5165. var indexEnd = string.length;
  5166. while (indexEnd > 0 && string[indexEnd - 1] === "\n") indexEnd--;
  5167. return string.substring(0, indexEnd);
  5168. }
  5169. var blockElements = [
  5170. "ADDRESS",
  5171. "ARTICLE",
  5172. "ASIDE",
  5173. "AUDIO",
  5174. "BLOCKQUOTE",
  5175. "BODY",
  5176. "CANVAS",
  5177. "CENTER",
  5178. "DD",
  5179. "DIR",
  5180. "DIV",
  5181. "DL",
  5182. "DT",
  5183. "FIELDSET",
  5184. "FIGCAPTION",
  5185. "FIGURE",
  5186. "FOOTER",
  5187. "FORM",
  5188. "FRAMESET",
  5189. "H1",
  5190. "H2",
  5191. "H3",
  5192. "H4",
  5193. "H5",
  5194. "H6",
  5195. "HEADER",
  5196. "HGROUP",
  5197. "HR",
  5198. "HTML",
  5199. "ISINDEX",
  5200. "LI",
  5201. "MAIN",
  5202. "MENU",
  5203. "NAV",
  5204. "NOFRAMES",
  5205. "NOSCRIPT",
  5206. "OL",
  5207. "OUTPUT",
  5208. "P",
  5209. "PRE",
  5210. "SECTION",
  5211. "TABLE",
  5212. "TBODY",
  5213. "TD",
  5214. "TFOOT",
  5215. "TH",
  5216. "THEAD",
  5217. "TR",
  5218. "UL"
  5219. ];
  5220. function isBlock(node) {
  5221. return is(node, blockElements);
  5222. }
  5223. var voidElements = [
  5224. "AREA",
  5225. "BASE",
  5226. "BR",
  5227. "COL",
  5228. "COMMAND",
  5229. "EMBED",
  5230. "HR",
  5231. "IMG",
  5232. "INPUT",
  5233. "KEYGEN",
  5234. "LINK",
  5235. "META",
  5236. "PARAM",
  5237. "SOURCE",
  5238. "TRACK",
  5239. "WBR"
  5240. ];
  5241. function isVoid(node) {
  5242. return is(node, voidElements);
  5243. }
  5244. function hasVoid(node) {
  5245. return has(node, voidElements);
  5246. }
  5247. var meaningfulWhenBlankElements = [
  5248. "A",
  5249. "TABLE",
  5250. "THEAD",
  5251. "TBODY",
  5252. "TFOOT",
  5253. "TH",
  5254. "TD",
  5255. "IFRAME",
  5256. "SCRIPT",
  5257. "AUDIO",
  5258. "VIDEO"
  5259. ];
  5260. function isMeaningfulWhenBlank(node) {
  5261. return is(node, meaningfulWhenBlankElements);
  5262. }
  5263. function hasMeaningfulWhenBlank(node) {
  5264. return has(node, meaningfulWhenBlankElements);
  5265. }
  5266. function is(node, tagNames) {
  5267. return tagNames.indexOf(node.nodeName) >= 0;
  5268. }
  5269. function has(node, tagNames) {
  5270. return node.getElementsByTagName && tagNames.some(function(tagName) {
  5271. return node.getElementsByTagName(tagName).length;
  5272. });
  5273. }
  5274. var rules = {};
  5275. rules.paragraph = {
  5276. filter: "p",
  5277. replacement: function(content) {
  5278. return "\n\n" + content + "\n\n";
  5279. }
  5280. };
  5281. rules.lineBreak = {
  5282. filter: "br",
  5283. replacement: function(content, node, options) {
  5284. return options.br + "\n";
  5285. }
  5286. };
  5287. rules.heading = {
  5288. filter: ["h1", "h2", "h3", "h4", "h5", "h6"],
  5289. replacement: function(content, node, options) {
  5290. var hLevel = Number(node.nodeName.charAt(1));
  5291. if (options.headingStyle === "setext" && hLevel < 3) {
  5292. var underline = repeat(hLevel === 1 ? "=" : "-", content.length);
  5293. return "\n\n" + content + "\n" + underline + "\n\n";
  5294. } else {
  5295. return "\n\n" + repeat("#", hLevel) + " " + content + "\n\n";
  5296. }
  5297. }
  5298. };
  5299. rules.blockquote = {
  5300. filter: "blockquote",
  5301. replacement: function(content) {
  5302. content = content.replace(/^\n+|\n+$/g, "");
  5303. content = content.replace(/^/gm, "> ");
  5304. return "\n\n" + content + "\n\n";
  5305. }
  5306. };
  5307. rules.list = {
  5308. filter: ["ul", "ol"],
  5309. replacement: function(content, node) {
  5310. var parent = node.parentNode;
  5311. if (parent.nodeName === "LI" && parent.lastElementChild === node) {
  5312. return "\n" + content;
  5313. } else {
  5314. return "\n\n" + content + "\n\n";
  5315. }
  5316. }
  5317. };
  5318. rules.listItem = {
  5319. filter: "li",
  5320. replacement: function(content, node, options) {
  5321. content = content.replace(/^\n+/, "").replace(/\n+$/, "\n").replace(/\n/gm, "\n ");
  5322. var prefix = options.bulletListMarker + " ";
  5323. var parent = node.parentNode;
  5324. if (parent.nodeName === "OL") {
  5325. var start = parent.getAttribute("start");
  5326. var index = Array.prototype.indexOf.call(parent.children, node);
  5327. prefix = (start ? Number(start) + index : index + 1) + ". ";
  5328. }
  5329. return prefix + content + (node.nextSibling && !/\n$/.test(content) ? "\n" : "");
  5330. }
  5331. };
  5332. rules.indentedCodeBlock = {
  5333. filter: function(node, options) {
  5334. return options.codeBlockStyle === "indented" && node.nodeName === "PRE" && node.firstChild && node.firstChild.nodeName === "CODE";
  5335. },
  5336. replacement: function(content, node, options) {
  5337. return "\n\n " + node.firstChild.textContent.replace(/\n/g, "\n ") + "\n\n";
  5338. }
  5339. };
  5340. rules.fencedCodeBlock = {
  5341. filter: function(node, options) {
  5342. return options.codeBlockStyle === "fenced" && node.nodeName === "PRE" && node.firstChild && node.firstChild.nodeName === "CODE";
  5343. },
  5344. replacement: function(content, node, options) {
  5345. var className = node.firstChild.getAttribute("class") || "";
  5346. var language = (className.match(/language-(\S+)/) || [null, ""])[1];
  5347. var code = node.firstChild.textContent;
  5348. var fenceChar = options.fence.charAt(0);
  5349. var fenceSize = 3;
  5350. var fenceInCodeRegex = new RegExp("^" + fenceChar + "{3,}", "gm");
  5351. var match;
  5352. while (match = fenceInCodeRegex.exec(code)) {
  5353. if (match[0].length >= fenceSize) {
  5354. fenceSize = match[0].length + 1;
  5355. }
  5356. }
  5357. var fence = repeat(fenceChar, fenceSize);
  5358. return "\n\n" + fence + language + "\n" + code.replace(/\n$/, "") + "\n" + fence + "\n\n";
  5359. }
  5360. };
  5361. rules.horizontalRule = {
  5362. filter: "hr",
  5363. replacement: function(content, node, options) {
  5364. return "\n\n" + options.hr + "\n\n";
  5365. }
  5366. };
  5367. rules.inlineLink = {
  5368. filter: function(node, options) {
  5369. return options.linkStyle === "inlined" && node.nodeName === "A" && node.getAttribute("href");
  5370. },
  5371. replacement: function(content, node) {
  5372. var href = node.getAttribute("href");
  5373. if (href) href = href.replace(/([()])/g, "\\$1");
  5374. var title = cleanAttribute(node.getAttribute("title"));
  5375. if (title) title = ' "' + title.replace(/"/g, '\\"') + '"';
  5376. return "[" + content + "](" + href + title + ")";
  5377. }
  5378. };
  5379. rules.referenceLink = {
  5380. filter: function(node, options) {
  5381. return options.linkStyle === "referenced" && node.nodeName === "A" && node.getAttribute("href");
  5382. },
  5383. replacement: function(content, node, options) {
  5384. var href = node.getAttribute("href");
  5385. var title = cleanAttribute(node.getAttribute("title"));
  5386. if (title) title = ' "' + title + '"';
  5387. var replacement;
  5388. var reference;
  5389. switch (options.linkReferenceStyle) {
  5390. case "collapsed":
  5391. replacement = "[" + content + "][]";
  5392. reference = "[" + content + "]: " + href + title;
  5393. break;
  5394. case "shortcut":
  5395. replacement = "[" + content + "]";
  5396. reference = "[" + content + "]: " + href + title;
  5397. break;
  5398. default:
  5399. var id = this.references.length + 1;
  5400. replacement = "[" + content + "][" + id + "]";
  5401. reference = "[" + id + "]: " + href + title;
  5402. }
  5403. this.references.push(reference);
  5404. return replacement;
  5405. },
  5406. references: [],
  5407. append: function(options) {
  5408. var references = "";
  5409. if (this.references.length) {
  5410. references = "\n\n" + this.references.join("\n") + "\n\n";
  5411. this.references = [];
  5412. }
  5413. return references;
  5414. }
  5415. };
  5416. rules.emphasis = {
  5417. filter: ["em", "i"],
  5418. replacement: function(content, node, options) {
  5419. if (!content.trim()) return "";
  5420. return options.emDelimiter + content + options.emDelimiter;
  5421. }
  5422. };
  5423. rules.strong = {
  5424. filter: ["strong", "b"],
  5425. replacement: function(content, node, options) {
  5426. if (!content.trim()) return "";
  5427. return options.strongDelimiter + content + options.strongDelimiter;
  5428. }
  5429. };
  5430. rules.code = {
  5431. filter: function(node) {
  5432. var hasSiblings = node.previousSibling || node.nextSibling;
  5433. var isCodeBlock = node.parentNode.nodeName === "PRE" && !hasSiblings;
  5434. return node.nodeName === "CODE" && !isCodeBlock;
  5435. },
  5436. replacement: function(content) {
  5437. if (!content) return "";
  5438. content = content.replace(/\r?\n|\r/g, " ");
  5439. var extraSpace = /^`|^ .*?[^ ].* $|`$/.test(content) ? " " : "";
  5440. var delimiter = "`";
  5441. var matches = content.match(/`+/gm) || [];
  5442. while (matches.indexOf(delimiter) !== -1) delimiter = delimiter + "`";
  5443. return delimiter + extraSpace + content + extraSpace + delimiter;
  5444. }
  5445. };
  5446. rules.image = {
  5447. filter: "img",
  5448. replacement: function(content, node) {
  5449. var alt = cleanAttribute(node.getAttribute("alt"));
  5450. var src = node.getAttribute("src") || "";
  5451. var title = cleanAttribute(node.getAttribute("title"));
  5452. var titlePart = title ? ' "' + title + '"' : "";
  5453. return src ? "![" + alt + "](" + src + titlePart + ")" : "";
  5454. }
  5455. };
  5456. function cleanAttribute(attribute) {
  5457. return attribute ? attribute.replace(/(\n+\s*)+/g, "\n") : "";
  5458. }
  5459. function Rules(options) {
  5460. this.options = options;
  5461. this._keep = [];
  5462. this._remove = [];
  5463. this.blankRule = {
  5464. replacement: options.blankReplacement
  5465. };
  5466. this.keepReplacement = options.keepReplacement;
  5467. this.defaultRule = {
  5468. replacement: options.defaultReplacement
  5469. };
  5470. this.array = [];
  5471. for (var key in options.rules) this.array.push(options.rules[key]);
  5472. }
  5473. Rules.prototype = {
  5474. add: function(key, rule) {
  5475. this.array.unshift(rule);
  5476. },
  5477. keep: function(filter) {
  5478. this._keep.unshift({
  5479. filter,
  5480. replacement: this.keepReplacement
  5481. });
  5482. },
  5483. remove: function(filter) {
  5484. this._remove.unshift({
  5485. filter,
  5486. replacement: function() {
  5487. return "";
  5488. }
  5489. });
  5490. },
  5491. forNode: function(node) {
  5492. if (node.isBlank) return this.blankRule;
  5493. var rule;
  5494. if (rule = findRule(this.array, node, this.options)) return rule;
  5495. if (rule = findRule(this._keep, node, this.options)) return rule;
  5496. if (rule = findRule(this._remove, node, this.options)) return rule;
  5497. return this.defaultRule;
  5498. },
  5499. forEach: function(fn) {
  5500. for (var i2 = 0; i2 < this.array.length; i2++) fn(this.array[i2], i2);
  5501. }
  5502. };
  5503. function findRule(rules2, node, options) {
  5504. for (var i2 = 0; i2 < rules2.length; i2++) {
  5505. var rule = rules2[i2];
  5506. if (filterValue(rule, node, options)) return rule;
  5507. }
  5508. return void 0;
  5509. }
  5510. function filterValue(rule, node, options) {
  5511. var filter = rule.filter;
  5512. if (typeof filter === "string") {
  5513. if (filter === node.nodeName.toLowerCase()) return true;
  5514. } else if (Array.isArray(filter)) {
  5515. if (filter.indexOf(node.nodeName.toLowerCase()) > -1) return true;
  5516. } else if (typeof filter === "function") {
  5517. if (filter.call(rule, node, options)) return true;
  5518. } else {
  5519. throw new TypeError("`filter` needs to be a string, array, or function");
  5520. }
  5521. }
  5522. function collapseWhitespace(options) {
  5523. var element = options.element;
  5524. var isBlock2 = options.isBlock;
  5525. var isVoid2 = options.isVoid;
  5526. var isPre = options.isPre || function(node2) {
  5527. return node2.nodeName === "PRE";
  5528. };
  5529. if (!element.firstChild || isPre(element)) return;
  5530. var prevText = null;
  5531. var keepLeadingWs = false;
  5532. var prev = null;
  5533. var node = next(prev, element, isPre);
  5534. while (node !== element) {
  5535. if (node.nodeType === 3 || node.nodeType === 4) {
  5536. var text2 = node.data.replace(/[ \r\n\t]+/g, " ");
  5537. if ((!prevText || / $/.test(prevText.data)) && !keepLeadingWs && text2[0] === " ") {
  5538. text2 = text2.substr(1);
  5539. }
  5540. if (!text2) {
  5541. node = remove(node);
  5542. continue;
  5543. }
  5544. node.data = text2;
  5545. prevText = node;
  5546. } else if (node.nodeType === 1) {
  5547. if (isBlock2(node) || node.nodeName === "BR") {
  5548. if (prevText) {
  5549. prevText.data = prevText.data.replace(/ $/, "");
  5550. }
  5551. prevText = null;
  5552. keepLeadingWs = false;
  5553. } else if (isVoid2(node) || isPre(node)) {
  5554. prevText = null;
  5555. keepLeadingWs = true;
  5556. } else if (prevText) {
  5557. keepLeadingWs = false;
  5558. }
  5559. } else {
  5560. node = remove(node);
  5561. continue;
  5562. }
  5563. var nextNode = next(prev, node, isPre);
  5564. prev = node;
  5565. node = nextNode;
  5566. }
  5567. if (prevText) {
  5568. prevText.data = prevText.data.replace(/ $/, "");
  5569. if (!prevText.data) {
  5570. remove(prevText);
  5571. }
  5572. }
  5573. }
  5574. function remove(node) {
  5575. var next2 = node.nextSibling || node.parentNode;
  5576. node.parentNode.removeChild(node);
  5577. return next2;
  5578. }
  5579. function next(prev, current, isPre) {
  5580. if (prev && prev.parentNode === current || isPre(current)) {
  5581. return current.nextSibling || current.parentNode;
  5582. }
  5583. return current.firstChild || current.nextSibling || current.parentNode;
  5584. }
  5585. var root = typeof window !== "undefined" ? window : {};
  5586. function canParseHTMLNatively() {
  5587. var Parser = root.DOMParser;
  5588. var canParse = false;
  5589. try {
  5590. if (new Parser().parseFromString("", "text/html")) {
  5591. canParse = true;
  5592. }
  5593. } catch (e2) {
  5594. }
  5595. return canParse;
  5596. }
  5597. function createHTMLParser() {
  5598. var Parser = function() {
  5599. };
  5600. {
  5601. if (shouldUseActiveX()) {
  5602. Parser.prototype.parseFromString = function(string) {
  5603. var doc = new window.ActiveXObject("htmlfile");
  5604. doc.designMode = "on";
  5605. doc.open();
  5606. doc.write(string);
  5607. doc.close();
  5608. return doc;
  5609. };
  5610. } else {
  5611. Parser.prototype.parseFromString = function(string) {
  5612. var doc = document.implementation.createHTMLDocument("");
  5613. doc.open();
  5614. doc.write(string);
  5615. doc.close();
  5616. return doc;
  5617. };
  5618. }
  5619. }
  5620. return Parser;
  5621. }
  5622. function shouldUseActiveX() {
  5623. var useActiveX = false;
  5624. try {
  5625. document.implementation.createHTMLDocument("").open();
  5626. } catch (e2) {
  5627. if (root.ActiveXObject) useActiveX = true;
  5628. }
  5629. return useActiveX;
  5630. }
  5631. var HTMLParser = canParseHTMLNatively() ? root.DOMParser : createHTMLParser();
  5632. function RootNode(input, options) {
  5633. var root2;
  5634. if (typeof input === "string") {
  5635. var doc = htmlParser().parseFromString(
  5636. // DOM parsers arrange elements in the <head> and <body>.
  5637. // Wrapping in a custom element ensures elements are reliably arranged in
  5638. // a single element.
  5639. '<x-turndown id="turndown-root">' + input + "</x-turndown>",
  5640. "text/html"
  5641. );
  5642. root2 = doc.getElementById("turndown-root");
  5643. } else {
  5644. root2 = input.cloneNode(true);
  5645. }
  5646. collapseWhitespace({
  5647. element: root2,
  5648. isBlock,
  5649. isVoid,
  5650. isPre: options.preformattedCode ? isPreOrCode : null
  5651. });
  5652. return root2;
  5653. }
  5654. var _htmlParser;
  5655. function htmlParser() {
  5656. _htmlParser = _htmlParser || new HTMLParser();
  5657. return _htmlParser;
  5658. }
  5659. function isPreOrCode(node) {
  5660. return node.nodeName === "PRE" || node.nodeName === "CODE";
  5661. }
  5662. function Node$1(node, options) {
  5663. node.isBlock = isBlock(node);
  5664. node.isCode = node.nodeName === "CODE" || node.parentNode.isCode;
  5665. node.isBlank = isBlank(node);
  5666. node.flankingWhitespace = flankingWhitespace(node, options);
  5667. return node;
  5668. }
  5669. function isBlank(node) {
  5670. return !isVoid(node) && !isMeaningfulWhenBlank(node) && /^\s*$/i.test(node.textContent) && !hasVoid(node) && !hasMeaningfulWhenBlank(node);
  5671. }
  5672. function flankingWhitespace(node, options) {
  5673. if (node.isBlock || options.preformattedCode && node.isCode) {
  5674. return { leading: "", trailing: "" };
  5675. }
  5676. var edges = edgeWhitespace(node.textContent);
  5677. if (edges.leadingAscii && isFlankedByWhitespace("left", node, options)) {
  5678. edges.leading = edges.leadingNonAscii;
  5679. }
  5680. if (edges.trailingAscii && isFlankedByWhitespace("right", node, options)) {
  5681. edges.trailing = edges.trailingNonAscii;
  5682. }
  5683. return { leading: edges.leading, trailing: edges.trailing };
  5684. }
  5685. function edgeWhitespace(string) {
  5686. var m = string.match(/^(([ \t\r\n]*)(\s*))(?:(?=\S)[\s\S]*\S)?((\s*?)([ \t\r\n]*))$/);
  5687. return {
  5688. leading: m[1],
  5689. // whole string for whitespace-only strings
  5690. leadingAscii: m[2],
  5691. leadingNonAscii: m[3],
  5692. trailing: m[4],
  5693. // empty for whitespace-only strings
  5694. trailingNonAscii: m[5],
  5695. trailingAscii: m[6]
  5696. };
  5697. }
  5698. function isFlankedByWhitespace(side, node, options) {
  5699. var sibling2;
  5700. var regExp;
  5701. var isFlanked;
  5702. if (side === "left") {
  5703. sibling2 = node.previousSibling;
  5704. regExp = / $/;
  5705. } else {
  5706. sibling2 = node.nextSibling;
  5707. regExp = /^ /;
  5708. }
  5709. if (sibling2) {
  5710. if (sibling2.nodeType === 3) {
  5711. isFlanked = regExp.test(sibling2.nodeValue);
  5712. } else if (options.preformattedCode && sibling2.nodeName === "CODE") {
  5713. isFlanked = false;
  5714. } else if (sibling2.nodeType === 1 && !isBlock(sibling2)) {
  5715. isFlanked = regExp.test(sibling2.textContent);
  5716. }
  5717. }
  5718. return isFlanked;
  5719. }
  5720. var reduce = Array.prototype.reduce;
  5721. var escapes = [
  5722. [/\\/g, "\\\\"],
  5723. [/\*/g, "\\*"],
  5724. [/^-/g, "\\-"],
  5725. [/^\+ /g, "\\+ "],
  5726. [/^(=+)/g, "\\$1"],
  5727. [/^(#{1,6}) /g, "\\$1 "],
  5728. [/`/g, "\\`"],
  5729. [/^~~~/g, "\\~~~"],
  5730. [/\[/g, "\\["],
  5731. [/\]/g, "\\]"],
  5732. [/^>/g, "\\>"],
  5733. [/_/g, "\\_"],
  5734. [/^(\d+)\. /g, "$1\\. "]
  5735. ];
  5736. function TurndownService(options) {
  5737. if (!(this instanceof TurndownService)) return new TurndownService(options);
  5738. var defaults = {
  5739. rules,
  5740. headingStyle: "setext",
  5741. hr: "* * *",
  5742. bulletListMarker: "*",
  5743. codeBlockStyle: "indented",
  5744. fence: "```",
  5745. emDelimiter: "_",
  5746. strongDelimiter: "**",
  5747. linkStyle: "inlined",
  5748. linkReferenceStyle: "full",
  5749. br: " ",
  5750. preformattedCode: false,
  5751. blankReplacement: function(content, node) {
  5752. return node.isBlock ? "\n\n" : "";
  5753. },
  5754. keepReplacement: function(content, node) {
  5755. return node.isBlock ? "\n\n" + node.outerHTML + "\n\n" : node.outerHTML;
  5756. },
  5757. defaultReplacement: function(content, node) {
  5758. return node.isBlock ? "\n\n" + content + "\n\n" : content;
  5759. }
  5760. };
  5761. this.options = extend({}, defaults, options);
  5762. this.rules = new Rules(this.options);
  5763. }
  5764. TurndownService.prototype = {
  5765. /**
  5766. * The entry point for converting a string or DOM node to Markdown
  5767. * @public
  5768. * @param {String|HTMLElement} input The string or DOM node to convert
  5769. * @returns A Markdown representation of the input
  5770. * @type String
  5771. */
  5772. turndown: function(input) {
  5773. if (!canConvert(input)) {
  5774. throw new TypeError(
  5775. input + " is not a string, or an element/document/fragment node."
  5776. );
  5777. }
  5778. if (input === "") return "";
  5779. var output = process.call(this, new RootNode(input, this.options));
  5780. return postProcess.call(this, output);
  5781. },
  5782. /**
  5783. * Add one or more plugins
  5784. * @public
  5785. * @param {Function|Array} plugin The plugin or array of plugins to add
  5786. * @returns The Turndown instance for chaining
  5787. * @type Object
  5788. */
  5789. use: function(plugin) {
  5790. if (Array.isArray(plugin)) {
  5791. for (var i2 = 0; i2 < plugin.length; i2++) this.use(plugin[i2]);
  5792. } else if (typeof plugin === "function") {
  5793. plugin(this);
  5794. } else {
  5795. throw new TypeError("plugin must be a Function or an Array of Functions");
  5796. }
  5797. return this;
  5798. },
  5799. /**
  5800. * Adds a rule
  5801. * @public
  5802. * @param {String} key The unique key of the rule
  5803. * @param {Object} rule The rule
  5804. * @returns The Turndown instance for chaining
  5805. * @type Object
  5806. */
  5807. addRule: function(key, rule) {
  5808. this.rules.add(key, rule);
  5809. return this;
  5810. },
  5811. /**
  5812. * Keep a node (as HTML) that matches the filter
  5813. * @public
  5814. * @param {String|Array|Function} filter The unique key of the rule
  5815. * @returns The Turndown instance for chaining
  5816. * @type Object
  5817. */
  5818. keep: function(filter) {
  5819. this.rules.keep(filter);
  5820. return this;
  5821. },
  5822. /**
  5823. * Remove a node that matches the filter
  5824. * @public
  5825. * @param {String|Array|Function} filter The unique key of the rule
  5826. * @returns The Turndown instance for chaining
  5827. * @type Object
  5828. */
  5829. remove: function(filter) {
  5830. this.rules.remove(filter);
  5831. return this;
  5832. },
  5833. /**
  5834. * Escapes Markdown syntax
  5835. * @public
  5836. * @param {String} string The string to escape
  5837. * @returns A string with Markdown syntax escaped
  5838. * @type String
  5839. */
  5840. escape: function(string) {
  5841. return escapes.reduce(function(accumulator, escape) {
  5842. return accumulator.replace(escape[0], escape[1]);
  5843. }, string);
  5844. }
  5845. };
  5846. function process(parentNode) {
  5847. var self = this;
  5848. return reduce.call(parentNode.childNodes, function(output, node) {
  5849. node = new Node$1(node, self.options);
  5850. var replacement = "";
  5851. if (node.nodeType === 3) {
  5852. replacement = node.isCode ? node.nodeValue : self.escape(node.nodeValue);
  5853. } else if (node.nodeType === 1) {
  5854. replacement = replacementForNode.call(self, node);
  5855. }
  5856. return join(output, replacement);
  5857. }, "");
  5858. }
  5859. function postProcess(output) {
  5860. var self = this;
  5861. this.rules.forEach(function(rule) {
  5862. if (typeof rule.append === "function") {
  5863. output = join(output, rule.append(self.options));
  5864. }
  5865. });
  5866. return output.replace(/^[\t\r\n]+/, "").replace(/[\t\r\n\s]+$/, "");
  5867. }
  5868. function replacementForNode(node) {
  5869. var rule = this.rules.forNode(node);
  5870. var content = process.call(this, node);
  5871. var whitespace2 = node.flankingWhitespace;
  5872. if (whitespace2.leading || whitespace2.trailing) content = content.trim();
  5873. return whitespace2.leading + rule.replacement(content, node, this.options) + whitespace2.trailing;
  5874. }
  5875. function join(output, replacement) {
  5876. var s1 = trimTrailingNewlines(output);
  5877. var s2 = trimLeadingNewlines(replacement);
  5878. var nls = Math.max(output.length - s1.length, replacement.length - s2.length);
  5879. var separator = "\n\n".substring(0, nls);
  5880. return s1 + separator + s2;
  5881. }
  5882. function canConvert(input) {
  5883. return input != null && (typeof input === "string" || input.nodeType && (input.nodeType === 1 || input.nodeType === 9 || input.nodeType === 11));
  5884. }
  5885. var turndownPluginGfm_cjs = {};
  5886. var hasRequiredTurndownPluginGfm_cjs;
  5887. function requireTurndownPluginGfm_cjs() {
  5888. if (hasRequiredTurndownPluginGfm_cjs) return turndownPluginGfm_cjs;
  5889. hasRequiredTurndownPluginGfm_cjs = 1;
  5890. Object.defineProperty(turndownPluginGfm_cjs, "__esModule", { value: true });
  5891. var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/;
  5892. function highlightedCodeBlock(turndownService) {
  5893. turndownService.addRule("highlightedCodeBlock", {
  5894. filter: function(node) {
  5895. var firstChild = node.firstChild;
  5896. return node.nodeName === "DIV" && highlightRegExp.test(node.className) && firstChild && firstChild.nodeName === "PRE";
  5897. },
  5898. replacement: function(content, node, options) {
  5899. var className = node.className || "";
  5900. var language = (className.match(highlightRegExp) || [null, ""])[1];
  5901. return "\n\n" + options.fence + language + "\n" + node.firstChild.textContent + "\n" + options.fence + "\n\n";
  5902. }
  5903. });
  5904. }
  5905. function strikethrough(turndownService) {
  5906. turndownService.addRule("strikethrough", {
  5907. filter: ["del", "s", "strike"],
  5908. replacement: function(content) {
  5909. return "~~" + content + "~~";
  5910. }
  5911. });
  5912. }
  5913. var indexOf = Array.prototype.indexOf;
  5914. var every = Array.prototype.every;
  5915. var rules2 = {};
  5916. var alignMap = { left: ":---", right: "---:", center: ":---:" };
  5917. let isCodeBlock_ = null;
  5918. let options_ = null;
  5919. const tableShouldBeSkippedCache_ = /* @__PURE__ */ new WeakMap();
  5920. function getAlignment(node) {
  5921. return node ? (node.getAttribute("align") || node.style.textAlign || "").toLowerCase() : "";
  5922. }
  5923. function getBorder(alignment) {
  5924. return alignment ? alignMap[alignment] : "---";
  5925. }
  5926. function getColumnAlignment(table, columnIndex) {
  5927. var votes = {
  5928. left: 0,
  5929. right: 0,
  5930. center: 0,
  5931. "": 0
  5932. };
  5933. var align = "";
  5934. for (var i2 = 0; i2 < table.rows.length; ++i2) {
  5935. var row = table.rows[i2];
  5936. if (columnIndex < row.childNodes.length) {
  5937. var cellAlignment = getAlignment(row.childNodes[columnIndex]);
  5938. ++votes[cellAlignment];
  5939. if (votes[cellAlignment] > votes[align]) {
  5940. align = cellAlignment;
  5941. }
  5942. }
  5943. }
  5944. return align;
  5945. }
  5946. rules2.tableCell = {
  5947. filter: ["th", "td"],
  5948. replacement: function(content, node) {
  5949. if (tableShouldBeSkipped(nodeParentTable(node))) return content;
  5950. return cell(content, node);
  5951. }
  5952. };
  5953. rules2.tableRow = {
  5954. filter: "tr",
  5955. replacement: function(content, node) {
  5956. const parentTable = nodeParentTable(node);
  5957. if (tableShouldBeSkipped(parentTable)) return content;
  5958. var borderCells = "";
  5959. if (isHeadingRow(node)) {
  5960. const colCount = tableColCount(parentTable);
  5961. for (var i2 = 0; i2 < colCount; i2++) {
  5962. const childNode = i2 < node.childNodes.length ? node.childNodes[i2] : null;
  5963. var border = getBorder(getColumnAlignment(parentTable, i2));
  5964. borderCells += cell(border, childNode, i2);
  5965. }
  5966. }
  5967. return "\n" + content + (borderCells ? "\n" + borderCells : "");
  5968. }
  5969. };
  5970. rules2.table = {
  5971. filter: function(node, options) {
  5972. return node.nodeName === "TABLE";
  5973. },
  5974. replacement: function(content, node) {
  5975. if (tableShouldBeHtml(node, options_)) {
  5976. let html = node.outerHTML;
  5977. let divParent = nodeParentDiv(node);
  5978. if (divParent === null || !divParent.classList.contains("joplin-table-wrapper")) {
  5979. return `
  5980.  
  5981. <div class="joplin-table-wrapper">${html}</div>
  5982.  
  5983. `;
  5984. } else {
  5985. return html;
  5986. }
  5987. } else {
  5988. if (tableShouldBeSkipped(node)) return content;
  5989. content = content.replace(/\n+/g, "\n");
  5990. var secondLine = content.trim().split("\n");
  5991. if (secondLine.length >= 2) secondLine = secondLine[1];
  5992. var secondLineIsDivider = /\| :?---/.test(secondLine);
  5993. var columnCount = tableColCount(node);
  5994. var emptyHeader = "";
  5995. if (columnCount && !secondLineIsDivider) {
  5996. emptyHeader = "|" + " |".repeat(columnCount) + "\n|";
  5997. for (var columnIndex = 0; columnIndex < columnCount; ++columnIndex) {
  5998. emptyHeader += " " + getBorder(getColumnAlignment(node, columnIndex)) + " |";
  5999. }
  6000. }
  6001. const captionContent = node.caption ? node.caption.textContent || "" : "";
  6002. const caption = captionContent ? `${captionContent}
  6003.  
  6004. ` : "";
  6005. const tableContent = `${emptyHeader}${content}`.trimStart();
  6006. return `
  6007.  
  6008. ${caption}${tableContent}
  6009.  
  6010. `;
  6011. }
  6012. }
  6013. };
  6014. rules2.tableCaption = {
  6015. filter: ["caption"],
  6016. replacement: () => ""
  6017. };
  6018. rules2.tableColgroup = {
  6019. filter: ["colgroup", "col"],
  6020. replacement: () => ""
  6021. };
  6022. rules2.tableSection = {
  6023. filter: ["thead", "tbody", "tfoot"],
  6024. replacement: function(content) {
  6025. return content;
  6026. }
  6027. };
  6028. function isHeadingRow(tr) {
  6029. var parentNode = tr.parentNode;
  6030. return parentNode.nodeName === "THEAD" || parentNode.firstChild === tr && (parentNode.nodeName === "TABLE" || isFirstTbody(parentNode)) && every.call(tr.childNodes, function(n) {
  6031. return n.nodeName === "TH";
  6032. });
  6033. }
  6034. function isFirstTbody(element) {
  6035. var previousSibling = element.previousSibling;
  6036. return element.nodeName === "TBODY" && (!previousSibling || previousSibling.nodeName === "THEAD" && /^\s*$/i.test(previousSibling.textContent));
  6037. }
  6038. function cell(content, node = null, index = null) {
  6039. if (index === null) index = indexOf.call(node.parentNode.childNodes, node);
  6040. var prefix = " ";
  6041. if (index === 0) prefix = "| ";
  6042. let filteredContent = content.trim().replace(/\n\r/g, "<br>").replace(/\n/g, "<br>");
  6043. filteredContent = filteredContent.replace(/\|+/g, "\\|");
  6044. while (filteredContent.length < 3) filteredContent += " ";
  6045. if (node) filteredContent = handleColSpan(filteredContent, node, " ");
  6046. return prefix + filteredContent + " |";
  6047. }
  6048. function nodeContainsTable(node) {
  6049. if (!node.childNodes) return false;
  6050. for (let i2 = 0; i2 < node.childNodes.length; i2++) {
  6051. const child2 = node.childNodes[i2];
  6052. if (child2.nodeName === "TABLE") return true;
  6053. if (nodeContainsTable(child2)) return true;
  6054. }
  6055. return false;
  6056. }
  6057. const nodeContains = (node, types) => {
  6058. if (!node.childNodes) return false;
  6059. for (let i2 = 0; i2 < node.childNodes.length; i2++) {
  6060. const child2 = node.childNodes[i2];
  6061. if (types === "code" && isCodeBlock_ && isCodeBlock_(child2)) return true;
  6062. if (types.includes(child2.nodeName)) return true;
  6063. if (nodeContains(child2, types)) return true;
  6064. }
  6065. return false;
  6066. };
  6067. const tableShouldBeHtml = (tableNode, options) => {
  6068. const possibleTags = [
  6069. "UL",
  6070. "OL",
  6071. "H1",
  6072. "H2",
  6073. "H3",
  6074. "H4",
  6075. "H5",
  6076. "H6",
  6077. "HR",
  6078. "BLOCKQUOTE"
  6079. ];
  6080. if (options.preserveNestedTables) possibleTags.push("TABLE");
  6081. return nodeContains(tableNode, "code") || nodeContains(tableNode, possibleTags);
  6082. };
  6083. function tableShouldBeSkipped(tableNode) {
  6084. const cached = tableShouldBeSkippedCache_.get(tableNode);
  6085. if (cached !== void 0) return cached;
  6086. const result = tableShouldBeSkipped_(tableNode);
  6087. tableShouldBeSkippedCache_.set(tableNode, result);
  6088. return result;
  6089. }
  6090. function tableShouldBeSkipped_(tableNode) {
  6091. if (!tableNode) return true;
  6092. if (!tableNode.rows) return true;
  6093. if (tableNode.rows.length === 1 && tableNode.rows[0].childNodes.length <= 1) return true;
  6094. if (nodeContainsTable(tableNode)) return true;
  6095. return false;
  6096. }
  6097. function nodeParentDiv(node) {
  6098. let parent = node.parentNode;
  6099. while (parent.nodeName !== "DIV") {
  6100. parent = parent.parentNode;
  6101. if (!parent) return null;
  6102. }
  6103. return parent;
  6104. }
  6105. function nodeParentTable(node) {
  6106. let parent = node.parentNode;
  6107. while (parent.nodeName !== "TABLE") {
  6108. parent = parent.parentNode;
  6109. if (!parent) return null;
  6110. }
  6111. return parent;
  6112. }
  6113. function handleColSpan(content, node, emptyChar) {
  6114. const colspan = node.getAttribute("colspan") || 1;
  6115. for (let i2 = 1; i2 < colspan; i2++) {
  6116. content += " | " + emptyChar.repeat(3);
  6117. }
  6118. return content;
  6119. }
  6120. function tableColCount(node) {
  6121. let maxColCount = 0;
  6122. for (let i2 = 0; i2 < node.rows.length; i2++) {
  6123. const row = node.rows[i2];
  6124. const colCount = row.childNodes.length;
  6125. if (colCount > maxColCount) maxColCount = colCount;
  6126. }
  6127. return maxColCount;
  6128. }
  6129. function tables(turndownService) {
  6130. isCodeBlock_ = turndownService.isCodeBlock;
  6131. options_ = turndownService.options;
  6132. turndownService.keep(function(node) {
  6133. if (node.nodeName === "TABLE" && tableShouldBeHtml(node, turndownService.options)) return true;
  6134. return false;
  6135. });
  6136. for (var key in rules2) turndownService.addRule(key, rules2[key]);
  6137. }
  6138. function taskListItems(turndownService) {
  6139. turndownService.addRule("taskListItems", {
  6140. filter: function(node) {
  6141. return node.type === "checkbox" && node.parentNode.nodeName === "LI";
  6142. },
  6143. replacement: function(content, node) {
  6144. return (node.checked ? "[x]" : "[ ]") + " ";
  6145. }
  6146. });
  6147. }
  6148. function gfm(turndownService) {
  6149. turndownService.use([
  6150. highlightedCodeBlock,
  6151. strikethrough,
  6152. tables,
  6153. taskListItems
  6154. ]);
  6155. }
  6156. turndownPluginGfm_cjs.gfm = gfm;
  6157. turndownPluginGfm_cjs.highlightedCodeBlock = highlightedCodeBlock;
  6158. turndownPluginGfm_cjs.strikethrough = strikethrough;
  6159. turndownPluginGfm_cjs.tables = tables;
  6160. turndownPluginGfm_cjs.taskListItems = taskListItems;
  6161. return turndownPluginGfm_cjs;
  6162. }
  6163. var turndownPluginGfm_cjsExports = requireTurndownPluginGfm_cjs();
  6164. var M = "__monkeyWindow-" + (() => {
  6165. try {
  6166. return new URL((_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('__entry.js', document.baseURI).href)).origin;
  6167. } catch {
  6168. return location.origin;
  6169. }
  6170. })(), y = document[M] ?? window, g = y.GM, v = y.GM_xmlhttpRequest;
  6171. function k(l) {
  6172. var e2;
  6173. const t = new Headers(), a2 = l.replace(/\r?\n[\t ]+/g, " ");
  6174. for (const d of a2.split(/\r?\n/)) {
  6175. const i2 = d.split(":"), o2 = (e2 = i2.shift()) == null ? void 0 : e2.trim();
  6176. if (o2) {
  6177. const r2 = i2.join(":").trim();
  6178. try {
  6179. t.append(o2, r2);
  6180. } catch (c2) {
  6181. console.warn(`Response ${c2.message}`);
  6182. }
  6183. }
  6184. }
  6185. return t;
  6186. }
  6187. const H = async (l, t) => {
  6188. const a2 = v || g.xmlHttpRequest;
  6189. if (typeof a2 != "function")
  6190. throw new DOMException(
  6191. "GM_xmlhttpRequest or GM.xmlHttpRequest is not granted.",
  6192. "NotFoundError"
  6193. );
  6194. const e2 = new Request(l, t);
  6195. if (e2.signal.aborted)
  6196. throw new DOMException("Network request aborted.", "AbortError");
  6197. const d = await e2.blob(), i2 = Object.fromEntries(e2.headers);
  6198. return new Headers(void 0).forEach((o2, r2) => {
  6199. i2[r2] = o2;
  6200. }), new Promise((o2, r2) => {
  6201. let c2 = false;
  6202. const R = new Promise((n) => {
  6203. const { abort: h } = a2({
  6204. method: e2.method.toUpperCase(),
  6205. url: e2.url || location.href,
  6206. headers: i2,
  6207. data: d.size ? d : void 0,
  6208. redirect: e2.redirect,
  6209. binary: true,
  6210. nocache: e2.cache === "no-store",
  6211. revalidate: e2.cache === "reload",
  6212. timeout: 3e5,
  6213. responseType: a2.RESPONSE_TYPE_STREAM ?? "blob",
  6214. overrideMimeType: e2.headers.get("Content-Type") ?? void 0,
  6215. anonymous: e2.credentials === "omit",
  6216. onload: ({ response: s }) => {
  6217. if (c2) {
  6218. n(null);
  6219. return;
  6220. }
  6221. n(s);
  6222. },
  6223. async onreadystatechange({
  6224. readyState: s,
  6225. responseHeaders: p,
  6226. status: b,
  6227. statusText: q,
  6228. finalUrl: w,
  6229. response: E
  6230. }) {
  6231. if (s === XMLHttpRequest.DONE)
  6232. e2.signal.removeEventListener("abort", h);
  6233. else if (s !== XMLHttpRequest.HEADERS_RECEIVED)
  6234. return;
  6235. if (c2) {
  6236. n(null);
  6237. return;
  6238. }
  6239. const u2 = k(p), f = e2.url !== w, m = new Response(
  6240. E instanceof ReadableStream ? E : await R,
  6241. {
  6242. headers: u2,
  6243. status: b,
  6244. statusText: q
  6245. }
  6246. );
  6247. Object.defineProperties(m, {
  6248. url: {
  6249. value: w
  6250. },
  6251. type: {
  6252. value: "basic"
  6253. },
  6254. ...m.redirected !== f ? {
  6255. redirected: {
  6256. value: f
  6257. }
  6258. } : {},
  6259. // https://fetch.spec.whatwg.org/#forbidden-response-header-name
  6260. ...u2.has("set-cookie") || u2.has("set-cookie2") ? {
  6261. headers: {
  6262. value: u2
  6263. }
  6264. } : {}
  6265. }), o2(m), c2 = true;
  6266. },
  6267. onerror: ({ statusText: s, error: p }) => {
  6268. r2(
  6269. new TypeError(s || p || "Network request failed.")
  6270. ), n(null);
  6271. },
  6272. ontimeout() {
  6273. r2(new TypeError("Network request timeout.")), n(null);
  6274. },
  6275. onabort() {
  6276. r2(new DOMException("Network request aborted.", "AbortError")), n(null);
  6277. }
  6278. });
  6279. e2.signal.addEventListener("abort", h);
  6280. });
  6281. });
  6282. };
  6283. function blobToDataURL(blob) {
  6284. return new Promise((resolve, reject) => {
  6285. const reader = new FileReader();
  6286. reader.onload = () => resolve(reader.result);
  6287. reader.onerror = (error) => reject(error);
  6288. reader.readAsDataURL(blob);
  6289. });
  6290. }
  6291. async function convertSrcToDataURL(src) {
  6292. if (src.startsWith("data:")) {
  6293. return src;
  6294. }
  6295. try {
  6296. const response = await H(src);
  6297. const blob = await response.blob();
  6298. const dataURL = await blobToDataURL(blob);
  6299. return dataURL;
  6300. } catch (err) {
  6301. console.error(`Failed to fetch image: ${src}`, err);
  6302. throw err;
  6303. }
  6304. }
  6305. const imageCache = /* @__PURE__ */ new Map();
  6306. async function prefetchImages(node) {
  6307. const images = Array.from(node.querySelectorAll("img"));
  6308. const fetchPromises = images.map(async ({ src }) => {
  6309. if (imageCache.has(src)) return;
  6310. const dataURL = await convertSrcToDataURL(src);
  6311. imageCache.set(src, dataURL);
  6312. });
  6313. await Promise.all(fetchPromises);
  6314. }
  6315. function createTurndownService() {
  6316. const turndown2 = new TurndownService({
  6317. emDelimiter: "*",
  6318. bulletListMarker: "-"
  6319. });
  6320. turndown2.addRule("pre", {
  6321. filter: ["pre"],
  6322. replacement: (_content, node) => {
  6323. var _a2;
  6324. return "\n```txt\n" + ((_a2 = node.textContent) == null ? void 0 : _a2.trim()) + "\n```\n";
  6325. }
  6326. });
  6327. turndown2.addRule("superscript", {
  6328. filter: ["sup"],
  6329. replacement: (content) => "^" + content
  6330. });
  6331. turndown2.addRule("paragraph", {
  6332. filter: ["p"],
  6333. replacement: (content) => "\n\n" + content + "\n\n"
  6334. });
  6335. turndown2.addRule("convert-img-src-to-base64", {
  6336. filter: ["img"],
  6337. replacement: (_content, node) => {
  6338. const { src, alt } = node;
  6339. const dataURL = imageCache.get(src);
  6340. if (dataURL) {
  6341. return `![${alt}](${dataURL})`;
  6342. }
  6343. return `![${alt}](${src})`;
  6344. }
  6345. });
  6346. turndown2.use(turndownPluginGfm_cjsExports.tables);
  6347. return turndown2;
  6348. }
  6349. async function htmlToMd(node, {
  6350. turndownService = createTurndownService(),
  6351. convertImage = true
  6352. } = {}) {
  6353. if (convertImage) await prefetchImages(node);
  6354. const md = turndownService.turndown(node);
  6355. if (convertImage) imageCache.clear();
  6356. return md;
  6357. }
  6358. const getDescription = async (convertImage = true) => {
  6359. const el = await findElement("div[data-track-load='description_content']");
  6360. return htmlToMd(el, { convertImage });
  6361. };
  6362. function Copy_description($$anchor, $$props) {
  6363. push($$props, false);
  6364. async function copyDescription() {
  6365. const desc = await getDescription(false);
  6366. copy(desc);
  6367. }
  6368. init();
  6369. Button($$anchor, {
  6370. variant: "green",
  6371. onclick: copyDescription,
  6372. children: ($$anchor2, $$slotProps) => {
  6373. var text$1 = text();
  6374. template_effect(() => set_text(text$1, globalState.site === "cn" ? "复制描述" : "Copy Description"));
  6375. append($$anchor2, text$1);
  6376. },
  6377. $$slots: { default: true }
  6378. });
  6379. pop();
  6380. }
  6381. function downloadFile(blob, filename, extension) {
  6382. const url2 = URL.createObjectURL(blob);
  6383. const a2 = document.createElement("a");
  6384. a2.href = url2;
  6385. a2.download = filename + "." + extension;
  6386. document.body.appendChild(a2);
  6387. a2.click();
  6388. document.body.removeChild(a2);
  6389. URL.revokeObjectURL(url2);
  6390. }
  6391. function createNotebook({
  6392. title,
  6393. description,
  6394. code,
  6395. language = "python",
  6396. url: url2
  6397. }) {
  6398. const notebook = {
  6399. metadata: {
  6400. language_info: {
  6401. name: language
  6402. }
  6403. },
  6404. nbformat: 5,
  6405. nbformat_minor: 10,
  6406. cells: []
  6407. };
  6408. const regex = /^(https:\/\/(leetcode\.com|leetcode\.cn)\/problems\/[a-zA-Z0-9_-]+)/;
  6409. const match = url2.match(regex);
  6410. const titleCell = createMarkdownCell(
  6411. `# [${title}](${match ? match[0] : url2})`
  6412. );
  6413. const descriptionPrefix = globalState.site === "cn" ? "题目描述" : "Description";
  6414. const descriptionCell = createMarkdownCell(
  6415. `## ${descriptionPrefix}
  6416.  
  6417. ` + description
  6418. );
  6419. const partitionCell = createMarkdownCell("---\n\n");
  6420. const solutionPrefix = globalState.site === "cn" ? "解答" : "Solution";
  6421. const solutionCell = createMarkdownCell(`## ${solutionPrefix}`);
  6422. const codeCell = createCodeCell(code);
  6423. notebook.cells.push(
  6424. titleCell,
  6425. descriptionCell,
  6426. partitionCell,
  6427. solutionCell,
  6428. codeCell
  6429. );
  6430. return notebook;
  6431. }
  6432. function createMarkdownCell(content) {
  6433. return {
  6434. cell_type: "markdown",
  6435. metadata: {},
  6436. source: content
  6437. };
  6438. }
  6439. function createCodeCell(content) {
  6440. return {
  6441. cell_type: "code",
  6442. metadata: {},
  6443. source: content,
  6444. execution_count: null,
  6445. outputs: []
  6446. };
  6447. }
  6448. function downloadNotebook(notebook, filename) {
  6449. const blob = new Blob([JSON.stringify(notebook)], {
  6450. type: "application/x-ipynb+json"
  6451. });
  6452. downloadFile(blob, filename, "ipynb");
  6453. }
  6454. function Download_as_jupyter($$anchor, $$props) {
  6455. push($$props, false);
  6456. async function saveAsJupyter() {
  6457. var _a2, _b, _c, _d;
  6458. const title = await getTitle();
  6459. const notebook = createNotebook({
  6460. title,
  6461. description: await getDescription(),
  6462. code: ((_b = (_a2 = problemState.editor) == null ? void 0 : _a2.getModel()) == null ? void 0 : _b.getValue()) ?? "",
  6463. language: ((_d = (_c = problemState.editor) == null ? void 0 : _c.getModel()) == null ? void 0 : _d.getLanguageId()) ?? "python",
  6464. url: window.location.href
  6465. });
  6466. downloadNotebook(notebook, title);
  6467. }
  6468. init();
  6469. Button($$anchor, {
  6470. variant: "orange",
  6471. onclick: () => {
  6472. prefixToast.promise(saveAsJupyter(), {
  6473. loading: "Scraping problem description and code...",
  6474. success: "Start downloading jupyter notebook...",
  6475. error: "Something went wrong while scraping. See browser console for more detail."
  6476. });
  6477. },
  6478. children: ($$anchor2, $$slotProps) => {
  6479. var text$1 = text();
  6480. template_effect(() => set_text(text$1, globalState.site === "cn" ? "保存为 Jupyter Notebook (.ipynb)" : "Save as Jupyter Notebook (.ipynb)"));
  6481. append($$anchor2, text$1);
  6482. },
  6483. $$slots: { default: true }
  6484. });
  6485. pop();
  6486. }
  6487. var root_1$2 = /* @__PURE__ */ template(`<!> <!> <!>`, 1);
  6488. function DescriptionButttons($$anchor) {
  6489. ButtonGroup($$anchor, {
  6490. children: ($$anchor2, $$slotProps) => {
  6491. var fragment_1 = root_1$2();
  6492. var node = first_child(fragment_1);
  6493. Copy_title(node, {});
  6494. var node_1 = sibling(node, 2);
  6495. Copy_description(node_1, {});
  6496. var node_2 = sibling(node_1, 2);
  6497. Download_as_jupyter(node_2, {});
  6498. append($$anchor2, fragment_1);
  6499. },
  6500. $$slots: { default: true }
  6501. });
  6502. }
  6503. async function initDescriptionTab() {
  6504. var _a2;
  6505. const descriptionTab = await findElement(
  6506. ".flexlayout__tab:has([data-track-load='description_content'])",
  6507. {
  6508. timeout: 0,
  6509. additionalRule: (el) => el.style.display !== "none"
  6510. }
  6511. );
  6512. const titleContainer = await findElement("div:has(> .text-title-large)", {
  6513. parent: descriptionTab
  6514. });
  6515. const buttonsContainer = document.createElement("div");
  6516. buttonsContainer.setAttribute(
  6517. "id",
  6518. a(CONFIG.APP_NAME) + "-description"
  6519. );
  6520. buttonsContainer.style.cssText = "display: contents;";
  6521. (_a2 = titleContainer.parentElement) == null ? void 0 : _a2.before(buttonsContainer);
  6522. mount(DescriptionButttons, {
  6523. target: buttonsContainer
  6524. });
  6525. }
  6526. function Find_editorial_screenshot($$anchor, $$props) {
  6527. push($$props, false);
  6528. const editorialsMarkdown = _GM_getResourceText("editorials");
  6529. function extractScreenshotLink(problemTitle) {
  6530. const cleanTitle = problemTitle.trim();
  6531. const headingPattern = new RegExp(`####\\s+\\[${cleanTitle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\]\\((.*?)\\)`, "i");
  6532. const match = editorialsMarkdown.match(headingPattern);
  6533. return match ? match[1] : null;
  6534. }
  6535. async function goToEditorialScreenshot() {
  6536. const title = await getTitle();
  6537. const link2 = extractScreenshotLink(title);
  6538. if (link2) {
  6539. window.open(link2, "_blank");
  6540. } else {
  6541. toast.warning(`Editorial screenshot not found for problem: ${title}`);
  6542. }
  6543. }
  6544. init();
  6545. Button($$anchor, {
  6546. onclick: goToEditorialScreenshot,
  6547. children: ($$anchor2, $$slotProps) => {
  6548. var text$1 = text("Find Screenshot");
  6549. append($$anchor2, text$1);
  6550. },
  6551. $$slots: { default: true }
  6552. });
  6553. pop();
  6554. }
  6555. const turndown = createTurndownService();
  6556. turndown.addRule("remove-heading-link", {
  6557. filter: (node) => node.nodeName === "A" && node.getAttribute("aria-hidden") === "true",
  6558. replacement: () => ""
  6559. });
  6560. turndown.addRule("save-math-as-is", {
  6561. filter: (node) => ["SPAN", "DIV"].includes(node.nodeName) && node.matches(".math, .maths, .math-tex"),
  6562. replacement: (_content, node) => node.outerHTML
  6563. });
  6564. function waitForIframeToLoad(iframe) {
  6565. return new Promise((resolve) => {
  6566. var _a2, _b, _c, _d;
  6567. if (iframe.src !== "about:blank") {
  6568. const isSameOrigin = new URL(iframe.src).hostname === window.location.hostname;
  6569. 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") {
  6570. resolve(void 0);
  6571. return;
  6572. }
  6573. }
  6574. console.log("wait for iframe to load...");
  6575. (_d = iframe.contentWindow) == null ? void 0 : _d.addEventListener("load", resolve, {
  6576. once: true
  6577. });
  6578. });
  6579. }
  6580. const playgroundCache = /* @__PURE__ */ new Map();
  6581. async function prefetchPlayground(editorialEl) {
  6582. const iframes = Array.from(editorialEl.querySelectorAll("iframe"));
  6583. const promises = iframes.map(async (iframe) => {
  6584. var _a2, _b;
  6585. await waitForIframeToLoad(iframe);
  6586. const { src, contentDocument } = iframe;
  6587. if (!src.includes("playground")) return;
  6588. console.log((_b = (_a2 = iframe.contentWindow) == null ? void 0 : _a2.location) == null ? void 0 : _b.href);
  6589. const langTab = await findElement("div.lang-btn-set", {
  6590. parent: contentDocument,
  6591. timeout: 1e3
  6592. });
  6593. const textarea = contentDocument == null ? void 0 : contentDocument.querySelector(
  6594. "textarea[name='lc-codemirror']"
  6595. );
  6596. let result = `<MixedCodeBlock>
  6597.  
  6598. `;
  6599. Array.from(
  6600. langTab.children
  6601. ).forEach((button) => {
  6602. var _a3;
  6603. let lang = (_a3 = button.textContent) == null ? void 0 : _a3.toLowerCase();
  6604. if (lang === "python3") lang = "python";
  6605. button.click();
  6606. const code = textarea == null ? void 0 : textarea.textContent;
  6607. result += `\`\`\`${lang}
  6608. ${code}
  6609. \`\`\`
  6610.  
  6611. `;
  6612. });
  6613. result += `</MixedCodeBlock>`;
  6614. playgroundCache.set(src, result);
  6615. });
  6616. await Promise.all(promises);
  6617. }
  6618. turndown.addRule("save-code-playground", {
  6619. filter: ["iframe"],
  6620. replacement: (_content, node) => {
  6621. const { src } = node;
  6622. if (!src.includes("playground")) return "";
  6623. return `[LeetCode Playground](${src})
  6624.  
  6625. ` + (playgroundCache.get(src) ?? "");
  6626. }
  6627. });
  6628. const slideCache = /* @__PURE__ */ new Map();
  6629. async function preFetchSlides(editorialEl) {
  6630. const slideImages = editorialEl.querySelectorAll("img[alt='Current']");
  6631. const promises = Array.from(slideImages).map(async (image) => {
  6632. var _a2, _b, _c;
  6633. const slideContainer = (_a2 = image.parentElement) == null ? void 0 : _a2.parentElement;
  6634. if (!slideContainer) {
  6635. throw new Error("Slide container not found");
  6636. }
  6637. const slideNumIndicator = slideContainer.children[2].children[1];
  6638. slideNumIndicator.setAttribute("data-skip-me-turndown", "true");
  6639. const slidesCountStr = (_c = (_b = slideNumIndicator.textContent) == null ? void 0 : _b.match(/\d+$/)) == null ? void 0 : _c[0];
  6640. if (!slidesCountStr) {
  6641. throw new Error("Slide count not found");
  6642. }
  6643. const nextSlideButton = slideContainer.querySelector("svg:nth-child(3)");
  6644. if (!nextSlideButton) {
  6645. throw new Error("Next slide button not found");
  6646. }
  6647. const firstSlideSrc = image.src;
  6648. slideCache.set(firstSlideSrc, []);
  6649. for (let i2 = 0; i2 < Number(slidesCountStr); i2++) {
  6650. simulateMouseClickReact(nextSlideButton);
  6651. const dataURL = await convertSrcToDataURL(image.src);
  6652. slideCache.get(firstSlideSrc).push(dataURL);
  6653. }
  6654. });
  6655. await Promise.all(promises);
  6656. }
  6657. turndown.addRule("save-slides", {
  6658. filter: (node) => node.tagName === "IMG" && node.alt === "Current",
  6659. replacement: (_content, node) => {
  6660. const { src } = node;
  6661. const dataURLs = slideCache.get(src);
  6662. if (!dataURLs) return "";
  6663. let res = `<Slides>
  6664.  
  6665. `;
  6666. dataURLs.forEach((dataURL, index) => {
  6667. res += `![Slide ${index + 1}](${dataURL})
  6668. `;
  6669. });
  6670. res += `
  6671. </Slides>`;
  6672. return res;
  6673. }
  6674. });
  6675. turndown.remove(
  6676. (node) => node.getAttribute("data-skip-me-turndown") === "true"
  6677. );
  6678. async function scrapeEditorial(editorialEl) {
  6679. await prefetchPlayground(editorialEl);
  6680. await preFetchSlides(editorialEl);
  6681. const editorial = await htmlToMd(editorialEl, {
  6682. turndownService: turndown
  6683. });
  6684. playgroundCache.clear();
  6685. slideCache.clear();
  6686. return editorial;
  6687. }
  6688. async function downloadEditorial(editorialFinder, titleFinder) {
  6689. prefixToast.promise(
  6690. async () => {
  6691. const editorialEl = await editorialFinder();
  6692. const editorial = await scrapeEditorial(editorialEl);
  6693. const title = await titleFinder();
  6694. const blob = new Blob([`# ${title}
  6695.  
  6696. `, editorial], {
  6697. type: "text/markdown; charset=UTF-8"
  6698. });
  6699. downloadFile(blob, title, "md");
  6700. },
  6701. {
  6702. loading: "Scraping editorial...",
  6703. success: "Editorial scraped. Downloading...",
  6704. error: "Something went wrong while scraping. See browser console for more detail."
  6705. }
  6706. );
  6707. }
  6708. function Save_editorial($$anchor, $$props) {
  6709. push($$props, false);
  6710. async function findEditorial() {
  6711. const editorialEl = await findElement(".flexlayout__tab:has(#editorial-quick-navigation) div.WRmCx", { timeout: 2e3 });
  6712. return editorialEl;
  6713. }
  6714. init();
  6715. Button($$anchor, {
  6716. onclick: () => downloadEditorial(findEditorial, getTitle),
  6717. variant: "orange",
  6718. children: ($$anchor2, $$slotProps) => {
  6719. var text$1 = text("Save Editorial as Markdown");
  6720. append($$anchor2, text$1);
  6721. },
  6722. $$slots: { default: true }
  6723. });
  6724. pop();
  6725. }
  6726. function Read_saved_editorial($$anchor, $$props) {
  6727. push($$props, false);
  6728. init();
  6729. Button($$anchor, {
  6730. get href() {
  6731. return CONFIG.EDITORIAL_READER_URL;
  6732. },
  6733. variant: "green",
  6734. children: ($$anchor2, $$slotProps) => {
  6735. var text$1 = text("Read Saved Editorial");
  6736. append($$anchor2, text$1);
  6737. },
  6738. $$slots: { default: true }
  6739. });
  6740. pop();
  6741. }
  6742. var root_1$1 = /* @__PURE__ */ template(`<!> <!> <!>`, 1);
  6743. function EditorialButtons($$anchor) {
  6744. ButtonGroup($$anchor, {
  6745. style: "z-index: 10; position:relative; padding: 0.5rem",
  6746. children: ($$anchor2, $$slotProps) => {
  6747. var fragment_1 = root_1$1();
  6748. var node = first_child(fragment_1);
  6749. Find_editorial_screenshot(node, {});
  6750. var node_1 = sibling(node, 2);
  6751. Save_editorial(node_1, {});
  6752. var node_2 = sibling(node_1, 2);
  6753. Read_saved_editorial(node_2, {});
  6754. append($$anchor2, fragment_1);
  6755. },
  6756. $$slots: { default: true }
  6757. });
  6758. }
  6759. async function initEditorialTab() {
  6760. const editorialTab = await findElement(
  6761. ".flexlayout__tab:has(div.bg-blocker, #editorial-quick-navigation)",
  6762. {
  6763. timeout: 0,
  6764. additionalRule: (el) => el.style.display !== "none"
  6765. }
  6766. );
  6767. const buttonsContainer = document.createElement("div");
  6768. buttonsContainer.style.cssText = "display: contents;";
  6769. buttonsContainer.setAttribute(
  6770. "id",
  6771. a(CONFIG.APP_NAME) + "-editorial"
  6772. );
  6773. editorialTab.prepend(buttonsContainer);
  6774. mount(EditorialButtons, {
  6775. target: buttonsContainer
  6776. });
  6777. }
  6778. async function main$1() {
  6779. const initPromises = [];
  6780. initPromises.push(problemState.patchMonacoEditor());
  6781. initPromises.push(initDescriptionTab());
  6782. if (globalState.site === "global") {
  6783. initPromises.push(initEditorialTab());
  6784. }
  6785. await Promise.all(initPromises);
  6786. }
  6787. function getElementIndex(element) {
  6788. if (!element.parentNode) throw new Error("Element has no parent node");
  6789. return Array.from(element.parentNode.children).indexOf(element);
  6790. }
  6791. function Save_explore_article($$anchor, $$props) {
  6792. push($$props, false);
  6793. async function findExploreEditorial() {
  6794. return await findElement("div.block-markdown");
  6795. }
  6796. async function getExploreTitle() {
  6797. var _a2, _b;
  6798. const tocContainer = await findElement("div.list-group:not(.item-list-group)");
  6799. const titleContainer = tocContainer.querySelector(".list-group-item .selected");
  6800. if (!titleContainer) {
  6801. throw new Error("Title container not found");
  6802. }
  6803. const title = ((_b = (_a2 = titleContainer.querySelector(".title")) == null ? void 0 : _a2.textContent) == null ? void 0 : _b.trim()) ?? "";
  6804. const articleNumber = getElementIndex(titleContainer) + 1;
  6805. const chapterEl = titleContainer.closest("div.chapter-item");
  6806. if (!chapterEl) {
  6807. throw new Error("Chapter not found");
  6808. }
  6809. const chapterNumber = getElementIndex(chapterEl);
  6810. return `${chapterNumber}.${articleNumber} ${title}`;
  6811. }
  6812. init();
  6813. Button($$anchor, {
  6814. onclick: () => downloadEditorial(findExploreEditorial, getExploreTitle),
  6815. children: ($$anchor2, $$slotProps) => {
  6816. var text$1 = text("Save Article as Markdown");
  6817. append($$anchor2, text$1);
  6818. },
  6819. $$slots: { default: true }
  6820. });
  6821. pop();
  6822. }
  6823. var root_1 = /* @__PURE__ */ template(`<!> <!>`, 1);
  6824. function ExploreButtons($$anchor) {
  6825. ButtonGroup($$anchor, {
  6826. children: ($$anchor2, $$slotProps) => {
  6827. var fragment_1 = root_1();
  6828. var node = first_child(fragment_1);
  6829. Save_explore_article(node, {});
  6830. var node_1 = sibling(node, 2);
  6831. Read_saved_editorial(node_1, {});
  6832. append($$anchor2, fragment_1);
  6833. },
  6834. $$slots: { default: true }
  6835. });
  6836. }
  6837. async function main() {
  6838. const toolbar = await findElement("div.left-side", { timeout: 0 });
  6839. const container = document.createElement("div");
  6840. container.style.cssText = "display: contents;";
  6841. toolbar.append(container);
  6842. mount(ExploreButtons, {
  6843. target: container
  6844. });
  6845. }
  6846. mount(Toaster, {
  6847. target: document.body,
  6848. props: { richColors: true, position: "top-center" }
  6849. });
  6850. const url = window.location.href;
  6851. const problemPageRegex = /https?:\/\/leetcode\.com\/problems\/.*|https?:\/\/leetcode\.cn\/problems\/.*/;
  6852. const explorePageRegex = /https?:\/\/leetcode\.com\/explore\/learn\/card\/.*/;
  6853. if (problemPageRegex.test(url)) {
  6854. main$1();
  6855. } else if (explorePageRegex.test(url)) {
  6856. main();
  6857. }
  6858.  
  6859. })();