LeetCode Toolkit

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

ของเมื่อวันที่ 25-04-2025 ดู เวอร์ชันล่าสุด

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