您需要先安装一个扩展,例如 篡改猴、Greasemonkey 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 Userscripts ,之后才能安装此脚本。
您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。
您需要先安装用户脚本管理器扩展后才能安装此脚本。
复制题目为 Markdown | 下载为 Jupyter Notebook | 保存时自动格式化 | 免费自动补全 | 显示题目评分
- // ==UserScript==
- // @name LeetCode Toolkit
- // @name:zh-CN LeetCode工具箱
- // @namespace https://github.com/eclipher/leetcode-toolkit
- // @version 2.7.0
- // @author eclipher
- // @description Find & Save Editorial, Copy problem as Markdown or Download as Jupyter Notebook, Format on Save, Unlock IntelliSense, Display Problem Ratings and more.
- // @description:zh-CN 复制题目为 Markdown | 下载为 Jupyter Notebook | 保存时自动格式化 | 免费自动补全 | 显示题目评分
- // @license MIT
- // @icon https://www.google.com/s2/favicons?sz=64&domain=leetcode.com
- // @homepage https://github.com/eclipher/Userscripts/tree/main/userscripts/leetcode-toolkit
- // @include /https?:\/\/leetcode\.com\/problems\/.*/
- // @include /https?:\/\/leetcode\.cn\/problems\/.*/
- // @include /https?:\/\/leetcode\.com\/explore\/.*\/card\/.*/
- // @exclude *://leetcode.com/problems/*/post-solution/*
- // @exclude *://leetcode.cn/problems/*/post-solution/*
- // @require https://cdn.jsdelivr.net/npm/compressorjs@1.2.1
- // @require https://cdn.jsdelivr.net/npm/turndown@7.2.0/lib/turndown.browser.umd.js
- // @resource editorials https://raw.githubusercontent.com/akhilkammila/leetcode-screenshotter/refs/heads/main/ReadMe.md
- // @resource ratings https://raw.githubusercontent.com/zerotrac/leetcode_problem_rating/refs/heads/main/ratings.txt
- // @connect assets.leetcode.com
- // @connect *
- // @grant GM_addStyle
- // @grant GM_getResourceText
- // @grant GM_xmlhttpRequest
- // @grant unsafeWindow
- // @grant window.onurlchange
- // ==/UserScript==
- (t=>{if(typeof GM_addStyle=="function"){GM_addStyle(t);return}const e=document.createElement("style");e.textContent=t,document.head.append(e)})(" .toast-container{inset:unset;border:none;background-color:transparent;overflow:clip;overflow-clip-margin:12px;display:flex;width:100%;max-width:360px;interpolate-size:allow-keywords;transition:.5s cubic-bezier(.215,.61,.355,1);transition-property:transform,translate;--space-to-screen: 20px}.toast-container.top{transform:translateY(var(--space-to-screen));flex-direction:column;--toast-initial-transform: translateY(-100%)}.toast-container.bottom{transform:translateY(calc(100vh - 100%));flex-direction:column-reverse;--toast-initial-transform: translateY(100%)}.toast-container.left{translate:calc(0% + var(--space-to-screen))}.toast-container.center{translate:calc(50vw - 50%)}.toast-container.right{translate:calc(100vw - 100% - var(--space-to-screen))}.toast{opacity:0;transition:all .5s cubic-bezier(.215,.61,.355,1);transform:var(--toast-initial-transform);height:0;overflow:hidden;margin-bottom:0;filter:blur(10px)}.toast.visible{opacity:1;transform:translateY(0);height:auto;filter:none;margin-bottom:12px}.toast[data-styled=true]{display:flex;align-items:center;gap:12px;background-color:#fff;border-radius:8px;box-shadow:0 4px 12px #00000026;border-left:4px solid var(--accent-color)}.toast[data-styled=true].visible{padding:16px}.toast[data-styled=true] .toast-icon{font-size:1.75rem;color:var(--accent-color)}.toast[data-styled=true] .toast-title{color:var(--accent-color);font-weight:600;font-size:1.125rem}.toast[data-styled=true] .toast-message{color:#333}.toast[data-styled=true] .toast-close{background:none;border:none;color:#999;cursor:pointer;font-size:1.25rem;padding:0;line-height:1}.toast-content{flex-grow:1}.toast.success{--accent-color: #4caf50}.toast.error{--accent-color: #f44336}.toast.info{--accent-color: #2196f3}.toast.warning{--accent-color: #ff9800}.toast.loading{--accent-color: #000000}.toast.loading>.toast-icon{animation:spin 1s linear infinite}@keyframes spin{to{transform:rotate(360deg)}}div.svelte-4mbyk0{display:inline-flex;flex-wrap:wrap;gap:.4rem}button.svelte-ll0ynk,a.svelte-ll0ynk{color:#fff;background-color:var(--bg, #6c5ce7);box-shadow:0 3px 0 0 var(--shadow, #a29bfe);padding:5px 20px;font-size:.8rem;font-weight:500;border-radius:5px;transition:all ease .1s;display:inline-flex;align-items:center;gap:.25rem;-webkit-user-select:none;user-select:none}button.svelte-ll0ynk:active,a.svelte-ll0ynk:active{transform:translateY(3px);box-shadow:0 0 0 0 var(--shadow, #a29bfe)}button.svelte-ll0ynk:disabled,a.svelte-ll0ynk:disabled{pointer-events:none;opacity:50%} ");
- (function (TurndownService, Compressor) {
- 'use strict';
- var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
- var __defProp = Object.defineProperty;
- var __typeError = (msg) => {
- throw TypeError(msg);
- };
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
- var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
- var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
- var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
- var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value);
- var _site, _a, _cells, _metadata, _nbformat, _nbformat_minor;
- class GlobalState {
- constructor() {
- __privateAdd(this, _site);
- }
- get site() {
- if (!__privateGet(this, _site)) {
- const hostname = window.location.hostname;
- __privateSet(this, _site, hostname === "leetcode.cn" ? "cn" : "global");
- }
- return __privateGet(this, _site);
- }
- }
- _site = new WeakMap();
- const globalState = new GlobalState();
- var _GM_getResourceText = /* @__PURE__ */ (() => typeof GM_getResourceText != "undefined" ? GM_getResourceText : void 0)();
- var _unsafeWindow = /* @__PURE__ */ (() => typeof unsafeWindow != "undefined" ? unsafeWindow : void 0)();
- var _monkeyWindow = /* @__PURE__ */ (() => window)();
- class TimeoutError extends Error {
- constructor(item, timeout) {
- super();
- __publicField(this, "name", this.constructor.name);
- this.message = `"${item}" not found within timeout (${timeout}ms)`;
- }
- }
- function find(finderFn, {
- subject = document,
- observerOption = {
- childList: true,
- subtree: true
- },
- timeout = 5e3,
- itemName = "Item"
- }) {
- return new Promise((resolve, reject) => {
- const item = finderFn();
- if (item) return resolve(item);
- let timeoutId;
- const observer = new MutationObserver(() => {
- const item2 = finderFn();
- if (item2) {
- observer.disconnect();
- clearTimeout(timeoutId);
- return resolve(item2);
- }
- });
- observer.observe(subject, observerOption);
- if (timeout > 0) {
- timeoutId = setTimeout(() => {
- observer.disconnect();
- const error = new TimeoutError(itemName, timeout);
- console.error(error);
- return reject(error);
- }, timeout);
- }
- });
- }
- async function findElement(selector, {
- parent = document,
- timeout = 500,
- additionalRule
- } = {}) {
- const element = await find(
- () => {
- const el = parent.querySelector(selector);
- if (additionalRule && el) {
- return additionalRule(el) ? el : null;
- } else {
- return el;
- }
- },
- {
- subject: parent,
- timeout,
- itemName: `Element ${selector}`
- }
- );
- return element;
- }
- const overrideOptions = {
- selectionHighlight: true,
- parameterHints: { enabled: true },
- hover: { enabled: true },
- quickSuggestions: true,
- suggestOnTriggerCharacters: true,
- "bracketPairColorization.enabled": true
- };
- function addIntellisense(editor) {
- const originalUpdateOptions = editor.updateOptions.bind(editor);
- editor.updateOptions = (options) => {
- originalUpdateOptions({
- ...options,
- ...overrideOptions
- });
- };
- }
- async function findMonacoEditor() {
- function getEditor() {
- var _a2;
- return ((_a2 = _unsafeWindow.monaco) == null ? void 0 : _a2.editor.getEditors()[0]) ?? null;
- }
- const editor = find(getEditor, {
- subject: document.head,
- observerOption: { childList: true },
- itemName: "Monaco Editor"
- });
- return editor;
- }
- var C = Object.defineProperty;
- var x = (s) => {
- throw TypeError(s);
- };
- var B = (s, e2, t) => e2 in s ? C(s, e2, { enumerable: true, configurable: true, writable: true, value: t }) : s[e2] = t;
- var w = (s, e2, t) => B(s, typeof e2 != "symbol" ? e2 + "" : e2, t), m = (s, e2, t) => e2.has(s) || x("Cannot " + t);
- var l = (s, e2, t) => (m(s, e2, "read from private field"), t ? t.call(s) : e2.get(s)), p = (s, e2, t) => e2.has(s) ? x("Cannot add the same private member more than once") : e2 instanceof WeakSet ? e2.add(s) : e2.set(s, t), y$1 = (s, e2, t, i2) => (m(s, e2, "write to private field"), e2.set(s, t), t), n = (s, e2, t) => (m(s, e2, "access private method"), t);
- const M$1 = {
- success: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-check-icon lucide-circle-check"><circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/></svg>',
- error: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-x-icon lucide-circle-x"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>',
- info: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-info-icon lucide-info"><circle cx="12" cy="12" r="10"/><path d="M12 16v-4"/><path d="M12 8h.01"/></svg>',
- warning: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-circle-alert-icon lucide-circle-alert"><circle cx="12" cy="12" r="10"/><line x1="12" x2="12" y1="8" y2="12"/><line x1="12" x2="12.01" y1="16" y2="16"/></svg>',
- loading: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-loader-circle-icon lucide-loader-circle"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',
- close: '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-x-icon lucide-x"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>'
- };
- function f(s, e2) {
- return typeof s == "function" ? s(e2) : s;
- }
- var r$1, o$2, T, $, v$1, b, k$1, d;
- class L {
- constructor(e2) {
- p(this, o$2);
- w(this, "defaultOptions", {
- durationMs: 3e3,
- dismissible: true,
- position: "top-right"
- });
- p(this, r$1);
- w(this, "toastTimeoutMap", /* @__PURE__ */ new Map());
- w(this, "count", 0);
- this.defaultOptions = { ...this.defaultOptions, ...e2 }, y$1(this, r$1, n(this, o$2, $).call(this)), this.changePosition(this.defaultOptions.position);
- }
- changePosition(e2) {
- l(this, r$1).className = `toast-container ${e2.replace("-", " ")}`;
- }
- isEmpty() {
- return l(this, r$1).children.length === 0;
- }
- dismissAll() {
- this.toastTimeoutMap.forEach((e2, t) => this.dismiss(t)), this.toastTimeoutMap.clear(), l(this, r$1).innerHTML = "";
- }
- // Function to hide and remove a toast
- dismiss(e2) {
- const t = n(this, o$2, v$1).call(this, e2);
- if (!t) {
- console.error("No toast found to dismiss");
- return;
- }
- const i2 = this.toastTimeoutMap.get(e2);
- i2 && (clearTimeout(i2), this.toastTimeoutMap.delete(e2)), t.classList.remove("visible"), t.addEventListener("transitionend", () => t.remove(), {
- once: true
- });
- }
- // public-facing method with `message` as first argument
- toast(e2, t = {}) {
- return n(this, o$2, k$1).call(this, { ...t, message: e2 });
- }
- success(e2, t) {
- return n(this, o$2, d).call(this, "success", { ...t, message: e2 });
- }
- error(e2, t) {
- return n(this, o$2, d).call(this, "error", { ...t, message: e2 });
- }
- info(e2, t) {
- return n(this, o$2, d).call(this, "info", { ...t, message: e2 });
- }
- warning(e2, t) {
- return n(this, o$2, d).call(this, "warning", { ...t, message: e2 });
- }
- /** Render a toast of "loading" type. By default, this kind of toast will stay on screen forever and cannot be dismissed by user. You can either:
- * - Programmatically remove it via `toaster.remove()`.
- * - Or explicitly pass `dismissible` and `duration` to override the default option. */
- loading(e2, t) {
- return n(this, o$2, d).call(this, "loading", {
- durationMs: 1 / 0,
- dismissible: false,
- ...t,
- message: e2
- });
- }
- /**
- * A convenience method to handle promises with toast notifications.
- * @param promise - The promise to handle, or a function that returns a promise.
- * @param handlers - An object containing loading, success, and error messages, as well as an optional finally callback.
- * @param options - Additional options for the toast.
- * @returns The ID of the toast.
- */
- async promise(e2, t, i2 = {}) {
- var u2;
- const c2 = this.loading(t.loading, {
- durationMs: 1 / 0,
- // Keep the loading toast on screen indefinitely until resolved (in case user specifies `durationMs`)
- ...i2
- }), h = f(e2);
- try {
- const a2 = await h, g2 = f(t.success, a2);
- this.success(g2, { id: c2, ...i2 });
- } catch (a2) {
- const g2 = f(t.error, a2);
- this.error(g2, { id: c2, ...i2 });
- } finally {
- (u2 = t.finally) == null || u2.call(t);
- }
- return c2;
- }
- }
- r$1 = /* @__PURE__ */ new WeakMap(), o$2 = /* @__PURE__ */ new WeakSet(), T = function() {
- return this.count++, `toast-${this.count};`;
- }, $ = function() {
- const e2 = document.getElementById("toast-rack");
- if (e2)
- return console.warn(
- "Toaster container already exists. Using the existing one."
- ), e2;
- const t = document.createElement("div");
- return t.id = "toast-rack", t.popover = "manual", document.body.append(t), t.showPopover(), t;
- }, v$1 = function(e2) {
- return l(this, r$1).children.namedItem(e2);
- }, /**
- * Get or create a toast element by id.
- * If no id is given, or the toast with the given id does not exist, it will create a new one.
- * @param id - The id of the toast to get or create.
- * @returns The toast element with a defined id.
- */
- b = function(e2) {
- if (e2) {
- const i2 = n(this, o$2, v$1).call(this, e2);
- if (i2)
- return delete i2.dataset.isNew, i2;
- console.warn(`Toast with id ${e2} not found, creating a new one.`);
- }
- const t = document.createElement("article");
- return t.id = n(this, o$2, T).call(this), t.dataset.isNew = "true", t;
- }, // The main function to create and show a toast
- k$1 = function(e2) {
- var c2, h, u2, a2;
- const t = {
- ...this.defaultOptions,
- ...e2,
- message: e2.message || ""
- }, i2 = n(this, o$2, b).call(this, t.id);
- return i2.innerHTML = `
- ${t.type ? `<div class="toast-icon">${M$1[t.type]}</div>` : ""}
- <div class="toast-content">
- ${t.title ? `<p class="toast-title ${((c2 = t.classes) == null ? void 0 : c2.title) || ""}">${t.title}</p>` : ""}
- <p class="toast-message ${((h = t.classes) == null ? void 0 : h.message) || ""}">${t.message}</p>
- </div>
- ${t.dismissible ? `<button class="toast-close ${((u2 = t.classes) == null ? void 0 : u2.close) || ""}">${M$1.close}</button>` : ""}
- `, i2.className = `toast ${t.type || ""} ${((a2 = t.classes) == null ? void 0 : a2.toast) || ""} `, i2.style.cssText = t.style || "", i2.dataset.styled = t.unstyled ? "false" : "true", l(this, r$1).append(i2), i2.dataset.isNew ? setTimeout(() => i2.classList.add("visible"), 0) : i2.classList.add("visible"), t.durationMs !== 1 / 0 && (clearTimeout(this.toastTimeoutMap.get(i2.id)), this.toastTimeoutMap.set(
- i2.id,
- setTimeout(() => this.dismiss(i2.id), t.durationMs)
- )), t.dismissible && i2.querySelector(".toast-close").addEventListener(
- "click",
- () => this.dismiss(i2.id)
- ), i2.id;
- }, d = function(e2, t) {
- return n(this, o$2, k$1).call(this, {
- ...t,
- type: e2,
- title: t.title ?? this.defaultOptions.title ?? e2[0].toUpperCase() + e2.slice(1)
- });
- };
- const CONFIG = {
- APP_NAME: "LeetCode Toolkit",
- EDITORIAL_READER_URL: "https://leetcode-editorial-reader.vercel.app"
- };
- const toaster = new L({
- title: CONFIG.APP_NAME,
- position: "top-center"
- });
- class ProblemPageState {
- constructor() {
- __publicField(this, "editor", null);
- }
- async patchMonacoEditor() {
- this.editor = await findMonacoEditor();
- this.enableFormatOnSave();
- addIntellisense(this.editor);
- }
- enableFormatOnSave() {
- document.addEventListener("keydown", async (e2) => {
- var _a2, _b;
- if (!(e2.ctrlKey && e2.key === "s")) return;
- try {
- await ((_b = (_a2 = this.editor) == null ? void 0 : _a2.getAction("editor.action.formatDocument")) == null ? void 0 : _b.run());
- } catch (err) {
- console.error(err);
- if (err instanceof Error) {
- toaster.error("Failed to format code:" + err.message);
- }
- }
- });
- }
- }
- const problemState = new ProblemPageState();
- function u$1(o2, n2, a2) {
- let t = (r2) => o2(r2, ...n2);
- return t;
- }
- function u(r2, n2, o2) {
- let a2 = r2.length - n2.length;
- if (a2 === 0) return r2(...n2);
- if (a2 === 1) return u$1(r2, n2);
- throw new Error("Wrong number of arguments");
- }
- var o$1 = [" ", `
- `, "\v", "\f", "\r", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "\u2028", "\u2029", " ", " ", " ", "\uFEFF"], c = /* @__PURE__ */ new Set(["-", "_", ...o$1]), i = (r2) => {
- let e2 = [], t = "", u2 = () => {
- t.length > 0 && (e2.push(t), t = "");
- };
- for (let s of r2) {
- if (c.has(s)) {
- u2();
- continue;
- }
- if (/[a-z]$/u.test(t) && /[A-Z]/u.test(s)) u2();
- else if (/[A-Z][A-Z]$/u.test(t) && /[a-z]/u.test(s)) {
- let n2 = t.slice(-1);
- t = t.slice(0, -1), u2(), t = n2;
- } else /\d$/u.test(t) !== /\d/u.test(s) && u2();
- t += s;
- }
- return u2(), e2;
- };
- function a(...e2) {
- return u(o, e2);
- }
- var o = (e2) => i(e2).join("-").toLowerCase();
- function e(o2) {
- return o2 instanceof Promise;
- }
- const DEV = false;
- var is_array = Array.isArray;
- var index_of = Array.prototype.indexOf;
- var array_from = Array.from;
- var define_property = Object.defineProperty;
- var get_descriptor = Object.getOwnPropertyDescriptor;
- var get_descriptors = Object.getOwnPropertyDescriptors;
- var object_prototype = Object.prototype;
- var array_prototype = Array.prototype;
- var get_prototype_of = Object.getPrototypeOf;
- var is_extensible = Object.isExtensible;
- const noop = () => {
- };
- function run(fn) {
- return fn();
- }
- function run_all(arr) {
- for (var i2 = 0; i2 < arr.length; i2++) {
- arr[i2]();
- }
- }
- const DERIVED = 1 << 1;
- const EFFECT = 1 << 2;
- const RENDER_EFFECT = 1 << 3;
- const BLOCK_EFFECT = 1 << 4;
- const BRANCH_EFFECT = 1 << 5;
- const ROOT_EFFECT = 1 << 6;
- const BOUNDARY_EFFECT = 1 << 7;
- const UNOWNED = 1 << 8;
- const DISCONNECTED = 1 << 9;
- const CLEAN = 1 << 10;
- const DIRTY = 1 << 11;
- const MAYBE_DIRTY = 1 << 12;
- const INERT = 1 << 13;
- const DESTROYED = 1 << 14;
- const EFFECT_RAN = 1 << 15;
- const EFFECT_TRANSPARENT = 1 << 16;
- const INSPECT_EFFECT = 1 << 18;
- const HEAD_EFFECT = 1 << 19;
- const EFFECT_HAS_DERIVED = 1 << 20;
- const EFFECT_IS_UPDATING = 1 << 21;
- const STATE_SYMBOL = Symbol("$state");
- const LOADING_ATTR_SYMBOL = Symbol("");
- function equals(value) {
- return value === this.v;
- }
- function effect_in_teardown(rune) {
- {
- throw new Error(`https://svelte.dev/e/effect_in_teardown`);
- }
- }
- function effect_in_unowned_derived() {
- {
- throw new Error(`https://svelte.dev/e/effect_in_unowned_derived`);
- }
- }
- function effect_orphan(rune) {
- {
- throw new Error(`https://svelte.dev/e/effect_orphan`);
- }
- }
- function effect_update_depth_exceeded() {
- {
- throw new Error(`https://svelte.dev/e/effect_update_depth_exceeded`);
- }
- }
- function state_descriptors_fixed() {
- {
- throw new Error(`https://svelte.dev/e/state_descriptors_fixed`);
- }
- }
- function state_prototype_fixed() {
- {
- throw new Error(`https://svelte.dev/e/state_prototype_fixed`);
- }
- }
- function state_unsafe_mutation() {
- {
- throw new Error(`https://svelte.dev/e/state_unsafe_mutation`);
- }
- }
- let legacy_mode_flag = false;
- let tracing_mode_flag = false;
- function enable_legacy_mode_flag() {
- legacy_mode_flag = true;
- }
- const TEMPLATE_FRAGMENT = 1;
- const TEMPLATE_USE_IMPORT_NODE = 1 << 1;
- const UNINITIALIZED = Symbol();
- const NAMESPACE_HTML = "http://www.w3.org/1999/xhtml";
- const ATTACHMENT_KEY = "@attach";
- let component_context = null;
- function set_component_context(context) {
- component_context = context;
- }
- function push(props, runes = false, fn) {
- var ctx = component_context = {
- p: component_context,
- c: null,
- d: false,
- e: null,
- m: false,
- s: props,
- x: null,
- l: null
- };
- if (legacy_mode_flag && !runes) {
- component_context.l = {
- s: null,
- u: null,
- r1: [],
- r2: source(false)
- };
- }
- teardown(() => {
- ctx.d = true;
- });
- }
- function pop(component) {
- const context_stack_item = component_context;
- if (context_stack_item !== null) {
- const component_effects = context_stack_item.e;
- if (component_effects !== null) {
- var previous_effect = active_effect;
- var previous_reaction = active_reaction;
- context_stack_item.e = null;
- try {
- for (var i2 = 0; i2 < component_effects.length; i2++) {
- var component_effect = component_effects[i2];
- set_active_effect(component_effect.effect);
- set_active_reaction(component_effect.reaction);
- effect(component_effect.fn);
- }
- } finally {
- set_active_effect(previous_effect);
- set_active_reaction(previous_reaction);
- }
- }
- component_context = context_stack_item.p;
- context_stack_item.m = true;
- }
- return (
- /** @type {T} */
- {}
- );
- }
- function is_runes() {
- return !legacy_mode_flag || component_context !== null && component_context.l === null;
- }
- function proxy(value) {
- if (typeof value !== "object" || value === null || STATE_SYMBOL in value) {
- return value;
- }
- const prototype = get_prototype_of(value);
- if (prototype !== object_prototype && prototype !== array_prototype) {
- return value;
- }
- var sources = /* @__PURE__ */ new Map();
- var is_proxied_array = is_array(value);
- var version = /* @__PURE__ */ state(0);
- var reaction = active_reaction;
- var with_parent = (fn) => {
- var previous_reaction = active_reaction;
- set_active_reaction(reaction);
- var result = fn();
- set_active_reaction(previous_reaction);
- return result;
- };
- if (is_proxied_array) {
- sources.set("length", /* @__PURE__ */ state(
- /** @type {any[]} */
- value.length
- ));
- }
- return new Proxy(
- /** @type {any} */
- value,
- {
- defineProperty(_, prop2, descriptor) {
- if (!("value" in descriptor) || descriptor.configurable === false || descriptor.enumerable === false || descriptor.writable === false) {
- state_descriptors_fixed();
- }
- var s = sources.get(prop2);
- if (s === void 0) {
- s = with_parent(() => {
- var s2 = /* @__PURE__ */ state(descriptor.value);
- sources.set(prop2, s2);
- return s2;
- });
- } else {
- set(s, descriptor.value, true);
- }
- return true;
- },
- deleteProperty(target, prop2) {
- var s = sources.get(prop2);
- if (s === void 0) {
- if (prop2 in target) {
- const s2 = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED));
- sources.set(prop2, s2);
- update_version(version);
- }
- } else {
- if (is_proxied_array && typeof prop2 === "string") {
- var ls = (
- /** @type {Source<number>} */
- sources.get("length")
- );
- var n2 = Number(prop2);
- if (Number.isInteger(n2) && n2 < ls.v) {
- set(ls, n2);
- }
- }
- set(s, UNINITIALIZED);
- update_version(version);
- }
- return true;
- },
- get(target, prop2, receiver) {
- var _a2;
- if (prop2 === STATE_SYMBOL) {
- return value;
- }
- var s = sources.get(prop2);
- var exists = prop2 in target;
- if (s === void 0 && (!exists || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable))) {
- s = with_parent(() => {
- var p2 = proxy(exists ? target[prop2] : UNINITIALIZED);
- var s2 = /* @__PURE__ */ state(p2);
- return s2;
- });
- sources.set(prop2, s);
- }
- if (s !== void 0) {
- var v2 = get(s);
- return v2 === UNINITIALIZED ? void 0 : v2;
- }
- return Reflect.get(target, prop2, receiver);
- },
- getOwnPropertyDescriptor(target, prop2) {
- var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
- if (descriptor && "value" in descriptor) {
- var s = sources.get(prop2);
- if (s) descriptor.value = get(s);
- } else if (descriptor === void 0) {
- var source2 = sources.get(prop2);
- var value2 = source2 == null ? void 0 : source2.v;
- if (source2 !== void 0 && value2 !== UNINITIALIZED) {
- return {
- enumerable: true,
- configurable: true,
- value: value2,
- writable: true
- };
- }
- }
- return descriptor;
- },
- has(target, prop2) {
- var _a2;
- if (prop2 === STATE_SYMBOL) {
- return true;
- }
- var s = sources.get(prop2);
- var has = s !== void 0 && s.v !== UNINITIALIZED || Reflect.has(target, prop2);
- if (s !== void 0 || active_effect !== null && (!has || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable))) {
- if (s === void 0) {
- s = with_parent(() => {
- var p2 = has ? proxy(target[prop2]) : UNINITIALIZED;
- var s2 = /* @__PURE__ */ state(p2);
- return s2;
- });
- sources.set(prop2, s);
- }
- var value2 = get(s);
- if (value2 === UNINITIALIZED) {
- return false;
- }
- }
- return has;
- },
- set(target, prop2, value2, receiver) {
- var _a2;
- var s = sources.get(prop2);
- var has = prop2 in target;
- if (is_proxied_array && prop2 === "length") {
- for (var i2 = value2; i2 < /** @type {Source<number>} */
- s.v; i2 += 1) {
- var other_s = sources.get(i2 + "");
- if (other_s !== void 0) {
- set(other_s, UNINITIALIZED);
- } else if (i2 in target) {
- other_s = with_parent(() => /* @__PURE__ */ state(UNINITIALIZED));
- sources.set(i2 + "", other_s);
- }
- }
- }
- if (s === void 0) {
- if (!has || ((_a2 = get_descriptor(target, prop2)) == null ? void 0 : _a2.writable)) {
- s = with_parent(() => /* @__PURE__ */ state(void 0));
- set(s, proxy(value2));
- sources.set(prop2, s);
- }
- } else {
- has = s.v !== UNINITIALIZED;
- var p2 = with_parent(() => proxy(value2));
- set(s, p2);
- }
- var descriptor = Reflect.getOwnPropertyDescriptor(target, prop2);
- if (descriptor == null ? void 0 : descriptor.set) {
- descriptor.set.call(receiver, value2);
- }
- if (!has) {
- if (is_proxied_array && typeof prop2 === "string") {
- var ls = (
- /** @type {Source<number>} */
- sources.get("length")
- );
- var n2 = Number(prop2);
- if (Number.isInteger(n2) && n2 >= ls.v) {
- set(ls, n2 + 1);
- }
- }
- update_version(version);
- }
- return true;
- },
- ownKeys(target) {
- get(version);
- var own_keys = Reflect.ownKeys(target).filter((key2) => {
- var source3 = sources.get(key2);
- return source3 === void 0 || source3.v !== UNINITIALIZED;
- });
- for (var [key, source2] of sources) {
- if (source2.v !== UNINITIALIZED && !(key in target)) {
- own_keys.push(key);
- }
- }
- return own_keys;
- },
- setPrototypeOf() {
- state_prototype_fixed();
- }
- }
- );
- }
- function update_version(signal, d2 = 1) {
- set(signal, signal.v + d2);
- }
- function get_proxied_value(value) {
- try {
- if (value !== null && typeof value === "object" && STATE_SYMBOL in value) {
- return value[STATE_SYMBOL];
- }
- } catch {
- }
- return value;
- }
- function is(a2, b2) {
- return Object.is(get_proxied_value(a2), get_proxied_value(b2));
- }
- // @__NO_SIDE_EFFECTS__
- function derived(fn) {
- var flags = DERIVED | DIRTY;
- var parent_derived = active_reaction !== null && (active_reaction.f & DERIVED) !== 0 ? (
- /** @type {Derived} */
- active_reaction
- ) : null;
- if (active_effect === null || parent_derived !== null && (parent_derived.f & UNOWNED) !== 0) {
- flags |= UNOWNED;
- } else {
- active_effect.f |= EFFECT_HAS_DERIVED;
- }
- const signal = {
- ctx: component_context,
- deps: null,
- effects: null,
- equals,
- f: flags,
- fn,
- reactions: null,
- rv: 0,
- v: (
- /** @type {V} */
- null
- ),
- wv: 0,
- parent: parent_derived ?? active_effect
- };
- return signal;
- }
- function destroy_derived_effects(derived2) {
- var effects = derived2.effects;
- if (effects !== null) {
- derived2.effects = null;
- for (var i2 = 0; i2 < effects.length; i2 += 1) {
- destroy_effect(
- /** @type {Effect} */
- effects[i2]
- );
- }
- }
- }
- function get_derived_parent_effect(derived2) {
- var parent = derived2.parent;
- while (parent !== null) {
- if ((parent.f & DERIVED) === 0) {
- return (
- /** @type {Effect} */
- parent
- );
- }
- parent = parent.parent;
- }
- return null;
- }
- function execute_derived(derived2) {
- var value;
- var prev_active_effect = active_effect;
- set_active_effect(get_derived_parent_effect(derived2));
- {
- try {
- destroy_derived_effects(derived2);
- value = update_reaction(derived2);
- } finally {
- set_active_effect(prev_active_effect);
- }
- }
- return value;
- }
- function update_derived(derived2) {
- var value = execute_derived(derived2);
- if (!derived2.equals(value)) {
- derived2.v = value;
- derived2.wv = increment_write_version();
- }
- if (is_destroying_effect) return;
- var status = (skip_reaction || (derived2.f & UNOWNED) !== 0) && derived2.deps !== null ? MAYBE_DIRTY : CLEAN;
- set_signal_status(derived2, status);
- }
- const old_values = /* @__PURE__ */ new Map();
- function source(v2, stack) {
- var signal = {
- f: 0,
- // TODO ideally we could skip this altogether, but it causes type errors
- v: v2,
- reactions: null,
- equals,
- rv: 0,
- wv: 0
- };
- return signal;
- }
- // @__NO_SIDE_EFFECTS__
- function state(v2, stack) {
- const s = source(v2);
- push_reaction_value(s);
- return s;
- }
- function set(source2, value, should_proxy = false) {
- if (active_reaction !== null && // since we are untracking the function inside `$inspect.with` we need to add this check
- // to ensure we error if state is set inside an inspect effect
- (!untracking || (active_reaction.f & INSPECT_EFFECT) !== 0) && is_runes() && (active_reaction.f & (DERIVED | BLOCK_EFFECT | INSPECT_EFFECT)) !== 0 && !((reaction_sources == null ? void 0 : reaction_sources[1].includes(source2)) && reaction_sources[0] === active_reaction)) {
- state_unsafe_mutation();
- }
- let new_value = should_proxy ? proxy(value) : value;
- return internal_set(source2, new_value);
- }
- function internal_set(source2, value) {
- if (!source2.equals(value)) {
- var old_value = source2.v;
- if (is_destroying_effect) {
- old_values.set(source2, value);
- } else {
- old_values.set(source2, old_value);
- }
- source2.v = value;
- if ((source2.f & DERIVED) !== 0) {
- if ((source2.f & DIRTY) !== 0) {
- execute_derived(
- /** @type {Derived} */
- source2
- );
- }
- set_signal_status(source2, (source2.f & UNOWNED) === 0 ? CLEAN : MAYBE_DIRTY);
- }
- source2.wv = increment_write_version();
- mark_reactions(source2, DIRTY);
- if (is_runes() && active_effect !== null && (active_effect.f & CLEAN) !== 0 && (active_effect.f & (BRANCH_EFFECT | ROOT_EFFECT)) === 0) {
- if (untracked_writes === null) {
- set_untracked_writes([source2]);
- } else {
- untracked_writes.push(source2);
- }
- }
- }
- return value;
- }
- function mark_reactions(signal, status) {
- var reactions = signal.reactions;
- if (reactions === null) return;
- var runes = is_runes();
- var length = reactions.length;
- for (var i2 = 0; i2 < length; i2++) {
- var reaction = reactions[i2];
- var flags = reaction.f;
- if ((flags & DIRTY) !== 0) continue;
- if (!runes && reaction === active_effect) continue;
- set_signal_status(reaction, status);
- if ((flags & (CLEAN | UNOWNED)) !== 0) {
- if ((flags & DERIVED) !== 0) {
- mark_reactions(
- /** @type {Derived} */
- reaction,
- MAYBE_DIRTY
- );
- } else {
- schedule_effect(
- /** @type {Effect} */
- reaction
- );
- }
- }
- }
- }
- function select_multiple_invalid_value() {
- {
- console.warn(`https://svelte.dev/e/select_multiple_invalid_value`);
- }
- }
- var $window;
- var is_firefox;
- var first_child_getter;
- var next_sibling_getter;
- function init_operations() {
- if ($window !== void 0) {
- return;
- }
- $window = window;
- is_firefox = /Firefox/.test(navigator.userAgent);
- var element_prototype = Element.prototype;
- var node_prototype = Node.prototype;
- var text_prototype = Text.prototype;
- first_child_getter = get_descriptor(node_prototype, "firstChild").get;
- next_sibling_getter = get_descriptor(node_prototype, "nextSibling").get;
- if (is_extensible(element_prototype)) {
- element_prototype.__click = void 0;
- element_prototype.__className = void 0;
- element_prototype.__attributes = null;
- element_prototype.__style = void 0;
- element_prototype.__e = void 0;
- }
- if (is_extensible(text_prototype)) {
- text_prototype.__t = void 0;
- }
- }
- function create_text(value = "") {
- return document.createTextNode(value);
- }
- // @__NO_SIDE_EFFECTS__
- function get_first_child(node) {
- return first_child_getter.call(node);
- }
- // @__NO_SIDE_EFFECTS__
- function get_next_sibling(node) {
- return next_sibling_getter.call(node);
- }
- function child(node, is_text) {
- {
- return /* @__PURE__ */ get_first_child(node);
- }
- }
- function first_child(fragment, is_text) {
- {
- var first = (
- /** @type {DocumentFragment} */
- /* @__PURE__ */ get_first_child(
- /** @type {Node} */
- fragment
- )
- );
- if (first instanceof Comment && first.data === "") return /* @__PURE__ */ get_next_sibling(first);
- return first;
- }
- }
- function sibling(node, count = 1, is_text = false) {
- let next_sibling = node;
- while (count--) {
- next_sibling = /** @type {TemplateNode} */
- /* @__PURE__ */ get_next_sibling(next_sibling);
- }
- {
- return next_sibling;
- }
- }
- function validate_effect(rune) {
- if (active_effect === null && active_reaction === null) {
- effect_orphan();
- }
- if (active_reaction !== null && (active_reaction.f & UNOWNED) !== 0 && active_effect === null) {
- effect_in_unowned_derived();
- }
- if (is_destroying_effect) {
- effect_in_teardown();
- }
- }
- function push_effect(effect2, parent_effect) {
- var parent_last = parent_effect.last;
- if (parent_last === null) {
- parent_effect.last = parent_effect.first = effect2;
- } else {
- parent_last.next = effect2;
- effect2.prev = parent_last;
- parent_effect.last = effect2;
- }
- }
- function create_effect(type, fn, sync, push2 = true) {
- var parent = active_effect;
- var effect2 = {
- ctx: component_context,
- deps: null,
- nodes_start: null,
- nodes_end: null,
- f: type | DIRTY,
- first: null,
- fn,
- last: null,
- next: null,
- parent,
- prev: null,
- teardown: null,
- transitions: null,
- wv: 0
- };
- if (sync) {
- try {
- update_effect(effect2);
- effect2.f |= EFFECT_RAN;
- } catch (e2) {
- destroy_effect(effect2);
- throw e2;
- }
- } else if (fn !== null) {
- schedule_effect(effect2);
- }
- var inert = sync && effect2.deps === null && effect2.first === null && effect2.nodes_start === null && effect2.teardown === null && (effect2.f & (EFFECT_HAS_DERIVED | BOUNDARY_EFFECT)) === 0;
- if (!inert && push2) {
- if (parent !== null) {
- push_effect(effect2, parent);
- }
- if (active_reaction !== null && (active_reaction.f & DERIVED) !== 0) {
- var derived2 = (
- /** @type {Derived} */
- active_reaction
- );
- (derived2.effects ?? (derived2.effects = [])).push(effect2);
- }
- }
- return effect2;
- }
- function teardown(fn) {
- const effect2 = create_effect(RENDER_EFFECT, null, false);
- set_signal_status(effect2, CLEAN);
- effect2.teardown = fn;
- return effect2;
- }
- function user_effect(fn) {
- validate_effect();
- var defer = active_effect !== null && (active_effect.f & BRANCH_EFFECT) !== 0 && component_context !== null && !component_context.m;
- if (defer) {
- var context = (
- /** @type {ComponentContext} */
- component_context
- );
- (context.e ?? (context.e = [])).push({
- fn,
- effect: active_effect,
- reaction: active_reaction
- });
- } else {
- var signal = effect(fn);
- return signal;
- }
- }
- function user_pre_effect(fn) {
- validate_effect();
- return render_effect(fn);
- }
- function component_root(fn) {
- const effect2 = create_effect(ROOT_EFFECT, fn, true);
- return (options = {}) => {
- return new Promise((fulfil) => {
- if (options.outro) {
- pause_effect(effect2, () => {
- destroy_effect(effect2);
- fulfil(void 0);
- });
- } else {
- destroy_effect(effect2);
- fulfil(void 0);
- }
- });
- };
- }
- function effect(fn) {
- return create_effect(EFFECT, fn, false);
- }
- function render_effect(fn) {
- return create_effect(RENDER_EFFECT, fn, true);
- }
- function template_effect(fn, thunks = [], d2 = derived) {
- const deriveds = thunks.map(d2);
- return block(() => fn(...deriveds.map(get)));
- }
- function block(fn, flags = 0) {
- return create_effect(RENDER_EFFECT | BLOCK_EFFECT | flags, fn, true);
- }
- function branch(fn, push2 = true) {
- return create_effect(RENDER_EFFECT | BRANCH_EFFECT, fn, true, push2);
- }
- function execute_effect_teardown(effect2) {
- var teardown2 = effect2.teardown;
- if (teardown2 !== null) {
- const previously_destroying_effect = is_destroying_effect;
- const previous_reaction = active_reaction;
- set_is_destroying_effect(true);
- set_active_reaction(null);
- try {
- teardown2.call(null);
- } finally {
- set_is_destroying_effect(previously_destroying_effect);
- set_active_reaction(previous_reaction);
- }
- }
- }
- function destroy_effect_children(signal, remove_dom = false) {
- var effect2 = signal.first;
- signal.first = signal.last = null;
- while (effect2 !== null) {
- var next = effect2.next;
- if ((effect2.f & ROOT_EFFECT) !== 0) {
- effect2.parent = null;
- } else {
- destroy_effect(effect2, remove_dom);
- }
- effect2 = next;
- }
- }
- function destroy_block_effect_children(signal) {
- var effect2 = signal.first;
- while (effect2 !== null) {
- var next = effect2.next;
- if ((effect2.f & BRANCH_EFFECT) === 0) {
- destroy_effect(effect2);
- }
- effect2 = next;
- }
- }
- function destroy_effect(effect2, remove_dom = true) {
- var removed = false;
- if ((remove_dom || (effect2.f & HEAD_EFFECT) !== 0) && effect2.nodes_start !== null && effect2.nodes_end !== null) {
- remove_effect_dom(
- effect2.nodes_start,
- /** @type {TemplateNode} */
- effect2.nodes_end
- );
- removed = true;
- }
- destroy_effect_children(effect2, remove_dom && !removed);
- remove_reactions(effect2, 0);
- set_signal_status(effect2, DESTROYED);
- var transitions = effect2.transitions;
- if (transitions !== null) {
- for (const transition of transitions) {
- transition.stop();
- }
- }
- execute_effect_teardown(effect2);
- var parent = effect2.parent;
- if (parent !== null && parent.first !== null) {
- unlink_effect(effect2);
- }
- effect2.next = effect2.prev = effect2.teardown = effect2.ctx = effect2.deps = effect2.fn = effect2.nodes_start = effect2.nodes_end = null;
- }
- function remove_effect_dom(node, end) {
- while (node !== null) {
- var next = node === end ? null : (
- /** @type {TemplateNode} */
- /* @__PURE__ */ get_next_sibling(node)
- );
- node.remove();
- node = next;
- }
- }
- function unlink_effect(effect2) {
- var parent = effect2.parent;
- var prev = effect2.prev;
- var next = effect2.next;
- if (prev !== null) prev.next = next;
- if (next !== null) next.prev = prev;
- if (parent !== null) {
- if (parent.first === effect2) parent.first = next;
- if (parent.last === effect2) parent.last = prev;
- }
- }
- function pause_effect(effect2, callback) {
- var transitions = [];
- pause_children(effect2, transitions, true);
- run_out_transitions(transitions, () => {
- destroy_effect(effect2);
- if (callback) callback();
- });
- }
- function run_out_transitions(transitions, fn) {
- var remaining = transitions.length;
- if (remaining > 0) {
- var check = () => --remaining || fn();
- for (var transition of transitions) {
- transition.out(check);
- }
- } else {
- fn();
- }
- }
- function pause_children(effect2, transitions, local) {
- if ((effect2.f & INERT) !== 0) return;
- effect2.f ^= INERT;
- if (effect2.transitions !== null) {
- for (const transition of effect2.transitions) {
- if (transition.is_global || local) {
- transitions.push(transition);
- }
- }
- }
- var child2 = effect2.first;
- while (child2 !== null) {
- var sibling2 = child2.next;
- var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
- pause_children(child2, transitions, transparent ? local : false);
- child2 = sibling2;
- }
- }
- function resume_effect(effect2) {
- resume_children(effect2, true);
- }
- function resume_children(effect2, local) {
- if ((effect2.f & INERT) === 0) return;
- effect2.f ^= INERT;
- var child2 = effect2.first;
- while (child2 !== null) {
- var sibling2 = child2.next;
- var transparent = (child2.f & EFFECT_TRANSPARENT) !== 0 || (child2.f & BRANCH_EFFECT) !== 0;
- resume_children(child2, transparent ? local : false);
- child2 = sibling2;
- }
- if (effect2.transitions !== null) {
- for (const transition of effect2.transitions) {
- if (transition.is_global || local) {
- transition.in();
- }
- }
- }
- }
- let micro_tasks = [];
- function run_micro_tasks() {
- var tasks = micro_tasks;
- micro_tasks = [];
- run_all(tasks);
- }
- function queue_micro_task(fn) {
- if (micro_tasks.length === 0) {
- queueMicrotask(run_micro_tasks);
- }
- micro_tasks.push(fn);
- }
- function handle_error(error) {
- var effect2 = (
- /** @type {Effect} */
- active_effect
- );
- if ((effect2.f & EFFECT_RAN) === 0) {
- if ((effect2.f & BOUNDARY_EFFECT) === 0) {
- throw error;
- }
- effect2.fn(error);
- } else {
- invoke_error_boundary(error, effect2);
- }
- }
- function invoke_error_boundary(error, effect2) {
- while (effect2 !== null) {
- if ((effect2.f & BOUNDARY_EFFECT) !== 0) {
- try {
- effect2.fn(error);
- return;
- } catch {
- }
- }
- effect2 = effect2.parent;
- }
- throw error;
- }
- let is_flushing = false;
- let last_scheduled_effect = null;
- let is_updating_effect = false;
- let is_destroying_effect = false;
- function set_is_destroying_effect(value) {
- is_destroying_effect = value;
- }
- let queued_root_effects = [];
- let active_reaction = null;
- let untracking = false;
- function set_active_reaction(reaction) {
- active_reaction = reaction;
- }
- let active_effect = null;
- function set_active_effect(effect2) {
- active_effect = effect2;
- }
- let reaction_sources = null;
- function push_reaction_value(value) {
- if (active_reaction !== null && active_reaction.f & EFFECT_IS_UPDATING) {
- if (reaction_sources === null) {
- reaction_sources = [active_reaction, [value]];
- } else {
- reaction_sources[1].push(value);
- }
- }
- }
- let new_deps = null;
- let skipped_deps = 0;
- let untracked_writes = null;
- function set_untracked_writes(value) {
- untracked_writes = value;
- }
- let write_version = 1;
- let read_version = 0;
- let skip_reaction = false;
- function increment_write_version() {
- return ++write_version;
- }
- function check_dirtiness(reaction) {
- var _a2;
- var flags = reaction.f;
- if ((flags & DIRTY) !== 0) {
- return true;
- }
- if ((flags & MAYBE_DIRTY) !== 0) {
- var dependencies = reaction.deps;
- var is_unowned = (flags & UNOWNED) !== 0;
- if (dependencies !== null) {
- var i2;
- var dependency;
- var is_disconnected = (flags & DISCONNECTED) !== 0;
- var is_unowned_connected = is_unowned && active_effect !== null && !skip_reaction;
- var length = dependencies.length;
- if (is_disconnected || is_unowned_connected) {
- var derived2 = (
- /** @type {Derived} */
- reaction
- );
- var parent = derived2.parent;
- for (i2 = 0; i2 < length; i2++) {
- dependency = dependencies[i2];
- if (is_disconnected || !((_a2 = dependency == null ? void 0 : dependency.reactions) == null ? void 0 : _a2.includes(derived2))) {
- (dependency.reactions ?? (dependency.reactions = [])).push(derived2);
- }
- }
- if (is_disconnected) {
- derived2.f ^= DISCONNECTED;
- }
- if (is_unowned_connected && parent !== null && (parent.f & UNOWNED) === 0) {
- derived2.f ^= UNOWNED;
- }
- }
- for (i2 = 0; i2 < length; i2++) {
- dependency = dependencies[i2];
- if (check_dirtiness(
- /** @type {Derived} */
- dependency
- )) {
- update_derived(
- /** @type {Derived} */
- dependency
- );
- }
- if (dependency.wv > reaction.wv) {
- return true;
- }
- }
- }
- if (!is_unowned || active_effect !== null && !skip_reaction) {
- set_signal_status(reaction, CLEAN);
- }
- }
- return false;
- }
- function schedule_possible_effect_self_invalidation(signal, effect2, root2 = true) {
- var reactions = signal.reactions;
- if (reactions === null) return;
- for (var i2 = 0; i2 < reactions.length; i2++) {
- var reaction = reactions[i2];
- if ((reaction_sources == null ? void 0 : reaction_sources[1].includes(signal)) && reaction_sources[0] === active_reaction) continue;
- if ((reaction.f & DERIVED) !== 0) {
- schedule_possible_effect_self_invalidation(
- /** @type {Derived} */
- reaction,
- effect2,
- false
- );
- } else if (effect2 === reaction) {
- if (root2) {
- set_signal_status(reaction, DIRTY);
- } else if ((reaction.f & CLEAN) !== 0) {
- set_signal_status(reaction, MAYBE_DIRTY);
- }
- schedule_effect(
- /** @type {Effect} */
- reaction
- );
- }
- }
- }
- function update_reaction(reaction) {
- var _a2;
- var previous_deps = new_deps;
- var previous_skipped_deps = skipped_deps;
- var previous_untracked_writes = untracked_writes;
- var previous_reaction = active_reaction;
- var previous_skip_reaction = skip_reaction;
- var previous_reaction_sources = reaction_sources;
- var previous_component_context = component_context;
- var previous_untracking = untracking;
- var flags = reaction.f;
- new_deps = /** @type {null | Value[]} */
- null;
- skipped_deps = 0;
- untracked_writes = null;
- skip_reaction = (flags & UNOWNED) !== 0 && (untracking || !is_updating_effect || active_reaction === null);
- active_reaction = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) === 0 ? reaction : null;
- reaction_sources = null;
- set_component_context(reaction.ctx);
- untracking = false;
- read_version++;
- reaction.f |= EFFECT_IS_UPDATING;
- try {
- var result = (
- /** @type {Function} */
- (0, reaction.fn)()
- );
- var deps = reaction.deps;
- if (new_deps !== null) {
- var i2;
- remove_reactions(reaction, skipped_deps);
- if (deps !== null && skipped_deps > 0) {
- deps.length = skipped_deps + new_deps.length;
- for (i2 = 0; i2 < new_deps.length; i2++) {
- deps[skipped_deps + i2] = new_deps[i2];
- }
- } else {
- reaction.deps = deps = new_deps;
- }
- if (!skip_reaction) {
- for (i2 = skipped_deps; i2 < deps.length; i2++) {
- ((_a2 = deps[i2]).reactions ?? (_a2.reactions = [])).push(reaction);
- }
- }
- } else if (deps !== null && skipped_deps < deps.length) {
- remove_reactions(reaction, skipped_deps);
- deps.length = skipped_deps;
- }
- if (is_runes() && untracked_writes !== null && !untracking && deps !== null && (reaction.f & (DERIVED | MAYBE_DIRTY | DIRTY)) === 0) {
- for (i2 = 0; i2 < /** @type {Source[]} */
- untracked_writes.length; i2++) {
- schedule_possible_effect_self_invalidation(
- untracked_writes[i2],
- /** @type {Effect} */
- reaction
- );
- }
- }
- if (previous_reaction !== null && previous_reaction !== reaction) {
- read_version++;
- if (untracked_writes !== null) {
- if (previous_untracked_writes === null) {
- previous_untracked_writes = untracked_writes;
- } else {
- previous_untracked_writes.push(.../** @type {Source[]} */
- untracked_writes);
- }
- }
- }
- return result;
- } catch (error) {
- handle_error(error);
- } finally {
- new_deps = previous_deps;
- skipped_deps = previous_skipped_deps;
- untracked_writes = previous_untracked_writes;
- active_reaction = previous_reaction;
- skip_reaction = previous_skip_reaction;
- reaction_sources = previous_reaction_sources;
- set_component_context(previous_component_context);
- untracking = previous_untracking;
- reaction.f ^= EFFECT_IS_UPDATING;
- }
- }
- function remove_reaction(signal, dependency) {
- let reactions = dependency.reactions;
- if (reactions !== null) {
- var index = index_of.call(reactions, signal);
- if (index !== -1) {
- var new_length = reactions.length - 1;
- if (new_length === 0) {
- reactions = dependency.reactions = null;
- } else {
- reactions[index] = reactions[new_length];
- reactions.pop();
- }
- }
- }
- if (reactions === null && (dependency.f & DERIVED) !== 0 && // Destroying a child effect while updating a parent effect can cause a dependency to appear
- // to be unused, when in fact it is used by the currently-updating parent. Checking `new_deps`
- // allows us to skip the expensive work of disconnecting and immediately reconnecting it
- (new_deps === null || !new_deps.includes(dependency))) {
- set_signal_status(dependency, MAYBE_DIRTY);
- if ((dependency.f & (UNOWNED | DISCONNECTED)) === 0) {
- dependency.f ^= DISCONNECTED;
- }
- destroy_derived_effects(
- /** @type {Derived} **/
- dependency
- );
- remove_reactions(
- /** @type {Derived} **/
- dependency,
- 0
- );
- }
- }
- function remove_reactions(signal, start_index) {
- var dependencies = signal.deps;
- if (dependencies === null) return;
- for (var i2 = start_index; i2 < dependencies.length; i2++) {
- remove_reaction(signal, dependencies[i2]);
- }
- }
- function update_effect(effect2) {
- var flags = effect2.f;
- if ((flags & DESTROYED) !== 0) {
- return;
- }
- set_signal_status(effect2, CLEAN);
- var previous_effect = active_effect;
- var was_updating_effect = is_updating_effect;
- active_effect = effect2;
- is_updating_effect = true;
- try {
- if ((flags & BLOCK_EFFECT) !== 0) {
- destroy_block_effect_children(effect2);
- } else {
- destroy_effect_children(effect2);
- }
- execute_effect_teardown(effect2);
- var teardown2 = update_reaction(effect2);
- effect2.teardown = typeof teardown2 === "function" ? teardown2 : null;
- effect2.wv = write_version;
- var dep;
- if (DEV && tracing_mode_flag && (effect2.f & DIRTY) !== 0 && effect2.deps !== null) ;
- if (DEV) ;
- } finally {
- is_updating_effect = was_updating_effect;
- active_effect = previous_effect;
- }
- }
- function infinite_loop_guard() {
- try {
- effect_update_depth_exceeded();
- } catch (error) {
- if (last_scheduled_effect !== null) {
- {
- invoke_error_boundary(error, last_scheduled_effect);
- }
- } else {
- throw error;
- }
- }
- }
- function flush_queued_root_effects() {
- var was_updating_effect = is_updating_effect;
- try {
- var flush_count = 0;
- is_updating_effect = true;
- while (queued_root_effects.length > 0) {
- if (flush_count++ > 1e3) {
- infinite_loop_guard();
- }
- var root_effects = queued_root_effects;
- var length = root_effects.length;
- queued_root_effects = [];
- for (var i2 = 0; i2 < length; i2++) {
- var collected_effects = process_effects(root_effects[i2]);
- flush_queued_effects(collected_effects);
- }
- old_values.clear();
- }
- } finally {
- is_flushing = false;
- is_updating_effect = was_updating_effect;
- last_scheduled_effect = null;
- }
- }
- function flush_queued_effects(effects) {
- var length = effects.length;
- if (length === 0) return;
- for (var i2 = 0; i2 < length; i2++) {
- var effect2 = effects[i2];
- if ((effect2.f & (DESTROYED | INERT)) === 0) {
- if (check_dirtiness(effect2)) {
- update_effect(effect2);
- if (effect2.deps === null && effect2.first === null && effect2.nodes_start === null) {
- if (effect2.teardown === null) {
- unlink_effect(effect2);
- } else {
- effect2.fn = null;
- }
- }
- }
- }
- }
- }
- function schedule_effect(signal) {
- if (!is_flushing) {
- is_flushing = true;
- queueMicrotask(flush_queued_root_effects);
- }
- var effect2 = last_scheduled_effect = signal;
- while (effect2.parent !== null) {
- effect2 = effect2.parent;
- var flags = effect2.f;
- if ((flags & (ROOT_EFFECT | BRANCH_EFFECT)) !== 0) {
- if ((flags & CLEAN) === 0) return;
- effect2.f ^= CLEAN;
- }
- }
- queued_root_effects.push(effect2);
- }
- function process_effects(root2) {
- var effects = [];
- var effect2 = root2;
- while (effect2 !== null) {
- var flags = effect2.f;
- var is_branch = (flags & (BRANCH_EFFECT | ROOT_EFFECT)) !== 0;
- var is_skippable_branch = is_branch && (flags & CLEAN) !== 0;
- if (!is_skippable_branch && (flags & INERT) === 0) {
- if ((flags & EFFECT) !== 0) {
- effects.push(effect2);
- } else if (is_branch) {
- effect2.f ^= CLEAN;
- } else {
- if (check_dirtiness(effect2)) {
- update_effect(effect2);
- }
- }
- var child2 = effect2.first;
- if (child2 !== null) {
- effect2 = child2;
- continue;
- }
- }
- var parent = effect2.parent;
- effect2 = effect2.next;
- while (effect2 === null && parent !== null) {
- effect2 = parent.next;
- parent = parent.parent;
- }
- }
- return effects;
- }
- function get(signal) {
- var flags = signal.f;
- var is_derived = (flags & DERIVED) !== 0;
- if (active_reaction !== null && !untracking) {
- if (!(reaction_sources == null ? void 0 : reaction_sources[1].includes(signal)) || reaction_sources[0] !== active_reaction) {
- var deps = active_reaction.deps;
- if (signal.rv < read_version) {
- signal.rv = read_version;
- if (new_deps === null && deps !== null && deps[skipped_deps] === signal) {
- skipped_deps++;
- } else if (new_deps === null) {
- new_deps = [signal];
- } else if (!skip_reaction || !new_deps.includes(signal)) {
- new_deps.push(signal);
- }
- }
- }
- } else if (is_derived && /** @type {Derived} */
- signal.deps === null && /** @type {Derived} */
- signal.effects === null) {
- var derived2 = (
- /** @type {Derived} */
- signal
- );
- var parent = derived2.parent;
- if (parent !== null && (parent.f & UNOWNED) === 0) {
- derived2.f ^= UNOWNED;
- }
- }
- if (is_derived) {
- derived2 = /** @type {Derived} */
- signal;
- if (check_dirtiness(derived2)) {
- update_derived(derived2);
- }
- }
- if (is_destroying_effect && old_values.has(signal)) {
- return old_values.get(signal);
- }
- return signal.v;
- }
- function untrack(fn) {
- var previous_untracking = untracking;
- try {
- untracking = true;
- return fn();
- } finally {
- untracking = previous_untracking;
- }
- }
- const STATUS_MASK = -7169;
- function set_signal_status(signal, status) {
- signal.f = signal.f & STATUS_MASK | status;
- }
- function deep_read_state(value) {
- if (typeof value !== "object" || !value || value instanceof EventTarget) {
- return;
- }
- if (STATE_SYMBOL in value) {
- deep_read(value);
- } else if (!Array.isArray(value)) {
- for (let key in value) {
- const prop2 = value[key];
- if (typeof prop2 === "object" && prop2 && STATE_SYMBOL in prop2) {
- deep_read(prop2);
- }
- }
- }
- }
- function deep_read(value, visited = /* @__PURE__ */ new Set()) {
- if (typeof value === "object" && value !== null && // We don't want to traverse DOM elements
- !(value instanceof EventTarget) && !visited.has(value)) {
- visited.add(value);
- if (value instanceof Date) {
- value.getTime();
- }
- for (let key in value) {
- try {
- deep_read(value[key], visited);
- } catch (e2) {
- }
- }
- const proto = get_prototype_of(value);
- if (proto !== Object.prototype && proto !== Array.prototype && proto !== Map.prototype && proto !== Set.prototype && proto !== Date.prototype) {
- const descriptors = get_descriptors(proto);
- for (let key in descriptors) {
- const get2 = descriptors[key].get;
- if (get2) {
- try {
- get2.call(value);
- } catch (e2) {
- }
- }
- }
- }
- }
- }
- function is_capture_event(name) {
- return name.endsWith("capture") && name !== "gotpointercapture" && name !== "lostpointercapture";
- }
- const DELEGATED_EVENTS = [
- "beforeinput",
- "click",
- "change",
- "dblclick",
- "contextmenu",
- "focusin",
- "focusout",
- "input",
- "keydown",
- "keyup",
- "mousedown",
- "mousemove",
- "mouseout",
- "mouseover",
- "mouseup",
- "pointerdown",
- "pointermove",
- "pointerout",
- "pointerover",
- "pointerup",
- "touchend",
- "touchmove",
- "touchstart"
- ];
- function is_delegated(event_name) {
- return DELEGATED_EVENTS.includes(event_name);
- }
- const ATTRIBUTE_ALIASES = {
- // no `class: 'className'` because we handle that separately
- formnovalidate: "formNoValidate",
- ismap: "isMap",
- nomodule: "noModule",
- playsinline: "playsInline",
- readonly: "readOnly",
- defaultvalue: "defaultValue",
- defaultchecked: "defaultChecked",
- srcobject: "srcObject",
- novalidate: "noValidate",
- allowfullscreen: "allowFullscreen",
- disablepictureinpicture: "disablePictureInPicture",
- disableremoteplayback: "disableRemotePlayback"
- };
- function normalize_attribute(name) {
- name = name.toLowerCase();
- return ATTRIBUTE_ALIASES[name] ?? name;
- }
- const PASSIVE_EVENTS = ["touchstart", "touchmove"];
- function is_passive_event(name) {
- return PASSIVE_EVENTS.includes(name);
- }
- function autofocus(dom, value) {
- if (value) {
- const body = document.body;
- dom.autofocus = true;
- queue_micro_task(() => {
- if (document.activeElement === body) {
- dom.focus();
- }
- });
- }
- }
- function without_reactive_context(fn) {
- var previous_reaction = active_reaction;
- var previous_effect = active_effect;
- set_active_reaction(null);
- set_active_effect(null);
- try {
- return fn();
- } finally {
- set_active_reaction(previous_reaction);
- set_active_effect(previous_effect);
- }
- }
- const all_registered_events = /* @__PURE__ */ new Set();
- const root_event_handles = /* @__PURE__ */ new Set();
- function create_event(event_name, dom, handler, options = {}) {
- function target_handler(event) {
- if (!options.capture) {
- handle_event_propagation.call(dom, event);
- }
- if (!event.cancelBubble) {
- return without_reactive_context(() => {
- return handler == null ? void 0 : handler.call(this, event);
- });
- }
- }
- if (event_name.startsWith("pointer") || event_name.startsWith("touch") || event_name === "wheel") {
- queue_micro_task(() => {
- dom.addEventListener(event_name, target_handler, options);
- });
- } else {
- dom.addEventListener(event_name, target_handler, options);
- }
- return target_handler;
- }
- function delegate(events) {
- for (var i2 = 0; i2 < events.length; i2++) {
- all_registered_events.add(events[i2]);
- }
- for (var fn of root_event_handles) {
- fn(events);
- }
- }
- function handle_event_propagation(event) {
- var _a2;
- var handler_element = this;
- var owner_document = (
- /** @type {Node} */
- handler_element.ownerDocument
- );
- var event_name = event.type;
- var path = ((_a2 = event.composedPath) == null ? void 0 : _a2.call(event)) || [];
- var current_target = (
- /** @type {null | Element} */
- path[0] || event.target
- );
- var path_idx = 0;
- var handled_at = event.__root;
- if (handled_at) {
- var at_idx = path.indexOf(handled_at);
- if (at_idx !== -1 && (handler_element === document || handler_element === /** @type {any} */
- window)) {
- event.__root = handler_element;
- return;
- }
- var handler_idx = path.indexOf(handler_element);
- if (handler_idx === -1) {
- return;
- }
- if (at_idx <= handler_idx) {
- path_idx = at_idx;
- }
- }
- current_target = /** @type {Element} */
- path[path_idx] || event.target;
- if (current_target === handler_element) return;
- define_property(event, "currentTarget", {
- configurable: true,
- get() {
- return current_target || owner_document;
- }
- });
- var previous_reaction = active_reaction;
- var previous_effect = active_effect;
- set_active_reaction(null);
- set_active_effect(null);
- try {
- var throw_error;
- var other_errors = [];
- while (current_target !== null) {
- var parent_element = current_target.assignedSlot || current_target.parentNode || /** @type {any} */
- current_target.host || null;
- try {
- var delegated = current_target["__" + event_name];
- if (delegated != null && (!/** @type {any} */
- current_target.disabled || // DOM could've been updated already by the time this is reached, so we check this as well
- // -> the target could not have been disabled because it emits the event in the first place
- event.target === current_target)) {
- if (is_array(delegated)) {
- var [fn, ...data] = delegated;
- fn.apply(current_target, [event, ...data]);
- } else {
- delegated.call(current_target, event);
- }
- }
- } catch (error) {
- if (throw_error) {
- other_errors.push(error);
- } else {
- throw_error = error;
- }
- }
- if (event.cancelBubble || parent_element === handler_element || parent_element === null) {
- break;
- }
- current_target = parent_element;
- }
- if (throw_error) {
- for (let error of other_errors) {
- queueMicrotask(() => {
- throw error;
- });
- }
- throw throw_error;
- }
- } finally {
- event.__root = handler_element;
- delete event.currentTarget;
- set_active_reaction(previous_reaction);
- set_active_effect(previous_effect);
- }
- }
- function create_fragment_from_html(html) {
- var elem = document.createElement("template");
- elem.innerHTML = html.replaceAll("<!>", "<!---->");
- return elem.content;
- }
- function assign_nodes(start, end) {
- var effect2 = (
- /** @type {Effect} */
- active_effect
- );
- if (effect2.nodes_start === null) {
- effect2.nodes_start = start;
- effect2.nodes_end = end;
- }
- }
- // @__NO_SIDE_EFFECTS__
- function from_html(content, flags) {
- var is_fragment = (flags & TEMPLATE_FRAGMENT) !== 0;
- var use_import_node = (flags & TEMPLATE_USE_IMPORT_NODE) !== 0;
- var node;
- var has_start = !content.startsWith("<!>");
- return () => {
- if (node === void 0) {
- node = create_fragment_from_html(has_start ? content : "<!>" + content);
- if (!is_fragment) node = /** @type {Node} */
- /* @__PURE__ */ get_first_child(node);
- }
- var clone = (
- /** @type {TemplateNode} */
- use_import_node || is_firefox ? document.importNode(node, true) : node.cloneNode(true)
- );
- if (is_fragment) {
- var start = (
- /** @type {TemplateNode} */
- /* @__PURE__ */ get_first_child(clone)
- );
- var end = (
- /** @type {TemplateNode} */
- clone.lastChild
- );
- assign_nodes(start, end);
- } else {
- assign_nodes(clone, clone);
- }
- return clone;
- };
- }
- // @__NO_SIDE_EFFECTS__
- function from_namespace(content, flags, ns = "svg") {
- var has_start = !content.startsWith("<!>");
- var wrapped = `<${ns}>${has_start ? content : "<!>" + content}</${ns}>`;
- var node;
- return () => {
- if (!node) {
- var fragment = (
- /** @type {DocumentFragment} */
- create_fragment_from_html(wrapped)
- );
- var root2 = (
- /** @type {Element} */
- /* @__PURE__ */ get_first_child(fragment)
- );
- {
- node = /** @type {Element} */
- /* @__PURE__ */ get_first_child(root2);
- }
- }
- var clone = (
- /** @type {TemplateNode} */
- node.cloneNode(true)
- );
- {
- assign_nodes(clone, clone);
- }
- return clone;
- };
- }
- // @__NO_SIDE_EFFECTS__
- function from_svg(content, flags) {
- return /* @__PURE__ */ from_namespace(content, flags, "svg");
- }
- function text(value = "") {
- {
- var t = create_text(value + "");
- assign_nodes(t, t);
- return t;
- }
- }
- function comment() {
- var frag = document.createDocumentFragment();
- var start = document.createComment("");
- var anchor = create_text();
- frag.append(start, anchor);
- assign_nodes(start, anchor);
- return frag;
- }
- function append(anchor, dom) {
- if (anchor === null) {
- return;
- }
- anchor.before(
- /** @type {Node} */
- dom
- );
- }
- function set_text(text2, value) {
- var str = value == null ? "" : typeof value === "object" ? value + "" : value;
- if (str !== (text2.__t ?? (text2.__t = text2.nodeValue))) {
- text2.__t = str;
- text2.nodeValue = str + "";
- }
- }
- function mount(component, options) {
- return _mount(component, options);
- }
- const document_listeners = /* @__PURE__ */ new Map();
- function _mount(Component, { target, anchor, props = {}, events, context, intro = true }) {
- init_operations();
- var registered_events = /* @__PURE__ */ new Set();
- var event_handle = (events2) => {
- for (var i2 = 0; i2 < events2.length; i2++) {
- var event_name = events2[i2];
- if (registered_events.has(event_name)) continue;
- registered_events.add(event_name);
- var passive = is_passive_event(event_name);
- target.addEventListener(event_name, handle_event_propagation, { passive });
- var n2 = document_listeners.get(event_name);
- if (n2 === void 0) {
- document.addEventListener(event_name, handle_event_propagation, { passive });
- document_listeners.set(event_name, 1);
- } else {
- document_listeners.set(event_name, n2 + 1);
- }
- }
- };
- event_handle(array_from(all_registered_events));
- root_event_handles.add(event_handle);
- var component = void 0;
- var unmount = component_root(() => {
- var anchor_node = anchor ?? target.appendChild(create_text());
- branch(() => {
- if (context) {
- push({});
- var ctx = (
- /** @type {ComponentContext} */
- component_context
- );
- ctx.c = context;
- }
- if (events) {
- props.$$events = events;
- }
- component = Component(anchor_node, props) || {};
- if (context) {
- pop();
- }
- });
- return () => {
- var _a2;
- for (var event_name of registered_events) {
- target.removeEventListener(event_name, handle_event_propagation);
- var n2 = (
- /** @type {number} */
- document_listeners.get(event_name)
- );
- if (--n2 === 0) {
- document.removeEventListener(event_name, handle_event_propagation);
- document_listeners.delete(event_name);
- } else {
- document_listeners.set(event_name, n2);
- }
- }
- root_event_handles.delete(event_handle);
- if (anchor_node !== anchor) {
- (_a2 = anchor_node.parentNode) == null ? void 0 : _a2.removeChild(anchor_node);
- }
- };
- });
- mounted_components.set(component, unmount);
- return component;
- }
- let mounted_components = /* @__PURE__ */ new WeakMap();
- function if_block(node, fn, [root_index, hydrate_index] = [0, 0]) {
- var anchor = node;
- var consequent_effect = null;
- var alternate_effect = null;
- var condition = UNINITIALIZED;
- var flags = root_index > 0 ? EFFECT_TRANSPARENT : 0;
- var has_branch = false;
- const set_branch = (fn2, flag = true) => {
- has_branch = true;
- update_branch(flag, fn2);
- };
- const update_branch = (new_condition, fn2) => {
- if (condition === (condition = new_condition)) return;
- if (condition) {
- if (consequent_effect) {
- resume_effect(consequent_effect);
- } else if (fn2) {
- consequent_effect = branch(() => fn2(anchor));
- }
- if (alternate_effect) {
- pause_effect(alternate_effect, () => {
- alternate_effect = null;
- });
- }
- } else {
- if (alternate_effect) {
- resume_effect(alternate_effect);
- } else if (fn2) {
- alternate_effect = branch(() => fn2(anchor, [root_index + 1, hydrate_index]));
- }
- if (consequent_effect) {
- pause_effect(consequent_effect, () => {
- consequent_effect = null;
- });
- }
- }
- };
- block(() => {
- has_branch = false;
- fn(set_branch);
- if (!has_branch) {
- update_branch(null, null);
- }
- }, flags);
- }
- function snippet(node, get_snippet, ...args) {
- var anchor = node;
- var snippet2 = noop;
- var snippet_effect;
- block(() => {
- if (snippet2 === (snippet2 = get_snippet())) return;
- if (snippet_effect) {
- destroy_effect(snippet_effect);
- snippet_effect = null;
- }
- snippet_effect = branch(() => (
- /** @type {SnippetFn} */
- snippet2(anchor, ...args)
- ));
- }, EFFECT_TRANSPARENT);
- }
- function attach(node, get_fn) {
- var fn = void 0;
- var e2;
- block(() => {
- if (fn !== (fn = get_fn())) {
- if (e2) {
- destroy_effect(e2);
- e2 = null;
- }
- if (fn) {
- e2 = branch(() => {
- effect(() => (
- /** @type {(node: Element) => void} */
- fn(node)
- ));
- });
- }
- }
- });
- }
- function r(e2) {
- var t, f2, n2 = "";
- if ("string" == typeof e2 || "number" == typeof e2) n2 += e2;
- else if ("object" == typeof e2) if (Array.isArray(e2)) {
- var o2 = e2.length;
- for (t = 0; t < o2; t++) e2[t] && (f2 = r(e2[t])) && (n2 && (n2 += " "), n2 += f2);
- } else for (f2 in e2) e2[f2] && (n2 && (n2 += " "), n2 += f2);
- return n2;
- }
- function clsx$1() {
- for (var e2, t, f2 = 0, n2 = "", o2 = arguments.length; f2 < o2; f2++) (e2 = arguments[f2]) && (t = r(e2)) && (n2 && (n2 += " "), n2 += t);
- return n2;
- }
- function clsx(value) {
- if (typeof value === "object") {
- return clsx$1(value);
- } else {
- return value ?? "";
- }
- }
- const whitespace = [..." \n\r\f \v\uFEFF"];
- function to_class(value, hash, directives) {
- var classname = value == null ? "" : "" + value;
- if (hash) {
- classname = classname ? classname + " " + hash : hash;
- }
- if (directives) {
- for (var key in directives) {
- if (directives[key]) {
- classname = classname ? classname + " " + key : key;
- } else if (classname.length) {
- var len = key.length;
- var a2 = 0;
- while ((a2 = classname.indexOf(key, a2)) >= 0) {
- var b2 = a2 + len;
- if ((a2 === 0 || whitespace.includes(classname[a2 - 1])) && (b2 === classname.length || whitespace.includes(classname[b2]))) {
- classname = (a2 === 0 ? "" : classname.substring(0, a2)) + classname.substring(b2 + 1);
- } else {
- a2 = b2;
- }
- }
- }
- }
- }
- return classname === "" ? null : classname;
- }
- function append_styles(styles, important = false) {
- var separator = important ? " !important;" : ";";
- var css = "";
- for (var key in styles) {
- var value = styles[key];
- if (value != null && value !== "") {
- css += " " + key + ": " + value + separator;
- }
- }
- return css;
- }
- function to_css_name(name) {
- if (name[0] !== "-" || name[1] !== "-") {
- return name.toLowerCase();
- }
- return name;
- }
- function to_style(value, styles) {
- if (styles) {
- var new_style = "";
- var normal_styles;
- var important_styles;
- if (Array.isArray(styles)) {
- normal_styles = styles[0];
- important_styles = styles[1];
- } else {
- normal_styles = styles;
- }
- if (value) {
- value = String(value).replaceAll(/\s*\/\*.*?\*\/\s*/g, "").trim();
- var in_str = false;
- var in_apo = 0;
- var in_comment = false;
- var reserved_names = [];
- if (normal_styles) {
- reserved_names.push(...Object.keys(normal_styles).map(to_css_name));
- }
- if (important_styles) {
- reserved_names.push(...Object.keys(important_styles).map(to_css_name));
- }
- var start_index = 0;
- var name_index = -1;
- const len = value.length;
- for (var i2 = 0; i2 < len; i2++) {
- var c2 = value[i2];
- if (in_comment) {
- if (c2 === "/" && value[i2 - 1] === "*") {
- in_comment = false;
- }
- } else if (in_str) {
- if (in_str === c2) {
- in_str = false;
- }
- } else if (c2 === "/" && value[i2 + 1] === "*") {
- in_comment = true;
- } else if (c2 === '"' || c2 === "'") {
- in_str = c2;
- } else if (c2 === "(") {
- in_apo++;
- } else if (c2 === ")") {
- in_apo--;
- }
- if (!in_comment && in_str === false && in_apo === 0) {
- if (c2 === ":" && name_index === -1) {
- name_index = i2;
- } else if (c2 === ";" || i2 === len - 1) {
- if (name_index !== -1) {
- var name = to_css_name(value.substring(start_index, name_index).trim());
- if (!reserved_names.includes(name)) {
- if (c2 !== ";") {
- i2++;
- }
- var property = value.substring(start_index, i2).trim();
- new_style += " " + property + ";";
- }
- }
- start_index = i2 + 1;
- name_index = -1;
- }
- }
- }
- }
- if (normal_styles) {
- new_style += append_styles(normal_styles);
- }
- if (important_styles) {
- new_style += append_styles(important_styles, true);
- }
- new_style = new_style.trim();
- return new_style === "" ? null : new_style;
- }
- return value == null ? null : String(value);
- }
- function set_class(dom, is_html, value, hash, prev_classes, next_classes) {
- var prev = dom.__className;
- if (prev !== value || prev === void 0) {
- var next_class_name = to_class(value, hash, next_classes);
- {
- if (next_class_name == null) {
- dom.removeAttribute("class");
- } else if (is_html) {
- dom.className = next_class_name;
- } else {
- dom.setAttribute("class", next_class_name);
- }
- }
- dom.__className = value;
- } else if (next_classes && prev_classes !== next_classes) {
- for (var key in next_classes) {
- var is_present = !!next_classes[key];
- if (prev_classes == null || is_present !== !!prev_classes[key]) {
- dom.classList.toggle(key, is_present);
- }
- }
- }
- return next_classes;
- }
- function update_styles(dom, prev = {}, next, priority) {
- for (var key in next) {
- var value = next[key];
- if (prev[key] !== value) {
- if (next[key] == null) {
- dom.style.removeProperty(key);
- } else {
- dom.style.setProperty(key, value, priority);
- }
- }
- }
- }
- function set_style(dom, value, prev_styles, next_styles) {
- var prev = dom.__style;
- if (prev !== value) {
- var next_style_attr = to_style(value, next_styles);
- {
- if (next_style_attr == null) {
- dom.removeAttribute("style");
- } else {
- dom.style.cssText = next_style_attr;
- }
- }
- dom.__style = value;
- } else if (next_styles) {
- if (Array.isArray(next_styles)) {
- update_styles(dom, prev_styles == null ? void 0 : prev_styles[0], next_styles[0]);
- update_styles(dom, prev_styles == null ? void 0 : prev_styles[1], next_styles[1], "important");
- } else {
- update_styles(dom, prev_styles, next_styles);
- }
- }
- return next_styles;
- }
- function select_option(select, value, mounting) {
- if (select.multiple) {
- if (value == void 0) {
- return;
- }
- if (!is_array(value)) {
- return select_multiple_invalid_value();
- }
- for (var option of select.options) {
- option.selected = value.includes(get_option_value(option));
- }
- return;
- }
- for (option of select.options) {
- var option_value = get_option_value(option);
- if (is(option_value, value)) {
- option.selected = true;
- return;
- }
- }
- if (!mounting || value !== void 0) {
- select.selectedIndex = -1;
- }
- }
- function init_select(select, get_value) {
- let mounting = true;
- effect(() => {
- if (get_value) {
- select_option(select, untrack(get_value), mounting);
- }
- mounting = false;
- var observer = new MutationObserver(() => {
- var value = select.__value;
- select_option(select, value);
- });
- observer.observe(select, {
- // Listen to option element changes
- childList: true,
- subtree: true,
- // because of <optgroup>
- // Listen to option element value attribute changes
- // (doesn't get notified of select value changes,
- // because that property is not reflected as an attribute)
- attributes: true,
- attributeFilter: ["value"]
- });
- return () => {
- observer.disconnect();
- };
- });
- }
- function get_option_value(option) {
- if ("__value" in option) {
- return option.__value;
- } else {
- return option.value;
- }
- }
- const CLASS = Symbol("class");
- const STYLE = Symbol("style");
- const IS_CUSTOM_ELEMENT = Symbol("is custom element");
- const IS_HTML = Symbol("is html");
- function set_selected(element, selected) {
- if (selected) {
- if (!element.hasAttribute("selected")) {
- element.setAttribute("selected", "");
- }
- } else {
- element.removeAttribute("selected");
- }
- }
- function set_attribute(element, attribute, value, skip_warning) {
- var attributes = get_attributes(element);
- if (attributes[attribute] === (attributes[attribute] = value)) return;
- if (attribute === "loading") {
- element[LOADING_ATTR_SYMBOL] = value;
- }
- if (value == null) {
- element.removeAttribute(attribute);
- } else if (typeof value !== "string" && get_setters(element).includes(attribute)) {
- element[attribute] = value;
- } else {
- element.setAttribute(attribute, value);
- }
- }
- function set_attributes(element, prev, next, css_hash, skip_warning = false) {
- var attributes = get_attributes(element);
- var is_custom_element = attributes[IS_CUSTOM_ELEMENT];
- var preserve_attribute_case = !attributes[IS_HTML];
- var current = prev || {};
- var is_option_element = element.tagName === "OPTION";
- for (var key in prev) {
- if (!(key in next)) {
- next[key] = null;
- }
- }
- if (next.class) {
- next.class = clsx(next.class);
- } else if (css_hash || next[CLASS]) {
- next.class = null;
- }
- if (next[STYLE]) {
- next.style ?? (next.style = null);
- }
- var setters = get_setters(element);
- for (const key2 in next) {
- let value = next[key2];
- if (is_option_element && key2 === "value" && value == null) {
- element.value = element.__value = "";
- current[key2] = value;
- continue;
- }
- if (key2 === "class") {
- var is_html = element.namespaceURI === "http://www.w3.org/1999/xhtml";
- set_class(element, is_html, value, css_hash, prev == null ? void 0 : prev[CLASS], next[CLASS]);
- current[key2] = value;
- current[CLASS] = next[CLASS];
- continue;
- }
- if (key2 === "style") {
- set_style(element, value, prev == null ? void 0 : prev[STYLE], next[STYLE]);
- current[key2] = value;
- current[STYLE] = next[STYLE];
- continue;
- }
- var prev_value = current[key2];
- if (value === prev_value && !(value === void 0 && element.hasAttribute(key2))) {
- continue;
- }
- current[key2] = value;
- var prefix = key2[0] + key2[1];
- if (prefix === "$$") continue;
- if (prefix === "on") {
- const opts = {};
- const event_handle_key = "$$" + key2;
- let event_name = key2.slice(2);
- var delegated = is_delegated(event_name);
- if (is_capture_event(event_name)) {
- event_name = event_name.slice(0, -7);
- opts.capture = true;
- }
- if (!delegated && prev_value) {
- if (value != null) continue;
- element.removeEventListener(event_name, current[event_handle_key], opts);
- current[event_handle_key] = null;
- }
- if (value != null) {
- if (!delegated) {
- let handle = function(evt) {
- current[key2].call(this, evt);
- };
- current[event_handle_key] = create_event(event_name, element, handle, opts);
- } else {
- element[`__${event_name}`] = value;
- delegate([event_name]);
- }
- } else if (delegated) {
- element[`__${event_name}`] = void 0;
- }
- } else if (key2 === "style") {
- set_attribute(element, key2, value);
- } else if (key2 === "autofocus") {
- autofocus(
- /** @type {HTMLElement} */
- element,
- Boolean(value)
- );
- } else if (!is_custom_element && (key2 === "__value" || key2 === "value" && value != null)) {
- element.value = element.__value = value;
- } else if (key2 === "selected" && is_option_element) {
- set_selected(
- /** @type {HTMLOptionElement} */
- element,
- value
- );
- } else {
- var name = key2;
- if (!preserve_attribute_case) {
- name = normalize_attribute(name);
- }
- var is_default = name === "defaultValue" || name === "defaultChecked";
- if (value == null && !is_custom_element && !is_default) {
- attributes[key2] = null;
- if (name === "value" || name === "checked") {
- let input = (
- /** @type {HTMLInputElement} */
- element
- );
- const use_default = prev === void 0;
- if (name === "value") {
- let previous = input.defaultValue;
- input.removeAttribute(name);
- input.defaultValue = previous;
- input.value = input.__value = use_default ? previous : null;
- } else {
- let previous = input.defaultChecked;
- input.removeAttribute(name);
- input.defaultChecked = previous;
- input.checked = use_default ? previous : false;
- }
- } else {
- element.removeAttribute(key2);
- }
- } else if (is_default || setters.includes(name) && (is_custom_element || typeof value !== "string")) {
- element[name] = value;
- } else if (typeof value !== "function") {
- set_attribute(element, name, value);
- }
- }
- }
- return current;
- }
- function attribute_effect(element, fn, thunks = [], css_hash, skip_warning = false, d2 = derived) {
- const deriveds = thunks.map(d2);
- var prev = void 0;
- var effects = {};
- var is_select = element.nodeName === "SELECT";
- var inited = false;
- block(() => {
- var next = fn(...deriveds.map(get));
- var current = set_attributes(element, prev, next, css_hash, skip_warning);
- if (inited && is_select && "value" in next) {
- select_option(
- /** @type {HTMLSelectElement} */
- element,
- next.value,
- false
- );
- }
- for (let symbol of Object.getOwnPropertySymbols(effects)) {
- if (!next[symbol]) destroy_effect(effects[symbol]);
- }
- for (let symbol of Object.getOwnPropertySymbols(next)) {
- var n2 = next[symbol];
- if (symbol.description === ATTACHMENT_KEY && (!prev || n2 !== prev[symbol])) {
- if (effects[symbol]) destroy_effect(effects[symbol]);
- effects[symbol] = branch(() => attach(element, () => n2));
- }
- current[symbol] = n2;
- }
- prev = current;
- });
- if (is_select) {
- init_select(
- /** @type {HTMLSelectElement} */
- element,
- () => (
- /** @type {Record<string | symbol, any>} */
- prev.value
- )
- );
- }
- inited = true;
- }
- function get_attributes(element) {
- return (
- /** @type {Record<string | symbol, unknown>} **/
- // @ts-expect-error
- element.__attributes ?? (element.__attributes = {
- [IS_CUSTOM_ELEMENT]: element.nodeName.includes("-"),
- [IS_HTML]: element.namespaceURI === NAMESPACE_HTML
- })
- );
- }
- var setters_cache = /* @__PURE__ */ new Map();
- function get_setters(element) {
- var setters = setters_cache.get(element.nodeName);
- if (setters) return setters;
- setters_cache.set(element.nodeName, setters = []);
- var descriptors;
- var proto = element;
- var element_proto = Element.prototype;
- while (element_proto !== proto) {
- descriptors = get_descriptors(proto);
- for (var key in descriptors) {
- if (descriptors[key].set) {
- setters.push(key);
- }
- }
- proto = get_prototype_of(proto);
- }
- return setters;
- }
- function init(immutable = false) {
- const context = (
- /** @type {ComponentContextLegacy} */
- component_context
- );
- const callbacks = context.l.u;
- if (!callbacks) return;
- let props = () => deep_read_state(context.s);
- if (immutable) {
- let version = 0;
- let prev = (
- /** @type {Record<string, any>} */
- {}
- );
- const d2 = /* @__PURE__ */ derived(() => {
- let changed = false;
- const props2 = context.s;
- for (const key in props2) {
- if (props2[key] !== prev[key]) {
- prev[key] = props2[key];
- changed = true;
- }
- }
- if (changed) version++;
- return version;
- });
- props = () => get(d2);
- }
- if (callbacks.b.length) {
- user_pre_effect(() => {
- observe_all(context, props);
- run_all(callbacks.b);
- });
- }
- user_effect(() => {
- const fns = untrack(() => callbacks.m.map(run));
- return () => {
- for (const fn of fns) {
- if (typeof fn === "function") {
- fn();
- }
- }
- };
- });
- if (callbacks.a.length) {
- user_effect(() => {
- observe_all(context, props);
- run_all(callbacks.a);
- });
- }
- }
- function observe_all(context, props) {
- if (context.l.s) {
- for (const signal of context.l.s) get(signal);
- }
- props();
- }
- const rest_props_handler = {
- get(target, key) {
- if (target.exclude.includes(key)) return;
- return target.props[key];
- },
- set(target, key) {
- return false;
- },
- getOwnPropertyDescriptor(target, key) {
- if (target.exclude.includes(key)) return;
- if (key in target.props) {
- return {
- enumerable: true,
- configurable: true,
- value: target.props[key]
- };
- }
- },
- has(target, key) {
- if (target.exclude.includes(key)) return false;
- return key in target.props;
- },
- ownKeys(target) {
- return Reflect.ownKeys(target.props).filter((key) => !target.exclude.includes(key));
- }
- };
- // @__NO_SIDE_EFFECTS__
- function rest_props(props, exclude, name) {
- return new Proxy(
- { props, exclude },
- rest_props_handler
- );
- }
- function prop(props, key, flags, fallback) {
- var prop_value;
- {
- prop_value = /** @type {V} */
- props[key];
- }
- var fallback_value = (
- /** @type {V} */
- fallback
- );
- var fallback_dirty = true;
- var get_fallback = () => {
- if (fallback_dirty) {
- fallback_dirty = false;
- {
- fallback_value = /** @type {V} */
- fallback;
- }
- }
- return fallback_value;
- };
- if (prop_value === void 0 && fallback !== void 0) {
- prop_value = get_fallback();
- }
- var getter;
- {
- getter = () => {
- var value = (
- /** @type {V} */
- props[key]
- );
- if (value === void 0) return get_fallback();
- fallback_dirty = true;
- return value;
- };
- }
- {
- return getter;
- }
- }
- const PUBLIC_VERSION = "5";
- if (typeof window !== "undefined") {
- ((_a = window.__svelte ?? (window.__svelte = {})).v ?? (_a.v = /* @__PURE__ */ new Set())).add(PUBLIC_VERSION);
- }
- enable_legacy_mode_flag();
- var root = /* @__PURE__ */ from_html(`<div><!></div>`);
- function ButtonGroup($$anchor, $$props) {
- let props = /* @__PURE__ */ rest_props($$props, [
- "$$slots",
- "$$events",
- "$$legacy",
- "children"
- ]);
- var div = root();
- attribute_effect(div, () => ({ ...props }), void 0, "svelte-4mbyk0");
- var node = child(div);
- snippet(node, () => $$props.children);
- append($$anchor, div);
- }
- const mouseClickEvents = ["mousedown", "mouseup", "click"];
- function simulateMouseClickReact(element) {
- mouseClickEvents.forEach(
- (mouseEventType) => element.dispatchEvent(
- new MouseEvent(mouseEventType, {
- view: _unsafeWindow,
- bubbles: true,
- cancelable: true,
- buttons: 1
- })
- )
- );
- }
- const loaderIcon = ($$anchor) => {
- var svg = root_1$3();
- append($$anchor, svg);
- };
- var root_1$3 = /* @__PURE__ */ from_svg(`<svg class="animate-spin" xmlns="http://www.w3.org/2000/svg" width="1rem" height="1rem" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 2v4m4.2 1.8l2.9-2.9M18 12h4m-5.8 4.2l2.9 2.9M12 18v4m-7.1-2.9l2.9-2.9M2 12h4M4.9 4.9l2.9 2.9"></path></svg>`);
- var root_2 = /* @__PURE__ */ from_html(`<a><!></a>`);
- var root_3 = /* @__PURE__ */ from_html(`<button><!> <!></button>`);
- function Button($$anchor, $$props) {
- push($$props, true);
- let variant = prop($$props, "variant", 3, "purple"), type = prop($$props, "type", 3, "button"), restProps = /* @__PURE__ */ rest_props($$props, [
- "$$slots",
- "$$events",
- "$$legacy",
- "onclick",
- "children",
- "variant",
- "type",
- "href"
- ]);
- const variants = {
- purple: "--bg: #6c5ce7; --shadow: #a29bfe",
- green: "--bg: #1ba13e; --shadow: #42de6e",
- orange: "--bg: #ffa116; --shadow: #fedd9b"
- };
- let loading = /* @__PURE__ */ state(false);
- async function handleOnClick(e$1) {
- if (!$$props.onclick) return;
- const returnValue = $$props.onclick(e$1);
- if (e(returnValue)) {
- set(loading, true);
- await returnValue;
- set(loading, false);
- }
- }
- var fragment = comment();
- var node = first_child(fragment);
- {
- var consequent = ($$anchor2) => {
- var a2 = root_2();
- attribute_effect(
- a2,
- () => ({
- style: variants[variant()],
- href: $$props.href,
- target: "_blank",
- ...restProps
- }),
- void 0,
- "svelte-ll0ynk"
- );
- var node_1 = child(a2);
- snippet(node_1, () => $$props.children ?? noop);
- append($$anchor2, a2);
- };
- var alternate = ($$anchor2) => {
- var button = root_3();
- attribute_effect(
- button,
- () => ({
- style: variants[variant()],
- type: type(),
- disabled: get(loading),
- onclick: handleOnClick,
- ...restProps
- }),
- void 0,
- "svelte-ll0ynk"
- );
- var node_2 = child(button);
- {
- var consequent_1 = ($$anchor3) => {
- loaderIcon($$anchor3);
- };
- if_block(node_2, ($$render) => {
- if (get(loading)) $$render(consequent_1);
- });
- }
- var node_3 = sibling(node_2, 2);
- snippet(node_3, () => $$props.children ?? noop);
- append($$anchor2, button);
- };
- if_block(node, ($$render) => {
- if ($$props.href) $$render(consequent);
- else $$render(alternate, false);
- });
- }
- append($$anchor, fragment);
- pop();
- }
- async function copyText(text2) {
- try {
- await navigator.clipboard.writeText(text2);
- } catch (err) {
- if (err instanceof Error) {
- console.error(err);
- }
- throw err;
- }
- }
- const getTitle = async () => {
- const descriptionTabButton = (await findElement("#description_tab")).closest(".flexlayout__tab_button");
- if (!(descriptionTabButton == null ? void 0 : descriptionTabButton.classList.contains(".flexlayout__tab_button--selected"))) {
- simulateMouseClickReact(descriptionTabButton);
- }
- return (await findElement(".text-title-large")).textContent ?? "";
- };
- function Copy_title($$anchor, $$props) {
- push($$props, false);
- async function copyTitle() {
- copyText(await getTitle());
- toaster.success(globalState.site === "cn" ? "已复制题目标题到剪贴板" : "Problem title copied to clipboard");
- }
- init();
- Button($$anchor, {
- onclick: copyTitle,
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text();
- template_effect(() => set_text(text$1, globalState.site === "cn" ? "复制标题" : "Copy Title"));
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- var turndownPluginGfm_cjs = {};
- var hasRequiredTurndownPluginGfm_cjs;
- function requireTurndownPluginGfm_cjs() {
- if (hasRequiredTurndownPluginGfm_cjs) return turndownPluginGfm_cjs;
- hasRequiredTurndownPluginGfm_cjs = 1;
- Object.defineProperty(turndownPluginGfm_cjs, "__esModule", { value: true });
- var highlightRegExp = /highlight-(?:text|source)-([a-z0-9]+)/;
- function highlightedCodeBlock(turndownService) {
- turndownService.addRule("highlightedCodeBlock", {
- filter: function(node) {
- var firstChild = node.firstChild;
- return node.nodeName === "DIV" && highlightRegExp.test(node.className) && firstChild && firstChild.nodeName === "PRE";
- },
- replacement: function(content, node, options) {
- var className = node.className || "";
- var language = (className.match(highlightRegExp) || [null, ""])[1];
- return "\n\n" + options.fence + language + "\n" + node.firstChild.textContent + "\n" + options.fence + "\n\n";
- }
- });
- }
- function strikethrough(turndownService) {
- turndownService.addRule("strikethrough", {
- filter: ["del", "s", "strike"],
- replacement: function(content) {
- return "~~" + content + "~~";
- }
- });
- }
- var indexOf = Array.prototype.indexOf;
- var every = Array.prototype.every;
- var rules = {};
- var alignMap = { left: ":---", right: "---:", center: ":---:" };
- let isCodeBlock_ = null;
- let options_ = null;
- const tableShouldBeSkippedCache_ = /* @__PURE__ */ new WeakMap();
- function getAlignment(node) {
- return node ? (node.getAttribute("align") || node.style.textAlign || "").toLowerCase() : "";
- }
- function getBorder(alignment) {
- return alignment ? alignMap[alignment] : "---";
- }
- function getColumnAlignment(table, columnIndex) {
- var votes = {
- left: 0,
- right: 0,
- center: 0,
- "": 0
- };
- var align = "";
- for (var i2 = 0; i2 < table.rows.length; ++i2) {
- var row = table.rows[i2];
- if (columnIndex < row.childNodes.length) {
- var cellAlignment = getAlignment(row.childNodes[columnIndex]);
- ++votes[cellAlignment];
- if (votes[cellAlignment] > votes[align]) {
- align = cellAlignment;
- }
- }
- }
- return align;
- }
- rules.tableCell = {
- filter: ["th", "td"],
- replacement: function(content, node) {
- if (tableShouldBeSkipped(nodeParentTable(node))) return content;
- return cell(content, node);
- }
- };
- rules.tableRow = {
- filter: "tr",
- replacement: function(content, node) {
- const parentTable = nodeParentTable(node);
- if (tableShouldBeSkipped(parentTable)) return content;
- var borderCells = "";
- if (isHeadingRow(node)) {
- const colCount = tableColCount(parentTable);
- for (var i2 = 0; i2 < colCount; i2++) {
- const childNode = i2 < node.childNodes.length ? node.childNodes[i2] : null;
- var border = getBorder(getColumnAlignment(parentTable, i2));
- borderCells += cell(border, childNode, i2);
- }
- }
- return "\n" + content + (borderCells ? "\n" + borderCells : "");
- }
- };
- rules.table = {
- filter: function(node, options) {
- return node.nodeName === "TABLE";
- },
- replacement: function(content, node) {
- if (tableShouldBeHtml(node, options_)) {
- let html = node.outerHTML;
- let divParent = nodeParentDiv(node);
- if (divParent === null || !divParent.classList.contains("joplin-table-wrapper")) {
- return `
- <div class="joplin-table-wrapper">${html}</div>
- `;
- } else {
- return html;
- }
- } else {
- if (tableShouldBeSkipped(node)) return content;
- content = content.replace(/\n+/g, "\n");
- var secondLine = content.trim().split("\n");
- if (secondLine.length >= 2) secondLine = secondLine[1];
- var secondLineIsDivider = /\| :?---/.test(secondLine);
- var columnCount = tableColCount(node);
- var emptyHeader = "";
- if (columnCount && !secondLineIsDivider) {
- emptyHeader = "|" + " |".repeat(columnCount) + "\n|";
- for (var columnIndex = 0; columnIndex < columnCount; ++columnIndex) {
- emptyHeader += " " + getBorder(getColumnAlignment(node, columnIndex)) + " |";
- }
- }
- const captionContent = node.caption ? node.caption.textContent || "" : "";
- const caption = captionContent ? `${captionContent}
- ` : "";
- const tableContent = `${emptyHeader}${content}`.trimStart();
- return `
- ${caption}${tableContent}
- `;
- }
- }
- };
- rules.tableCaption = {
- filter: ["caption"],
- replacement: () => ""
- };
- rules.tableColgroup = {
- filter: ["colgroup", "col"],
- replacement: () => ""
- };
- rules.tableSection = {
- filter: ["thead", "tbody", "tfoot"],
- replacement: function(content) {
- return content;
- }
- };
- function isHeadingRow(tr) {
- var parentNode = tr.parentNode;
- return parentNode.nodeName === "THEAD" || parentNode.firstChild === tr && (parentNode.nodeName === "TABLE" || isFirstTbody(parentNode)) && every.call(tr.childNodes, function(n2) {
- return n2.nodeName === "TH";
- });
- }
- function isFirstTbody(element) {
- var previousSibling = element.previousSibling;
- return element.nodeName === "TBODY" && (!previousSibling || previousSibling.nodeName === "THEAD" && /^\s*$/i.test(previousSibling.textContent));
- }
- function cell(content, node = null, index = null) {
- if (index === null) index = indexOf.call(node.parentNode.childNodes, node);
- var prefix = " ";
- if (index === 0) prefix = "| ";
- let filteredContent = content.trim().replace(/\n\r/g, "<br>").replace(/\n/g, "<br>");
- filteredContent = filteredContent.replace(/\|+/g, "\\|");
- while (filteredContent.length < 3) filteredContent += " ";
- if (node) filteredContent = handleColSpan(filteredContent, node, " ");
- return prefix + filteredContent + " |";
- }
- function nodeContainsTable(node) {
- if (!node.childNodes) return false;
- for (let i2 = 0; i2 < node.childNodes.length; i2++) {
- const child2 = node.childNodes[i2];
- if (child2.nodeName === "TABLE") return true;
- if (nodeContainsTable(child2)) return true;
- }
- return false;
- }
- const nodeContains = (node, types) => {
- if (!node.childNodes) return false;
- for (let i2 = 0; i2 < node.childNodes.length; i2++) {
- const child2 = node.childNodes[i2];
- if (types === "code" && isCodeBlock_ && isCodeBlock_(child2)) return true;
- if (types.includes(child2.nodeName)) return true;
- if (nodeContains(child2, types)) return true;
- }
- return false;
- };
- const tableShouldBeHtml = (tableNode, options) => {
- const possibleTags = [
- "UL",
- "OL",
- "H1",
- "H2",
- "H3",
- "H4",
- "H5",
- "H6",
- "HR",
- "BLOCKQUOTE"
- ];
- if (options.preserveNestedTables) possibleTags.push("TABLE");
- return nodeContains(tableNode, "code") || nodeContains(tableNode, possibleTags);
- };
- function tableShouldBeSkipped(tableNode) {
- const cached = tableShouldBeSkippedCache_.get(tableNode);
- if (cached !== void 0) return cached;
- const result = tableShouldBeSkipped_(tableNode);
- tableShouldBeSkippedCache_.set(tableNode, result);
- return result;
- }
- function tableShouldBeSkipped_(tableNode) {
- if (!tableNode) return true;
- if (!tableNode.rows) return true;
- if (tableNode.rows.length === 1 && tableNode.rows[0].childNodes.length <= 1) return true;
- if (nodeContainsTable(tableNode)) return true;
- return false;
- }
- function nodeParentDiv(node) {
- let parent = node.parentNode;
- while (parent.nodeName !== "DIV") {
- parent = parent.parentNode;
- if (!parent) return null;
- }
- return parent;
- }
- function nodeParentTable(node) {
- let parent = node.parentNode;
- while (parent.nodeName !== "TABLE") {
- parent = parent.parentNode;
- if (!parent) return null;
- }
- return parent;
- }
- function handleColSpan(content, node, emptyChar) {
- const colspan = node.getAttribute("colspan") || 1;
- for (let i2 = 1; i2 < colspan; i2++) {
- content += " | " + emptyChar.repeat(3);
- }
- return content;
- }
- function tableColCount(node) {
- let maxColCount = 0;
- for (let i2 = 0; i2 < node.rows.length; i2++) {
- const row = node.rows[i2];
- const colCount = row.childNodes.length;
- if (colCount > maxColCount) maxColCount = colCount;
- }
- return maxColCount;
- }
- function tables(turndownService) {
- isCodeBlock_ = turndownService.isCodeBlock;
- options_ = turndownService.options;
- turndownService.keep(function(node) {
- if (node.nodeName === "TABLE" && tableShouldBeHtml(node, turndownService.options)) return true;
- return false;
- });
- for (var key in rules) turndownService.addRule(key, rules[key]);
- }
- function taskListItems(turndownService) {
- turndownService.addRule("taskListItems", {
- filter: function(node) {
- return node.type === "checkbox" && node.parentNode.nodeName === "LI";
- },
- replacement: function(content, node) {
- return (node.checked ? "[x]" : "[ ]") + " ";
- }
- });
- }
- function gfm(turndownService) {
- turndownService.use([
- highlightedCodeBlock,
- strikethrough,
- tables,
- taskListItems
- ]);
- }
- turndownPluginGfm_cjs.gfm = gfm;
- turndownPluginGfm_cjs.highlightedCodeBlock = highlightedCodeBlock;
- turndownPluginGfm_cjs.strikethrough = strikethrough;
- turndownPluginGfm_cjs.tables = tables;
- turndownPluginGfm_cjs.taskListItems = taskListItems;
- return turndownPluginGfm_cjs;
- }
- var turndownPluginGfm_cjsExports = requireTurndownPluginGfm_cjs();
- var M = "__monkeyWindow-" + (() => {
- try {
- return new URL((_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('__entry.js', document.baseURI).href)).origin;
- } catch {
- return location.origin;
- }
- })(), y = document[M] ?? window, g = y.GM, v = y.GM_xmlhttpRequest;
- function k(l2) {
- var e2;
- const t = new Headers(), a2 = l2.replace(/\r?\n[\t ]+/g, " ");
- for (const d2 of a2.split(/\r?\n/)) {
- const i2 = d2.split(":"), o2 = (e2 = i2.shift()) == null ? void 0 : e2.trim();
- if (o2) {
- const r2 = i2.join(":").trim();
- try {
- t.append(o2, r2);
- } catch (c2) {
- console.warn(`Response ${c2.message}`);
- }
- }
- }
- return t;
- }
- const H = async (l2, t) => {
- const a2 = v || g.xmlHttpRequest;
- if (typeof a2 != "function")
- throw new DOMException(
- "GM_xmlhttpRequest or GM.xmlHttpRequest is not granted.",
- "NotFoundError"
- );
- const e2 = new Request(l2, t);
- if (e2.signal.aborted)
- throw new DOMException("Network request aborted.", "AbortError");
- const d2 = await e2.blob(), i2 = Object.fromEntries(e2.headers);
- return new Headers(void 0).forEach((o2, r2) => {
- i2[r2] = o2;
- }), new Promise((o2, r2) => {
- let c2 = false;
- const R = new Promise((n2) => {
- const { abort: h } = a2({
- method: e2.method.toUpperCase(),
- url: e2.url || location.href,
- headers: i2,
- data: d2.size ? d2 : void 0,
- redirect: e2.redirect,
- binary: true,
- nocache: e2.cache === "no-store",
- revalidate: e2.cache === "reload",
- timeout: 3e5,
- responseType: a2.RESPONSE_TYPE_STREAM ?? "blob",
- overrideMimeType: e2.headers.get("Content-Type") ?? void 0,
- anonymous: e2.credentials === "omit",
- onload: ({ response: s }) => {
- if (c2) {
- n2(null);
- return;
- }
- n2(s);
- },
- async onreadystatechange({
- readyState: s,
- responseHeaders: p2,
- status: b2,
- statusText: q,
- finalUrl: w2,
- response: E
- }) {
- if (s === XMLHttpRequest.DONE)
- e2.signal.removeEventListener("abort", h);
- else if (s !== XMLHttpRequest.HEADERS_RECEIVED)
- return;
- if (c2) {
- n2(null);
- return;
- }
- const u2 = k(p2), f2 = e2.url !== w2, m2 = new Response(
- E instanceof ReadableStream ? E : await R,
- {
- headers: u2,
- status: b2,
- statusText: q
- }
- );
- Object.defineProperties(m2, {
- url: {
- value: w2
- },
- type: {
- value: "basic"
- },
- ...m2.redirected !== f2 ? {
- redirected: {
- value: f2
- }
- } : {},
- // https://fetch.spec.whatwg.org/#forbidden-response-header-name
- ...u2.has("set-cookie") || u2.has("set-cookie2") ? {
- headers: {
- value: u2
- }
- } : {}
- }), o2(m2), c2 = true;
- },
- onerror: ({ statusText: s, error: p2 }) => {
- r2(
- new TypeError(s || p2 || "Network request failed.")
- ), n2(null);
- },
- ontimeout() {
- r2(new TypeError("Network request timeout.")), n2(null);
- },
- onabort() {
- r2(new DOMException("Network request aborted.", "AbortError")), n2(null);
- }
- });
- e2.signal.addEventListener("abort", h);
- });
- });
- };
- async function compressImage(image) {
- return new Promise((resolve, reject) => {
- new Compressor(image, {
- success: resolve,
- error: reject
- });
- });
- }
- function blobToDataURL(blob) {
- return new Promise((resolve, reject) => {
- const reader = new FileReader();
- reader.onload = () => resolve(reader.result);
- reader.onerror = (error) => reject(error);
- reader.readAsDataURL(blob);
- });
- }
- async function convertSrcToDataURL(src) {
- if (src.startsWith("data:")) {
- return src;
- }
- try {
- const response = await H(src);
- let blob = await response.blob();
- const incompressableTypes = ["image/gif", "image/svg+xml"];
- if (!incompressableTypes.includes(blob.type)) {
- blob = await compressImage(blob);
- }
- const dataURL = await blobToDataURL(blob);
- return dataURL;
- } catch (err) {
- console.error(`Failed to convert image: ${src}`, err);
- throw err;
- }
- }
- const imageCache = /* @__PURE__ */ new Map();
- async function prefetchImages(node) {
- const images = Array.from(node.querySelectorAll("img"));
- const fetchPromises = images.map(async ({ src }) => {
- if (imageCache.has(src)) return;
- const dataURL = await convertSrcToDataURL(src);
- imageCache.set(src, dataURL);
- });
- await Promise.all(fetchPromises);
- }
- function createTurndownService() {
- const turndown2 = new TurndownService({
- emDelimiter: "*",
- bulletListMarker: "-"
- });
- turndown2.addRule("pre", {
- filter: ["pre"],
- replacement: (_content, node) => {
- var _a2;
- return "\n```txt\n" + ((_a2 = node.textContent) == null ? void 0 : _a2.trim()) + "\n```\n";
- }
- });
- turndown2.addRule("superscript", {
- filter: ["sup"],
- replacement: (content) => "^" + content
- });
- turndown2.addRule("paragraph", {
- filter: ["p"],
- replacement: (content) => "\n\n" + content + "\n\n"
- });
- turndown2.addRule("convert-img-src-to-base64", {
- filter: ["img"],
- replacement: (_content, node) => {
- const { src, alt } = node;
- const dataURL = imageCache.get(src);
- if (dataURL) {
- return ``;
- }
- return ``;
- }
- });
- turndown2.use(turndownPluginGfm_cjsExports.tables);
- return turndown2;
- }
- async function htmlToMd(node, {
- turndownService = createTurndownService(),
- convertImage = true
- } = {}) {
- if (convertImage) await prefetchImages(node);
- const md = turndownService.turndown(node);
- if (convertImage) imageCache.clear();
- return md;
- }
- const getDescription = async (convertImage = true) => {
- const el = await findElement("div[data-track-load='description_content']");
- return htmlToMd(el, { convertImage });
- };
- function Copy_description($$anchor, $$props) {
- push($$props, false);
- async function copyDescription() {
- const desc = await getDescription(false);
- copyText(desc);
- toaster.success(globalState.site === "cn" ? "已复制题目描述到剪贴板" : "Problem description copied to clipboard");
- }
- init();
- Button($$anchor, {
- variant: "green",
- onclick: copyDescription,
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text();
- template_effect(() => set_text(text$1, globalState.site === "cn" ? "复制描述" : "Copy Description"));
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- function downloadFile(blob, filename, extension) {
- const url2 = URL.createObjectURL(blob);
- const a2 = document.createElement("a");
- a2.href = url2;
- a2.download = filename + "." + extension;
- document.body.appendChild(a2);
- a2.click();
- document.body.removeChild(a2);
- URL.revokeObjectURL(url2);
- }
- class NotebookBuilder {
- constructor() {
- __privateAdd(this, _cells, []);
- __privateAdd(this, _metadata, {});
- __privateAdd(this, _nbformat, 5);
- __privateAdd(this, _nbformat_minor, 10);
- }
- addMarkdown(content) {
- const md = {
- cell_type: "markdown",
- metadata: {},
- source: content
- };
- __privateGet(this, _cells).push(md);
- return this;
- }
- /** Add a level one heading. There should be only one title in a document. */
- addTitle(title, url2) {
- this.addMarkdown(`# [${title}](${url2})`);
- return this;
- }
- addSection(heading, content) {
- this.addMarkdown(`## ${heading}
- ${content ?? ""}`);
- return this;
- }
- /** Add a horizontal rule (`<hr>` in html) or line that visually separates content */
- addHorizontalRule() {
- this.addMarkdown("---\n\n");
- return this;
- }
- addCode(content) {
- const code = {
- cell_type: "code",
- metadata: {},
- source: content,
- execution_count: null,
- outputs: []
- };
- __privateGet(this, _cells).push(code);
- return this;
- }
- setLanguage(language) {
- __privateGet(this, _metadata).language_info = {
- name: language
- };
- return this;
- }
- build() {
- return {
- metadata: __privateGet(this, _metadata),
- nbformat: __privateGet(this, _nbformat),
- nbformat_minor: __privateGet(this, _nbformat_minor),
- cells: __privateGet(this, _cells)
- };
- }
- download(filename) {
- const notebook = this.build();
- const blob = new Blob([JSON.stringify(notebook)], {
- type: "application/x-ipynb+json"
- });
- downloadFile(blob, filename, "ipynb");
- }
- }
- _cells = new WeakMap();
- _metadata = new WeakMap();
- _nbformat = new WeakMap();
- _nbformat_minor = new WeakMap();
- function Download_as_jupyter($$anchor, $$props) {
- push($$props, false);
- async function saveAsJupyter() {
- var _a2, _b, _c, _d;
- const builder = new NotebookBuilder();
- const title = await getTitle();
- const url2 = window.location.href;
- const urlRegex = /^(https:\/\/(leetcode\.com|leetcode\.cn)\/problems\/[a-zA-Z0-9_-]+)/;
- const urlMatch = url2.match(urlRegex);
- builder.addTitle(title, urlMatch ? urlMatch[0] : url2);
- const description = await getDescription();
- builder.addSection(globalState.site === "cn" ? "题目描述" : "Description", description);
- builder.addHorizontalRule();
- builder.addSection(globalState.site === "cn" ? "解答" : "Solution");
- const code = (_b = (_a2 = problemState.editor) == null ? void 0 : _a2.getModel()) == null ? void 0 : _b.getValue();
- if (!code) {
- toaster.error("Fail to retrieve current code in the editor");
- } else {
- builder.addCode(code);
- }
- const language = ((_d = (_c = problemState.editor) == null ? void 0 : _c.getModel()) == null ? void 0 : _d.getLanguageId()) ?? "python";
- builder.setLanguage(language);
- builder.download(title);
- }
- init();
- Button($$anchor, {
- variant: "orange",
- onclick: () => {
- toaster.promise(saveAsJupyter(), {
- loading: "Scraping problem description and code...",
- success: "Start downloading jupyter notebook...",
- error: "Something went wrong while scraping. See browser console for more detail."
- });
- },
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text();
- template_effect(() => set_text(text$1, globalState.site === "cn" ? "保存为 Jupyter Notebook" : "Save as Jupyter Notebook"));
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- var root_1$2 = /* @__PURE__ */ from_html(`<!> <!> <!>`, 1);
- function DescriptionButttons($$anchor) {
- ButtonGroup($$anchor, {
- children: ($$anchor2, $$slotProps) => {
- var fragment_1 = root_1$2();
- var node = first_child(fragment_1);
- Copy_title(node, {});
- var node_1 = sibling(node, 2);
- Copy_description(node_1, {});
- var node_2 = sibling(node_1, 2);
- Download_as_jupyter(node_2, {});
- append($$anchor2, fragment_1);
- },
- $$slots: { default: true }
- });
- }
- const ratingsTxt = _GM_getResourceText("ratings");
- function getSlug(url2) {
- const pathParts = url2.pathname.split("/");
- if (pathParts.length < 3) return null;
- return pathParts[2];
- }
- function getRating(slugToSearch) {
- const lines = ratingsTxt.split("\n");
- for (const line of lines) {
- const parts = line.split(" ");
- if (parts.length < 2) continue;
- const slug = parts[4];
- if (slug === slugToSearch) {
- return Math.round(parseFloat(parts[0]));
- }
- }
- return null;
- }
- async function getOrCreateRatingElement() {
- const difficultyEl = await findElement(
- "div[class*='text-difficulty']",
- { timeout: 5e3 }
- );
- const id = a(CONFIG.APP_NAME) + "-rating";
- const el = difficultyEl.querySelector(`#${id}`);
- if (el) {
- return el;
- } else {
- const span = document.createElement("span");
- span.id = id;
- difficultyEl.append(span);
- return span;
- }
- }
- async function appendRating() {
- const slug = getSlug(window.location);
- if (!slug) return;
- const rating = getRating(slug);
- if (rating) {
- console.log("got a rating for slug", slug, ":", rating);
- }
- const el = await getOrCreateRatingElement();
- el.textContent = (rating == null ? void 0 : rating.toString()) ?? "";
- }
- function initRatings() {
- appendRating();
- if (_monkeyWindow.onurlchange === null) {
- _monkeyWindow.addEventListener("urlchange", () => {
- appendRating();
- });
- }
- }
- async function initDescriptionTab() {
- var _a2;
- const descriptionTab = await findElement(
- ".flexlayout__tab:has([data-track-load='description_content'])",
- {
- timeout: 0,
- additionalRule: (el) => el.style.display !== "none"
- }
- );
- const titleContainer = await findElement("div:has(> .text-title-large)", {
- parent: descriptionTab
- });
- const buttonsContainer = document.createElement("div");
- buttonsContainer.setAttribute(
- "id",
- a(CONFIG.APP_NAME) + "-description"
- );
- buttonsContainer.style.cssText = "display: contents;";
- (_a2 = titleContainer.parentElement) == null ? void 0 : _a2.before(buttonsContainer);
- mount(DescriptionButttons, {
- target: buttonsContainer
- });
- initRatings();
- }
- function Find_editorial_screenshot($$anchor, $$props) {
- push($$props, false);
- const editorialsMarkdown = _GM_getResourceText("editorials");
- function extractScreenshotLink(problemTitle) {
- const cleanTitle = problemTitle.trim();
- const headingPattern = new RegExp(`####\\s+\\[${cleanTitle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\]\\((.*?)\\)`, "i");
- const match = editorialsMarkdown.match(headingPattern);
- return match ? match[1] : null;
- }
- async function goToEditorialScreenshot() {
- const title = await getTitle();
- const link = extractScreenshotLink(title);
- if (link) {
- window.open(link, "_blank");
- } else {
- toaster.error(`Editorial screenshot not found for problem: ${title}`);
- }
- }
- init();
- Button($$anchor, {
- onclick: goToEditorialScreenshot,
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text("Find Screenshot");
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- const turndown = createTurndownService();
- turndown.addRule("remove-heading-link", {
- filter: (node) => node.nodeName === "A" && node.getAttribute("aria-hidden") === "true",
- replacement: () => ""
- });
- turndown.addRule("save-math-as-is", {
- filter: (node) => ["SPAN", "DIV"].includes(node.nodeName) && node.matches(".math, .maths, .math-tex"),
- replacement: (_content, node) => node.outerHTML
- });
- function waitForIframeToLoad(iframe) {
- return new Promise((resolve) => {
- var _a2, _b, _c, _d;
- if (iframe.src !== "about:blank") {
- const isSameOrigin = new URL(iframe.src).hostname === window.location.hostname;
- if (!isSameOrigin || ((_b = (_a2 = iframe.contentWindow) == null ? void 0 : _a2.location) == null ? void 0 : _b.href) !== "about:blank" && ((_c = iframe.contentWindow) == null ? void 0 : _c.document.readyState) == "complete") {
- resolve(void 0);
- return;
- }
- }
- console.log("wait for iframe to load...");
- (_d = iframe.contentWindow) == null ? void 0 : _d.addEventListener("load", resolve, {
- once: true
- });
- });
- }
- const playgroundCache = /* @__PURE__ */ new Map();
- async function prefetchPlayground(editorialEl) {
- const iframes = Array.from(editorialEl.querySelectorAll("iframe"));
- const promises = iframes.map(async (iframe) => {
- var _a2, _b;
- await waitForIframeToLoad(iframe);
- const { src, contentDocument } = iframe;
- if (!src.includes("playground")) return;
- console.log((_b = (_a2 = iframe.contentWindow) == null ? void 0 : _a2.location) == null ? void 0 : _b.href);
- const langTab = await findElement("div.lang-btn-set", {
- parent: contentDocument,
- timeout: 1e3
- });
- const textarea = contentDocument == null ? void 0 : contentDocument.querySelector(
- "textarea[name='lc-codemirror']"
- );
- let result = `<MixedCodeBlock>
- `;
- Array.from(
- langTab.children
- ).forEach((button) => {
- var _a3;
- let lang = (_a3 = button.textContent) == null ? void 0 : _a3.toLowerCase();
- if (lang === "python3") lang = "python";
- button.click();
- const code = textarea == null ? void 0 : textarea.textContent;
- result += `\`\`\`${lang}
- ${code}
- \`\`\`
- `;
- });
- result += `</MixedCodeBlock>`;
- playgroundCache.set(src, result);
- });
- await Promise.all(promises);
- }
- turndown.addRule("save-code-playground", {
- filter: ["iframe"],
- replacement: (_content, node) => {
- const { src } = node;
- if (!src.includes("playground")) return "";
- return `[LeetCode Playground](${src})
- ` + (playgroundCache.get(src) ?? "");
- }
- });
- const slideCache = /* @__PURE__ */ new Map();
- async function preFetchSlides(editorialEl) {
- const slideImages = editorialEl.querySelectorAll("img[alt='Current']");
- const promises = Array.from(slideImages).map(async (image) => {
- var _a2, _b, _c;
- const slideContainer = (_a2 = image.parentElement) == null ? void 0 : _a2.parentElement;
- if (!slideContainer) {
- throw new Error("Slide container not found");
- }
- const slideNumIndicator = slideContainer.children[2].children[1];
- slideNumIndicator.setAttribute("data-skip-me-turndown", "true");
- const slidesCountStr = (_c = (_b = slideNumIndicator.textContent) == null ? void 0 : _b.match(/\d+$/)) == null ? void 0 : _c[0];
- if (!slidesCountStr) {
- throw new Error("Slide count not found");
- }
- const nextSlideButton = slideContainer.querySelector("svg:nth-child(3)");
- if (!nextSlideButton) {
- throw new Error("Next slide button not found");
- }
- const firstSlideSrc = image.src;
- slideCache.set(firstSlideSrc, []);
- for (let i2 = 0; i2 < Number(slidesCountStr); i2++) {
- simulateMouseClickReact(nextSlideButton);
- const dataURL = await convertSrcToDataURL(image.src);
- slideCache.get(firstSlideSrc).push(dataURL);
- }
- });
- await Promise.all(promises);
- }
- turndown.addRule("save-slides", {
- filter: (node) => node.tagName === "IMG" && node.alt === "Current",
- replacement: (_content, node) => {
- const { src } = node;
- const dataURLs = slideCache.get(src);
- if (!dataURLs) return "";
- let res = `<Slides>
- `;
- dataURLs.forEach((dataURL, index) => {
- res += `
- `;
- });
- res += `
- </Slides>`;
- return res;
- }
- });
- turndown.addRule("save-details-as-is", {
- filter: ["details"],
- replacement: (_content, node) => {
- const { children } = node;
- [...children].forEach((child2) => {
- if (!child2.textContent) node.removeChild(child2);
- });
- return node.outerHTML;
- }
- });
- turndown.remove(
- (node) => node.getAttribute("data-skip-me-turndown") === "true"
- );
- async function scrapeEditorial(editorialEl) {
- await prefetchPlayground(editorialEl);
- await preFetchSlides(editorialEl);
- const editorial = await htmlToMd(editorialEl, {
- turndownService: turndown
- });
- playgroundCache.clear();
- slideCache.clear();
- return editorial;
- }
- async function downloadEditorial(editorialFinder, titleFinder) {
- toaster.promise(
- async () => {
- const editorialEl = await editorialFinder();
- const editorial = await scrapeEditorial(editorialEl);
- const title = await titleFinder();
- const blob = new Blob([`# ${title}
- `, editorial], {
- type: "text/markdown; charset=UTF-8"
- });
- downloadFile(blob, title, "md");
- },
- {
- loading: "Scraping editorial...",
- success: "Editorial scraped. Downloading...",
- error: "Something went wrong while scraping. See browser console for more detail."
- }
- );
- }
- function Save_editorial($$anchor, $$props) {
- push($$props, false);
- async function findEditorial() {
- const editorialEl = await findElement(".flexlayout__tab:has(#editorial-quick-navigation) div.WRmCx", { timeout: 2e3 });
- return editorialEl;
- }
- init();
- Button($$anchor, {
- onclick: () => downloadEditorial(findEditorial, getTitle),
- variant: "orange",
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text("Save Editorial as Markdown");
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- function Read_saved_editorial($$anchor, $$props) {
- push($$props, false);
- init();
- Button($$anchor, {
- get href() {
- return CONFIG.EDITORIAL_READER_URL;
- },
- variant: "green",
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text("Read Saved Editorial");
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- var root_1$1 = /* @__PURE__ */ from_html(`<!> <!> <!>`, 1);
- function EditorialButtons($$anchor) {
- ButtonGroup($$anchor, {
- style: "z-index: 10; position:relative; padding: 0.5rem",
- children: ($$anchor2, $$slotProps) => {
- var fragment_1 = root_1$1();
- var node = first_child(fragment_1);
- Find_editorial_screenshot(node, {});
- var node_1 = sibling(node, 2);
- Save_editorial(node_1, {});
- var node_2 = sibling(node_1, 2);
- Read_saved_editorial(node_2, {});
- append($$anchor2, fragment_1);
- },
- $$slots: { default: true }
- });
- }
- async function initEditorialTab() {
- const editorialTab = await findElement(
- ".flexlayout__tab:has(div.bg-blocker, #editorial-quick-navigation)",
- {
- timeout: 0,
- additionalRule: (el) => el.style.display !== "none"
- }
- );
- const buttonsContainer = document.createElement("div");
- buttonsContainer.style.cssText = "display: contents;";
- buttonsContainer.setAttribute(
- "id",
- a(CONFIG.APP_NAME) + "-editorial"
- );
- editorialTab.prepend(buttonsContainer);
- mount(EditorialButtons, {
- target: buttonsContainer
- });
- }
- async function main$1() {
- const initPromises = [];
- initPromises.push(problemState.patchMonacoEditor());
- initPromises.push(initDescriptionTab());
- if (globalState.site === "global") {
- initPromises.push(initEditorialTab());
- }
- await Promise.all(initPromises);
- }
- function getElementIndex(element) {
- if (!element.parentNode) throw new Error("Element has no parent node");
- return Array.from(element.parentNode.children).indexOf(element);
- }
- function Save_explore_article($$anchor, $$props) {
- push($$props, false);
- async function findExploreEditorial() {
- return await findElement("div.block-markdown");
- }
- async function getExploreTitle() {
- var _a2, _b;
- const tocContainer = await findElement("div.list-group:not(.item-list-group)");
- const titleContainer = tocContainer.querySelector(".list-group-item .selected");
- if (!titleContainer) {
- throw new Error("Title container not found");
- }
- const title = ((_b = (_a2 = titleContainer.querySelector(".title")) == null ? void 0 : _a2.textContent) == null ? void 0 : _b.trim()) ?? "";
- const articleNumber = getElementIndex(titleContainer) + 1;
- const chapterEl = titleContainer.closest("div.chapter-item");
- if (!chapterEl) {
- throw new Error("Chapter not found");
- }
- const chapterNumber = getElementIndex(chapterEl);
- return `${chapterNumber}.${articleNumber} ${title}`;
- }
- init();
- Button($$anchor, {
- onclick: () => downloadEditorial(findExploreEditorial, getExploreTitle),
- children: ($$anchor2, $$slotProps) => {
- var text$1 = text("Save Article as Markdown");
- append($$anchor2, text$1);
- },
- $$slots: { default: true }
- });
- pop();
- }
- var root_1 = /* @__PURE__ */ from_html(`<!> <!>`, 1);
- function ExploreButtons($$anchor) {
- ButtonGroup($$anchor, {
- children: ($$anchor2, $$slotProps) => {
- var fragment_1 = root_1();
- var node = first_child(fragment_1);
- Save_explore_article(node, {});
- var node_1 = sibling(node, 2);
- Read_saved_editorial(node_1, {});
- append($$anchor2, fragment_1);
- },
- $$slots: { default: true }
- });
- }
- async function main() {
- const toolbar = await findElement("div.left-side", { timeout: 0 });
- const container = document.createElement("div");
- container.style.cssText = "display: contents;";
- toolbar.append(container);
- mount(ExploreButtons, {
- target: container
- });
- }
- const url = window.location.href;
- const problemPageRegex = /https?:\/\/leetcode\.com\/problems\/.*|https?:\/\/leetcode\.cn\/problems\/.*/;
- const explorePageRegex = /https?:\/\/leetcode\.com\/explore\/.*\/card\/.*/;
- if (problemPageRegex.test(url)) {
- main$1();
- } else if (explorePageRegex.test(url)) {
- main();
- }
- })(TurndownService, Compressor);
QingJ © 2025
镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址