diff --git a/AGENTS.md b/AGENTS.md index 118c7662..dd9f90b3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,7 +70,7 @@ Treat scripts, imported ZIPs, Gallery content, Skills, plugin manifests, network - Swift: 4-space indentation, Xcode defaults, `UpperCamelCase` types and `lowerCamelCase` members. Prefer small SwiftUI views, modern Observation for new state models where deployment allows, stable `ForEach` identity, and accessibility labels for icon-only controls. - JavaScript/React: 2-space indentation, `UpperCamelCase` components and `lowerCamelCase` functions. Match surrounding formatting; avoid unrelated whole-file rewrites. -- Runtime examples: keep `main.jsx` UTF-8, deterministic, within runtime budgets, and compatible with their declared permissions/hosts/plugins. +- Runtime examples: keep `main.jsx` UTF-8, deterministic, within runtime budgets, and compatible with their declared permissions/hosts/plugins. They are formatted with Prettier (`Editor/editorfe/node_modules/.bin/prettier --no-config --print-width 100`) and commented for a reader who is new to ScriptWidget; a text with two spaces in a row must be written as a string in braces, because the formatter joins them. - Xcode projects use explicit file references. When adding shared Swift sources, add them to every app/widget/test target that compiles or references them, then lint both `.pbxproj` files with `plutil -lint`. - Preserve user-authored or unrelated dirty-worktree changes. Generated editor bundles are the exception only when deliberately rebuilt from matching frontend source. diff --git a/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx b/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx index 029ec5a7..3d781cc5 100644 --- a/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx +++ b/Android/app/src/main/assets/Script.android/android/Automation Counter/main.jsx @@ -1,40 +1,70 @@ // A counter with two declared actions. The buttons run them, and so can // another app: on Android turn on Settings > Automation, allow this package, // and send the "increment" or "reset" action from Tasker or a similar app. -const valueKey = "counter.value", sourceKey = "counter.source"; +// The actions and their functions are declared under "actions" in widget.json, which +// also lists the "storage" permission that $storage needs. +// Try: change the step in increment(), or add a third action here and in widget.json. +// The keys under which $storage, the small store of this package, keeps the two values. +const valueKey = "counter.value", + sourceKey = "counter.source"; +// The count is stored as text. If the text is not a number, start again from 0. function read() { const value = Number($storage.getString(valueKey)); return Number.isFinite(value) ? value : 0; } +// Save the new count and what caused the change. function write(value) { $storage.setString(valueKey, String(value)); // "widget" for a tap, "shortcut" for an app shortcut, "automation" for another app. $storage.setString(sourceKey, $getenv("action-source")); $render({"Count " + value}); } -function increment() { write(read() + 1); } -function reset() { write(0); } +// These two names are the "function" values of the actions in widget.json. +function increment() { + write(read() + 1); +} +function reset() { + write(0); +} +// For a widget this is "small", "medium" or "large". "action" and "function" mean the +// script was started to run an action, not to draw the widget. const size = $getenv("widget-size"); if (size === "action" || size === "function") { // The host calls the declared function after this script was evaluated. } else { + // Empty text until the count was changed for the first time. const source = $storage.getString(sourceKey); // A small widget has room for the icons only. const small = size === "small"; + // One button. actionID names an action declared in widget.json. const control = (id, symbol, title) => ( - + ); + // Draw the widget. frame="max" makes the stack fill it. Colors named material. + // follow the Android wallpaper. $render( - Counter - {String(read())} - {source ? "Changed by " + source : "Not changed yet"} + + Counter + + + {String(read())} + + + {source ? "Changed by " + source : "Not changed yet"} + {control("increment", "plus.circle.fill", "Add one")} {control("reset", "arrow.counterclockwise", "Reset")} - + , ); } diff --git a/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx b/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx index 7d27671c..1190cf15 100644 --- a/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx +++ b/Android/app/src/main/assets/Script.android/android/Scrolling Checklist/main.jsx @@ -1,34 +1,79 @@ // A list that scrolls inside the widget, which only Android can do. // Every row is a toggle that keeps its own state in package storage. // iPhone widgets cannot scroll, so the first rows are shown there. +// $storage needs the "storage" permission, which widget.json lists. +// Try: change the texts in items, or the number of rows shown without a list. const items = [ - "Water the plants", "Reply to Sam", "Book the dentist", "Renew the library card", "Back up the photos", - "Order printer ink", "Call the plumber", "Pay the electricity bill", "Plan the weekend trip", "Clean the keyboard", - "Update the budget", "Return the parcel", "Charge the camera", "Sort the bookshelf", "Write to grandma", - "Check the tire pressure", "Buy a birthday card", "Defrost the freezer", "Review the notes", "Stretch for ten minutes", + "Water the plants", + "Reply to Sam", + "Book the dentist", + "Renew the library card", + "Back up the photos", + "Order printer ink", + "Call the plumber", + "Pay the electricity bill", + "Plan the weekend trip", + "Clean the keyboard", + "Update the budget", + "Return the parcel", + "Charge the camera", + "Sort the bookshelf", + "Write to grandma", + "Check the tire pressure", + "Buy a birthday card", + "Defrost the freezer", + "Review the notes", + "Stretch for ten minutes", ]; +// $system.platform() says where the script runs. Only "android" has . const android = $system.platform() === "android"; const size = $getenv("widget-size"); +// One stored value per row: the text "true" when the row is checked. const done = items.map((_, index) => $storage.getString("check." + index) === "true"); const count = done.filter(Boolean).length; +// One row. stateKey is the $storage key that holds the state of this toggle. +// A checked row gets the quieter text color. const row = (title, index) => ( - {title} + + {title} + ); -const rows = android - ? {items.map(row)} - : {items.slice(0, size === "large" ? 7 : 2).map(row)}; +// Android: every row, in a list that scrolls. Elsewhere is unknown, so show the +// first 7 rows in a large widget and the first 2 in the other sizes. +const rows = android ? ( + {items.map(row)} +) : ( + + {items.slice(0, size === "large" ? 7 : 2).map(row)} + +); +// frame="max,topLeading" fills the widget and puts the content in the top left corner. $render( - + + {/* The title on the left and "3 of 20" on the right; pushes them apart. */} - Checklist + + Checklist + - {count + " of " + items.length} + + {count + " of " + items.length} + {rows} - + , ); diff --git a/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx b/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx index 06cf4985..2869fe4a 100644 --- a/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx +++ b/Android/app/src/main/assets/Script.android/android/Wallpaper Colors/main.jsx @@ -2,23 +2,50 @@ // "material." in any color prop and the widget follows the wallpaper, // in light and in dark mode. iPhone does not know these names and keeps its // default colors. +// Try: replace a role in the list with another one, such as "surfaceVariant" or "outline". +// Used only for the last line of text, which says where the widget runs. const android = $system.platform() === "android"; +// A small widget gets shorter texts. const small = $getenv("widget-size") === "small"; -const roles = ["primary", "secondary", "tertiary", "primaryContainer", "secondaryContainer", "tertiaryContainer"]; +// The roles shown as color swatches. +const roles = [ + "primary", + "secondary", + "tertiary", + "primaryContainer", + "secondaryContainer", + "tertiaryContainer", +]; +// frame="max,topLeading" fills the widget and puts the content in the top left corner. $render( - - {small ? "Wallpaper" : "Wallpaper colors"} + + + {small ? "Wallpaper" : "Wallpaper colors"} + + {/* One swatch per role. frame="max,26": as wide as possible and 26 points high. */} - {roles.map((role) => )} + {roles.map((role) => ( + + ))} + {/* A card in a container color. Its text uses the matching "on" color to stay readable. */} - {small ? "Follows it" : "Change the wallpaper and this card follows."} + + {small ? "Follows it" : "Change the wallpaper and this card follows."} + + {/* takes the free room, so the last line sits at the bottom. */} {android ? (small ? "Material colors" : "Material colors of this phone") : "Android only"} - + , ); diff --git a/CHANGELOG.md b/CHANGELOG.md index bb14c639..4ed29757 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,8 @@ Notable user-visible changes are recorded here. ScriptWidget follows semantic ve - Fix bundled templates whose text was cut off or pushed out of the widget, most visibly with the wider font of Android, Windows and Linux: Month Calendar (long month names, six-week months), the Daily Command Center, Family Command Board, Travel Day and Wellness dashboards, World Clock Faces and Year in Dots at the extra-large size, and fifteen smaller templates. - Give 21 bundled templates that had one layout a small-widget layout showing their essential content (clocks, battery, focus, reading, sleep, system and the five dashboards), give the Daily Command Center, Family Command Board, Monthly Budget, Travel Day and Wellness dashboards a medium layout, and fix the overlapping rows of the large Monthly Budget Planner and the cut-off header of the medium Personal Dashboard. - Fix Text Year Days Left, which counted to 31 January of the next year and so showed 31 days too many. +- Format every bundled example with Prettier and add comments for readers new to ScriptWidget; no example draws anything different. +- Linux 0.1.4: the management window lists Components and APIs as their own sidebar entries, as on Windows. - Continue expanded personal-data APIs, authenticated services/music and visual editing on the same release branch; M3–M5 remain in progress. ## Unreleased diff --git a/Editor/editorfe/scripts/generate-api-docs.mjs b/Editor/editorfe/scripts/generate-api-docs.mjs index ea61cc4f..6dfe3e64 100644 --- a/Editor/editorfe/scripts/generate-api-docs.mjs +++ b/Editor/editorfe/scripts/generate-api-docs.mjs @@ -1,7 +1,13 @@ import { readFile, writeFile } from "node:fs/promises"; import { scriptWidgetAPI as api } from "../src/scriptWidgetAPI.js"; import { dataAPICatalog } from "../src/dataAPICatalog.js"; -import { platformCell, platformColumns, platformRow, platformSentence, platformSupport } from "../src/platformSupport.js"; +import { componentSupport, platformCell, platformColumns, platformRow, platformSentence, platformSupport } from "../src/platformSupport.js"; + +const componentTable = [ + `| Component | ${platformColumns.map((column) => column.title).join(" | ")} |`, + `| --- | ${platformColumns.map(() => "---").join(" | ")} |`, + ...componentSupport.map((row) => `| ${row.label ?? row.components.map((name) => `\`${name}\``).join(", ")} | ${platformColumns.map((column) => platformCell(row[column.id])).join(" | ")} |`), +]; const outputURL = new URL("../../../docs/scriptwidget-runtime-api.md", import.meta.url); @@ -10,6 +16,12 @@ const lines = [ "", `> Generated from Studio's static API metadata (schema v${api.schemaVersion}, runtime ${api.runtimeVersion}). The native runtime switch is authoritative. Do not edit by hand.`, "", + "## Which systems each component runs on", + "", + "Every component below exists on iPhone, iPad, Mac, Android, Windows and Linux, except the scrolling ``, which only Android has and which is not in this reference (see [ScriptWidget for Android](android/README.md)). What a system draws differently is in this table; [Platform support](platform-support.md) has the same table beside the APIs and the widget features.", + "", + ...componentTable, + "", "## Components", "", ]; @@ -80,16 +92,16 @@ function runsOn(apis) { } // Replaces what is between the two markers of a hand-written page. -async function writeBetweenMarkers(file, content) { +async function writeBetweenMarkers(file, content, start = "", end = "") { const url = new URL(`../../../docs/${file}`, import.meta.url); const text = await readFile(url, "utf8"); - const start = "", end = ""; const from = text.indexOf(start), to = text.indexOf(end); - if (from < 0 || to < from) throw new Error(`docs/${file} has no platforms markers`); + if (from < 0 || to < from) throw new Error(`docs/${file} has no ${start} marker`); await writeFile(url, `${text.slice(0, from + start.length)}\n${content.join("\n")}\n${text.slice(to)}`); } await writeBetweenMarkers("platform-support.md", platformTable); +await writeBetweenMarkers("platform-support.md", componentTable, "", ""); await writeBetweenMarkers("runtime-api.md", platformTable); for (const [file, apis] of Object.entries({ "calendar-api.md": ["$calendar"], diff --git a/Editor/editorfe/src/platformSupport.js b/Editor/editorfe/src/platformSupport.js index af59ecb9..90793a4b 100644 --- a/Editor/editorfe/src/platformSupport.js +++ b/Editor/editorfe/src/platformSupport.js @@ -58,3 +58,25 @@ export function platformSentence(row) { } return { yes: yes.join(", "), no: no.join(", ") }; } + +// The same for the JSX components. Android, Windows and Linux draw with one +// shared renderer, so a component exists on all three or on none; what differs +// is listed here. The authorities are docs/public-animations.md for the Apple +// columns and the "Differences" tables of docs/android, docs/windows and +// docs/linux for the others. +const lookAlike = "Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder"; +export const componentSupport = [ + { components: ["", "", "", "", "", "", ""], label: "Layout: ``, ``, ``, ``, ``, ``, ``", ...everywhere }, + { components: ["", ", ); } else if (size === "accessoryInline") { - $render({habits[0].name} · {streak(records[0])}-day streak); + // Lock Screen, inline: one line of text. + $render( + + {habits[0].name} · {streak(records[0])}-day streak + , + ); } else if (size === "small") { + // Small widget: the first habit, 8 weeks. $render(
- - + + + + + + , ); } else if (size === "medium") { + // Medium widget: the first habit, 22 weeks. $render(
- - + + + + + + , ); } else if (size === "extraLarge") { + // Extra large widget: the three habits side by side. $render( {habits.map((habit, index) => (
- + + + + + ))} - + , ); } else { + // Large widget: the three habits one below the other, 26 weeks each. $render( {habits.map((habit, index) => ( -
+ +
+ + + ))} - + , ); } diff --git a/Gallery/widgets/habit-streak/lib/records.js b/Gallery/widgets/habit-streak/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Gallery/widgets/habit-streak/lib/records.js +++ b/Gallery/widgets/habit-streak/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Gallery/widgets/habit-streak/main.jsx b/Gallery/widgets/habit-streak/main.jsx index 06171965..ff75485a 100644 --- a/Gallery/widgets/habit-streak/main.jsx +++ b/Gallery/widgets/habit-streak/main.jsx @@ -1,40 +1,143 @@ // Explicit check-ins only. Optional widget-param: your habit name (up to 40 characters). // The earlier template recorded automatically on refresh. Its original keys stay // untouched; they are not reliable evidence of completed days and are never imported. -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); -const size = $getenv("widget-size"), title = ($getenv("widget-param") || localRecords.configuration("habitStreak").title).trim(); +// Shows how many days in a row you checked in, with Check in, Undo and Reset buttons. +// Try changing the colors below, or the habit name in Records & Configuration. +// $storage needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. +const size = $getenv("widget-size"), + title = ($getenv("widget-param") || localRecords.configuration("habitStreak").title).trim(); if (!title || title.length > 40) throw new Error("Use a habit name of 1–40 characters."); +// One record per day under the key "habitStreak.v2": 1 means done; no record reads as 0. const log = localRecords.create("habitStreak.v2", (value) => value === 1, 0); -function checkIn() { const changed = log.edit(() => 1); $render({changed ? "Checked in" : "Already checked in"}); } -function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); } -function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); } -const state = log.read(), done = log.value(state) === 1; +// The three functions below are named by the "actions" in widget.json. A tap on a +// {size !== "small" && } - {!["small", "medium"].includes(size) && Last 7 days{log.recent(state).map((day) => {day.date.slice(5)}{day.recorded ? "✓" : "—"})}} - {hasLegacy && {size === "small" ? "Earlier counter kept" : legacyLabel}} - ); + // Home Screen sizes. frame="max" fills the widget; padding is the space in points + // around the content. + $render( + + + + + {title} + + + + {streakLabel} + + + + + {/* The small widget has no room for a third button. */} + {size !== "small" && ( + + )} + + {/* Large sizes: the last 7 days, oldest first. day.date.slice(5) is the MM-DD part. */} + {!["small", "medium"].includes(size) && ( + + + Last 7 days + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? "✓" : "—"} + + + ))} + + )} + {/* Shown only when the earlier version left a counter behind. */} + {hasLegacy && ( + + {size === "small" ? "Earlier counter kept" : legacyLabel} + + )} + , + ); } diff --git a/Gallery/widgets/health-card/lib/health.js b/Gallery/widgets/health-card/lib/health.js index 1e6ae9dd..eb0074c9 100644 --- a/Gallery/widgets/health-card/lib/health.js +++ b/Gallery/widgets/health-card/lib/health.js @@ -1,60 +1,173 @@ // Query only the selected metric. Never persist HealthKit readings or authorization. +// main.jsx imports this file ("lib/health.js") and then uses `healthCard`. var healthCard = (() => { - const defaults = {metric:"steps",stepsGoal:8000,energyGoal:500}; + // metric is "steps", "energy" or "heart". The goals are steps and kcal per day. + const defaults = { metric: "steps", stepsGoal: 8000, energyGoal: 500 }; + // Check the settings, or throw a message the app can show. function validate(value) { - if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "energyGoal,metric,stepsGoal" || - !["steps","energy","heart"].includes(value.metric) || !Number.isInteger(value.stepsGoal) || value.stepsGoal < 1 || value.stepsGoal > 100000 || - !Number.isInteger(value.energyGoal) || value.energyGoal < 1 || value.energyGoal > 10000) throw new Error("Choose a metric and valid goals in Records & Configuration."); + if ( + !value || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).sort().join(",") !== "energyGoal,metric,stepsGoal" || + !["steps", "energy", "heart"].includes(value.metric) || + !Number.isInteger(value.stepsGoal) || + value.stepsGoal < 1 || + value.stepsGoal > 100000 || + !Number.isInteger(value.energyGoal) || + value.energyGoal < 1 || + value.energyGoal > 10000 + ) + throw new Error("Choose a metric and valid goals in Records & Configuration."); return value; } - function options(raw,parameter) { - let result = {...defaults}; + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter, which is JSON such as + // {"metric":"heart"}. + function options(raw, parameter) { + let result = { ...defaults }; if (raw !== null && raw !== undefined && raw !== "") { - if (typeof raw !== "string" || raw.length > 4096) throw new Error("Invalid saved health configuration."); + if (typeof raw !== "string" || raw.length > 4096) + throw new Error("Invalid saved health configuration."); const saved = JSON.parse(raw); - if (!saved || Object.keys(saved).sort().join(",") !== "kind,values,version" || saved.kind !== "healthCard" || saved.version !== 1) throw new Error("Invalid saved health configuration."); - result = {...validate(saved.values)}; + if ( + !saved || + Object.keys(saved).sort().join(",") !== "kind,values,version" || + saved.kind !== "healthCard" || + saved.version !== 1 + ) + throw new Error("Invalid saved health configuration."); + result = { ...validate(saved.values) }; } if (parameter) { - if (typeof parameter !== "string" || parameter.length > 4096) throw new Error("Invalid health parameter."); + if (typeof parameter !== "string" || parameter.length > 4096) + throw new Error("Invalid health parameter."); const overrides = JSON.parse(parameter); - if (!overrides || typeof overrides !== "object" || Array.isArray(overrides) || Object.keys(overrides).some(key => !Object.hasOwn(defaults,key))) throw new Error("Unknown health setting."); - result = {...result,...overrides}; + if ( + !overrides || + typeof overrides !== "object" || + Array.isArray(overrides) || + Object.keys(overrides).some((key) => !Object.hasOwn(defaults, key)) + ) + throw new Error("Unknown health setting."); + result = { ...result, ...overrides }; } return validate(result); } - async function load(config,now,projection) { + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which gets no reading. + async function load(config, now, projection) { validate(config); const metric = config.metric; - const title = metric === "steps" ? "Steps today" : metric === "energy" ? "Active energy" : "Latest heart rate"; - const icon = metric === "steps" ? "figure.walk" : metric === "energy" ? "flame.fill" : "heart.fill"; + // Title, icon and color of the chosen metric. + const title = + metric === "steps" + ? "Steps today" + : metric === "energy" + ? "Active energy" + : "Latest heart rate"; + const icon = + metric === "steps" ? "figure.walk" : metric === "energy" ? "flame.fill" : "heart.fill"; const color = metric === "steps" ? "#2563eb" : metric === "energy" ? "#c2410c" : "#be185d"; - const empty = (heading,detail) => ({available:false,title,icon,color,heading,detail}); - if (projection) return empty("Refresh in current entry","Health readings are queried only for the current entry."); - if (!$health.isAvailable()) return empty("Health on iPhone","Install on iPhone and enable Health in ScriptWidget Settings."); + // The result when there is no number: a heading and one line of explanation. + const empty = (heading, detail) => ({ available: false, title, icon, color, heading, detail }); + if (projection) + return empty( + "Refresh in current entry", + "Health readings are queried only for the current entry.", + ); + // isAvailable() is false on a system without Health data. + if (!$health.isAvailable()) + return empty( + "Health on iPhone", + "Install on iPhone and enable Health in ScriptWidget Settings.", + ); + // Health does not tell an app whether reading was allowed, so this only stops when + // Health is not available or not set up. const authorization = $health.authorizationStatus(); - if (["unavailable","undeclared","denied","notDetermined"].includes(authorization)) return empty("Connect Health","Enable Health in ScriptWidget Settings on iPhone."); + if (["unavailable", "undeclared", "denied", "notDetermined"].includes(authorization)) + return empty("Connect Health", "Enable Health in ScriptWidget Settings on iPhone."); let reading; - try { reading = await (metric === "steps" ? $health.stepCountToday() : metric === "energy" ? $health.activeEnergyToday() : $health.heartRateLatest()); } - catch { return empty("Health unavailable","Open ScriptWidget to check access; locked devices may delay readings."); } - if (!reading || typeof reading !== "object" || reading.hasSamples === false || (reading.hasSamples !== true && reading.value === 0)) - return empty("No readable data","Check Health access and recorded samples. Read permission is not disclosed."); - if (reading.hasSamples !== undefined && typeof reading.hasSamples !== "boolean") return empty("Reading unavailable","Invalid sample metadata. Refresh later."); + // Ask Health for the chosen metric only. `await` waits for the answer. + try { + reading = await (metric === "steps" + ? $health.stepCountToday() + : metric === "energy" + ? $health.activeEnergyToday() + : $health.heartRateLatest()); + } catch { + return empty( + "Health unavailable", + "Open ScriptWidget to check access; locked devices may delay readings.", + ); + } + // No samples. A value of 0 without the hasSamples flag is treated the same way. + if ( + !reading || + typeof reading !== "object" || + reading.hasSamples === false || + (reading.hasSamples !== true && reading.value === 0) + ) + return empty( + "No readable data", + "Check Health access and recorded samples. Read permission is not disclosed.", + ); + if (reading.hasSamples !== undefined && typeof reading.hasSamples !== "boolean") + return empty("Reading unavailable", "Invalid sample metadata. Refresh later."); + // Accept the reading only with the expected unit, a believable value and a recent end: + // within 15 minutes for today's totals, 24 hours for the heart rate. const unit = metric === "steps" ? "count" : metric === "energy" ? "kcal" : "bpm"; - const start = Date.parse(reading.start),end = Date.parse(reading.end),limit = metric === "heart" ? 24*3600000 : 15*60000; - if (reading.unit !== unit || typeof reading.value !== "number" || !Number.isFinite(reading.value) || reading.value < (metric === "heart" ? 1 : 0) || - reading.value > (metric === "steps" ? 1000000 : metric === "energy" ? 100000 : 300) || - !Number.isFinite(start) || !Number.isFinite(end) || start > end || end > now+60000 || now-end > limit) - return empty("Reading unavailable","No recent valid sample. Open Health and refresh later."); + const start = Date.parse(reading.start), + end = Date.parse(reading.end), + limit = metric === "heart" ? 24 * 3600000 : 15 * 60000; + if ( + reading.unit !== unit || + typeof reading.value !== "number" || + !Number.isFinite(reading.value) || + reading.value < (metric === "heart" ? 1 : 0) || + reading.value > (metric === "steps" ? 1000000 : metric === "energy" ? 100000 : 300) || + !Number.isFinite(start) || + !Number.isFinite(end) || + start > end || + end > now + 60000 || + now - end > limit + ) + return empty("Reading unavailable", "No recent valid sample. Open Health and refresh later."); + // A total that began on another day is not today's total. if (metric !== "heart") { - const today = new Date(now),begin = new Date(start); today.setHours(0,0,0,0);begin.setHours(0,0,0,0); - if (today.getTime() !== begin.getTime()) return empty("Refresh for today","Yesterday’s total is not shown as today’s activity."); + const today = new Date(now), + begin = new Date(start); + today.setHours(0, 0, 0, 0); + begin.setHours(0, 0, 0, 0); + if (today.getTime() !== begin.getTime()) + return empty("Refresh for today", "Yesterday’s total is not shown as today’s activity."); } - const goal = metric === "steps" ? config.stepsGoal : metric === "energy" ? config.energyGoal : null; - const minutes = Math.max(0,Math.floor((now-end)/60000)); - return {available:true,title,icon,color,value:Math.round(reading.value),unit:metric === "steps" ? "steps" : unit, - goal,progress:goal === null ? null : Math.min(1,reading.value/goal),age:minutes < 1 ? "Updated just now" : minutes < 60 ? `Updated ${minutes}m ago` : `Sample ${Math.floor(minutes/60)}h ago`, - detail:metric === "heart" ? "Latest sample · not live" : `Goal ${goal} ${metric === "steps" ? "steps" : "kcal"}`}; + // Heart rate has no goal. + const goal = + metric === "steps" ? config.stepsGoal : metric === "energy" ? config.energyGoal : null; + // Whole minutes since the end of the reading. + const minutes = Math.max(0, Math.floor((now - end) / 60000)); + // The result for main.jsx. `progress` is value / goal, at most 1. + return { + available: true, + title, + icon, + color, + value: Math.round(reading.value), + unit: metric === "steps" ? "steps" : unit, + goal, + progress: goal === null ? null : Math.min(1, reading.value / goal), + age: + minutes < 1 + ? "Updated just now" + : minutes < 60 + ? `Updated ${minutes}m ago` + : `Sample ${Math.floor(minutes / 60)}h ago`, + detail: + metric === "heart" + ? "Latest sample · not live" + : `Goal ${goal} ${metric === "steps" ? "steps" : "kcal"}`, + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Gallery/widgets/health-card/main.jsx b/Gallery/widgets/health-card/main.jsx index cd5d2674..7f58667a 100644 --- a/Gallery/widgets/health-card/main.jsx +++ b/Gallery/widgets/health-card/main.jsx @@ -1,23 +1,182 @@ // Read-only HealthKit card. Configure goals in Records & Configuration. // Empty results never prove that read permission was granted or denied. +// Shows one Health number (steps, active energy or heart rate) and a ring for its goal. +// Try another metric or goal in Records & Configuration, or with a widget parameter such +// as {"metric":"energy","energyGoal":400}. +// The Health API runs on iPhone and iPad, and on Android through Health Connect (no ring goals +// or stand time); not on Mac, Windows or Linux. +// widget.json must declare the permissions "health", and "storage" for the saved settings. + +// $import runs another file of this package; lib/health.js defines `healthCard`. +// It returns false when the file is missing. if (!$import("lib/health.js")) throw new Error("Install the complete Health Steps Ring template."); -const config = healthCard.options($storage.getString("recordTemplate.config.v1"),$getenv("widget-param")); -const health = await healthCard.load(config,Date.now(),$getenv("timeline-is-projection") === "true"); -const size = $getenv("widget-size"),small = size === "small"; -const dark = $device.isdarkmode(),background = dark ? "#111827" : "#eff6ff",text = dark ? "#f8fafc" : "#1e3a8a",secondary = dark ? "#cbd5e1" : "#475569"; -const Ring = ({side}) => ; +// The settings: defaults, then what the app saved in $storage, then the widget parameter +// ($getenv("widget-param"), a text you set on each widget you place). +const config = healthCard.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Read the number. "timeline-is-projection" is "true" when the script runs for a future +// timeline entry; Health is not asked then. +const health = await healthCard.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +const size = $getenv("widget-size"), + small = size === "small"; +const dark = $device.isdarkmode(), + background = dark ? "#111827" : "#eff6ff", + text = dark ? "#f8fafc" : "#1e3a8a", + secondary = dark ? "#cbd5e1" : "#475569"; +// A progress ring with the icon of the metric in the middle. `value` goes from 0 to 1. +// puts its children on top of each other. +const Ring = ({ side }) => ( + + + + +); +// Choose a layout for the widget size. if (size === "accessoryInline") { - $render({health.available ? `${health.title}: ${health.value} ${health.unit}` : health.heading}); + // Lock Screen, inline: one line of text. + $render( + + {health.available ? `${health.title}: ${health.value} ${health.unit}` : health.heading} + , + ); } else if (size === "accessoryCircular") { - $render({health.available ? String(health.value) : "—"}{health.available ? health.unit : "Open app"}); + // Lock Screen, circular: an icon, the number and its unit. + $render( + + + + {health.available ? String(health.value) : "—"} + + {health.available ? health.unit : "Open app"} + , + ); } else if (size === "accessoryRectangular") { - $render({health.title}{health.available ? `${health.value} ${health.unit}` : health.heading}{health.available ? health.age : "Open ScriptWidget"}); + // Lock Screen, rectangular: three short lines. + $render( + + + {health.title} + + + {health.available ? `${health.value} ${health.unit}` : health.heading} + + {health.available ? health.age : "Open ScriptWidget"} + , + ); } else if (!health.available) { - $render({health.heading}{health.detail}); + // No number to show: say why. + $render( + + + + {health.heading} + + + {health.detail} + + , + ); } else if (small) { - $render({health.title}{String(health.value)}{health.unit}{health.detail}{health.age}); + // Small widget: the number, without a ring. + $render( + + + + + {health.title} + + + + + + {String(health.value)} + + + {health.unit} + + + + {health.detail} + + + {health.age} + + , + ); } else if (size === "medium") { - $render({health.goal === null ? : }{health.title}{String(health.value)}{health.unit}{health.detail}{health.age}); + // Medium widget: the ring on the left. Heart rate has no goal, so it gets an icon. + $render( + + {health.goal === null ? ( + + ) : ( + + )} + + + {health.title} + + + + {String(health.value)} + + + {health.unit} + + + + {health.detail} + + + {health.age} + + + , + ); } else { - $render({health.title}{health.goal === null ? : }{String(health.value)}{health.unit}{health.detail}{health.age}Apple Health · Read-only); + // Large and extra large widgets: the ring above the number. + $render( + + + {health.title} + + + {health.goal === null ? ( + + ) : ( + + )} + + + {String(health.value)} + + + {health.unit} + + + + {health.detail} + + + + {health.age} + + + Apple Health · Read-only + + , + ); } diff --git a/Gallery/widgets/health-overview/main.jsx b/Gallery/widgets/health-overview/main.jsx index 8c8f10f2..04873628 100644 --- a/Gallery/widgets/health-overview/main.jsx +++ b/Gallery/widgets/health-overview/main.jsx @@ -1,56 +1,410 @@ // Real read-only HealthKit summaries. Declare health; review access in app Settings. // Parameter: overview (default), sleep, activity or workouts. Nothing is saved. // Web Studio supplies editable samples; native widgets never seed Health data. -const family = $getenv("widget-size"), small = family === "small"; -const accessory = family.startsWith("accessory"), dark = $device.isdarkmode(); +// Shows the sleep of the last 24 hours, today's activity rings and recent workouts. +// Try the widget parameter (sleep, activity or workouts), or change `colors`. +// $health runs on iPhone and iPad, and on Android through Health Connect (no ring goals +// or stand time); not on Mac, Windows or Linux. +// widget.json must declare the permission "health". + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". +const family = $getenv("widget-size"), + small = family === "small"; +const accessory = family.startsWith("accessory"), + dark = $device.isdarkmode(); +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const mode = $getenv("widget-param").trim() || "overview"; +// Lock Screen sizes get a clear background and the system's own text colors. const background = accessory ? "clear" : dark ? "#17242b" : "#f2f8f8"; const foreground = accessory ? "primary" : dark ? "#eaf4f4" : "#23444b"; const secondary = accessory ? "secondary" : dark ? "#a6bec4" : "#58737c"; +// The ring colors: move, exercise, stand. const colors = ["#e67f92", "#70b58b", "#6aadd3"]; -let sleep = null, activity = null, workouts = null, errors = 0; +// Read the data. A part stays null when it is not asked for or cannot be read. +let sleep = null, + activity = null, + workouts = null, + errors = 0; +// isAvailable() is false on a system without Health data; the calls below would fail there. const supported = $health.isAvailable(); -if (!["overview", "sleep", "activity", "workouts"].includes(mode)) throw new Error("Use overview, sleep, activity or workouts as the widget parameter."); +if (!["overview", "sleep", "activity", "workouts"].includes(mode)) + throw new Error("Use overview, sleep, activity or workouts as the widget parameter."); if (supported) { - if (mode === "overview" || mode === "sleep") { try { sleep = await $health.sleepSummary(); } catch { errors++; } } - if (mode === "overview" || mode === "activity") { try { activity = await $health.activitySummary(); } catch { errors++; } } - if (mode === "overview" || mode === "workouts") { try { workouts = await $health.workouts(); } catch { errors++; } } + // `await` waits for the answer. A failed read is counted and the rest still shows. + if (mode === "overview" || mode === "sleep") { + try { + sleep = await $health.sleepSummary(); + } catch { + errors++; + } + } + if (mode === "overview" || mode === "activity") { + try { + activity = await $health.activitySummary(); + } catch { + errors++; + } + } + if (mode === "overview" || mode === "workouts") { + try { + workouts = await $health.workouts(); + } catch { + errors++; + } + } } -function duration(seconds) { const minutes = Math.round(seconds/60); return `${Math.floor(minutes/60)}h ${String(minutes%60).padStart(2,"0")}m`; } +// Seconds as text: 27000 becomes "7h 30m". +function duration(seconds) { + const minutes = Math.round(seconds / 60); + return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`; +} +// The text for each value, or a dash. hasSamples is false when Health returned nothing, +// which can also mean that the data was not shared with ScriptWidget. const sleeping = sleep?.hasSamples && sleep.totalSleepSeconds > 0; const sleepValue = sleeping ? duration(sleep.totalSleepSeconds) : "—"; const move = activity?.hasSamples ? activity.move : null; const moveValue = move ? `${Math.round(move.value)} ${move.unit}` : "—"; const recent = workouts?.items?.[0]; const workoutValue = workouts?.hasSamples ? String(workouts.items.length) : "—"; -const title = mode === "sleep" ? "Sleep summary" : mode === "activity" ? "Activity today" : mode === "workouts" ? "Recent workouts" : "Health overview"; -const rings = activity?.hasSamples ? [activity.move,activity.exercise,activity.stand] : []; -const progress = index => rings[index]?.goal > 0 ? Math.min(1,Math.max(0,rings[index].value/rings[index].goal)) : 0; -const Rings = ({side}) => ; -const Metric = ({label,value}) => {label}{value}; +const title = + mode === "sleep" + ? "Sleep summary" + : mode === "activity" + ? "Activity today" + : mode === "workouts" + ? "Recent workouts" + : "Health overview"; +// The three activity rings. progress(index) is value / goal, kept between 0 and 1. +const rings = activity?.hasSamples ? [activity.move, activity.exercise, activity.stand] : []; +const progress = (index) => + rings[index]?.goal > 0 ? Math.min(1, Math.max(0, rings[index].value / rings[index].goal)) : 0; +// Three rings inside each other; `side` is the outer size in points. +// puts its children on top of each other. +const Rings = ({ side }) => ( + + + + + +); +// A reusable piece of layout: a small label with its value under it. +const Metric = ({ label, value }) => ( + + + {label} + + + {value} + + +); +// Nothing to show: there is no Health data on this system, or nothing could be read. if (!supported || (!sleep && !activity && !workouts)) { const message = !supported ? "Use a Health-capable device." : "Review access in app Settings."; - $render(accessory ? Health · Open app : Health setup{small ? (!supported ? "Health unavailable\non this device." : "Review Health in\napp Settings.") : message}{small ? "Read-only" : "Read-only · Apple Health"}); + $render( + accessory ? ( + Health · Open app + ) : ( + + + + Health setup + + + {small + ? !supported + ? "Health unavailable\non this device." + : "Review Health in\napp Settings." + : message} + + + + {small ? "Read-only" : "Read-only · Apple Health"} + + + ), + ); } else if (family === "accessoryInline") { - $render({mode === "activity" ? `Move ${moveValue}` : mode === "workouts" ? `${workoutValue} workouts · 7d` : `Sleep ${sleepValue}`}); + // Lock Screen, inline: one line of text. + $render( + + {mode === "activity" + ? `Move ${moveValue}` + : mode === "workouts" + ? `${workoutValue} workouts · 7d` + : `Sleep ${sleepValue}`} + , + ); } else if (family === "accessoryCircular") { - $render({mode === "activity" ? moveValue : mode === "workouts" ? workoutValue : sleeping ? `${(sleep.totalSleepSeconds/3600).toFixed(1)}h` : "—"}); + // Lock Screen, circular: an icon and one value. + $render( + + + + {mode === "activity" + ? moveValue + : mode === "workouts" + ? workoutValue + : sleeping + ? `${(sleep.totalSleepSeconds / 3600).toFixed(1)}h` + : "—"} + + , + ); } else if (accessory) { - $render({title}{mode === "activity" ? moveValue : mode === "workouts" ? `${workoutValue} · last 7d` : sleepValue}); + // Lock Screen, rectangular: a title and one value. + $render( + + {title} + + {mode === "activity" + ? moveValue + : mode === "workouts" + ? `${workoutValue} · last 7d` + : sleepValue} + + , + ); } else if (mode === "sleep" && family === "medium") { - $render(SLEEP · LAST 24H{sleepValue}{sleep?.truncated ? "Partial window" : sleep?.conflictSeconds > 0 ? "Stage overlap" : sleeping ? "Known sleep intervals" : "No shared stages"}{["core","deep","rem"].map(stage=>)}); + // Sleep, medium widget: the total on the left, the sleep stages on the right. + $render( + + + + SLEEP · LAST 24H + + + {sleepValue} + + + {sleep?.truncated + ? "Partial window" + : sleep?.conflictSeconds > 0 + ? "Stage overlap" + : sleeping + ? "Known sleep intervals" + : "No shared stages"} + + + + + {["core", "deep", "rem"].map((stage) => ( + + ))} + + , + ); } else if (mode === "sleep") { - $render(SLEEP · LAST 24H{sleepValue}{sleep?.truncated ? "Partial sample window" : sleep?.conflictSeconds > 0 ? "Stage overlap" : sleeping ? "Known sleep intervals" : "No shared sleep stages"}{!small && sleeping && {["core","deep","rem"].map(stage=>)}}{small ? "Read-only" : "Apple Health · Read-only"}); + // Sleep, other sizes. + $render( + + + SLEEP · LAST 24H + + + + {sleepValue} + + + {sleep?.truncated + ? "Partial sample window" + : sleep?.conflictSeconds > 0 + ? "Stage overlap" + : sleeping + ? "Known sleep intervals" + : "No shared sleep stages"} + + {/* Larger sizes also list the stages. Each one is a number of seconds. */} + {!small && sleeping && ( + + {["core", "deep", "rem"].map((stage) => ( + + ))} + + )} + + + {small ? "Read-only" : "Apple Health · Read-only"} + + , + ); } else if (mode === "activity" && family === "medium") { - $render(ACTIVITY · TODAY{moveValue}{activity?.hasSamples ? `Exercise ${Math.round(activity.exercise.value)} min` : "No shared activity"}{activity?.hasSamples ? `Stand ${Math.round(activity.stand.value)} hrs` : "Goals unavailable"}); + // Activity, medium widget: the rings on the left, the numbers on the right. + $render( + + + + + ACTIVITY · TODAY + + + {moveValue} + + + {activity?.hasSamples + ? `Exercise ${Math.round(activity.exercise.value)} min` + : "No shared activity"} + + + {activity?.hasSamples + ? `Stand ${Math.round(activity.stand.value)} hrs` + : "Goals unavailable"} + + + + , + ); } else if (mode === "activity") { - $render(ACTIVITY · TODAY{moveValue}{!small && }); + // Activity, other sizes. + $render( + + + ACTIVITY · TODAY + + + + {moveValue} + + {!small && ( + + + + + )} + , + ); } else if (mode === "workouts") { - $render(WORKOUTS · LAST 7D{recent ? recent.activity : "—"}{recent ? `${Math.round(recent.duration/60)} min` : "None shared"}{!small && recent && {[recent.distanceMeters === null ? null : `${(recent.distanceMeters/1000).toFixed(1)} km`,recent.energyKcal === null ? null : `${Math.round(recent.energyKcal)} kcal`].filter(Boolean).join(" · ")}}{workouts?.truncated ? (small ? "More available" : "More results not shown") : small ? "Read-only" : "Apple Health · Read-only"}); + // Workouts: the first one in the list. Its duration is in seconds. + $render( + + + WORKOUTS · LAST 7D + + + + {recent ? recent.activity : "—"} + + + {recent ? `${Math.round(recent.duration / 60)} min` : "None shared"} + + {/* Distance and energy are null when a workout has none; filter(Boolean) drops them. */} + {!small && recent && ( + + {[ + recent.distanceMeters === null + ? null + : `${(recent.distanceMeters / 1000).toFixed(1)} km`, + recent.energyKcal === null ? null : `${Math.round(recent.energyKcal)} kcal`, + ] + .filter(Boolean) + .join(" · ")} + + )} + + + {workouts?.truncated + ? small + ? "More available" + : "More results not shown" + : small + ? "Read-only" + : "Apple Health · Read-only"} + + , + ); } else if (small) { - $render(HEALTH SNAPSHOT{sleepValue}Sleep · last 24h{move ? `Move ${moveValue}` : "No shared activity"}{errors ? "Some data unavailable" : "Apple Health"}); + // Overview, small widget: sleep and move only. + $render( + + + HEALTH SNAPSHOT + + + + {sleepValue} + + + Sleep · last 24h + + + + {move ? `Move ${moveValue}` : "No shared activity"} + + + {errors ? "Some data unavailable" : "Apple Health"} + + , + ); } else if (family === "medium") { - $render(HEALTH SNAPSHOT); + // Overview, medium widget: the rings and three values. + $render( + + + HEALTH SNAPSHOT + + + + + + + + + + + , + ); } else { - $render(Health overview{recent ? `${recent.activity} · ${Math.round(recent.duration/60)} min` : "No shared workouts in 7d"}{errors ? "Some data unavailable" : "Apple Health · Read-only"}); + // Overview, large and extra large widgets. + $render( + + + Health overview + + + + + + + + {recent + ? `${recent.activity} · ${Math.round(recent.duration / 60)} min` + : "No shared workouts in 7d"} + + + + {errors ? "Some data unavailable" : "Apple Health · Read-only"} + + , + ); } diff --git a/Gallery/widgets/hydration-goal-icloud/lib/cloud-hydration.js b/Gallery/widgets/hydration-goal-icloud/lib/cloud-hydration.js index e4362a70..70bc66c4 100644 --- a/Gallery/widgets/hydration-goal-icloud/lib/cloud-hydration.js +++ b/Gallery/widgets/hydration-goal-icloud/lib/cloud-hydration.js @@ -1,68 +1,121 @@ // Add-only cloud log. Keeping each tap as a uniquely identified event makes // two offline devices' additions safe to union when iCloud exposes a fork. +// main.jsx imports this file ("lib/cloud-hydration.js") and then uses +// `cloudHydration`. The log is one JSON document: +// { version: 1, events: [{ id, at, day, ml }] }. var cloudHydration = (() => { + // The name of the document in the connected iCloud Data store, and its limits. const documentName = "hydration.json"; const maximumEvents = 512; const maximumJSONLength = 60 * 1024; - const empty = () => ({version: 1, events: []}); + const empty = () => ({ version: 1, events: [] }); const keys = (value) => Object.keys(value).sort().join(","); - const dayKey = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // Day key in local time, for example "2026-03-08". + const dayKey = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // True for a real calendar date written as YYYY-MM-DD. const validDay = (day) => { if (typeof day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(day)) return false; const parts = day.split("-").map(Number); const date = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], 12)); return parts[0] >= 1970 && date.toISOString().slice(0, 10) === day; }; + // True for a UTC time written like 2026-03-08T12:00:00.000Z. const validTime = (time) => { - if (typeof time !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(time)) return false; + if (typeof time !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(time)) + return false; const date = new Date(time); return !Number.isNaN(date.getTime()) && date.toISOString() === time; }; - const fail = () => { throw new Error("Cloud hydration history is invalid. Keep the existing revisions and repair them before recording more water."); }; + const fail = () => { + throw new Error( + "Cloud hydration history is invalid. Keep the existing revisions and repair them before recording more water.", + ); + }; + // Check a document and return a copy of it. No document yet gives an empty log. function parse(value) { if (value === null || value === undefined) return empty(); - if (!value || Array.isArray(value) || keys(value) !== "events,version" || value.version !== 1 || - !Array.isArray(value.events) || value.events.length > maximumEvents) return fail(); + if ( + !value || + Array.isArray(value) || + keys(value) !== "events,version" || + value.version !== 1 || + !Array.isArray(value.events) || + value.events.length > maximumEvents + ) + return fail(); const ids = new Set(); + // Every event needs a unique 32-digit hex id, a time, a day and 25 to 2000 mL. for (const event of value.events) { - if (!event || Array.isArray(event) || keys(event) !== "at,day,id,ml" || - typeof event.id !== "string" || !/^[0-9a-f]{32}$/.test(event.id) || ids.has(event.id) || - !validTime(event.at) || !validDay(event.day) || - !Number.isInteger(event.ml) || event.ml < 25 || event.ml > 2000) return fail(); + if ( + !event || + Array.isArray(event) || + keys(event) !== "at,day,id,ml" || + typeof event.id !== "string" || + !/^[0-9a-f]{32}$/.test(event.id) || + ids.has(event.id) || + !validTime(event.at) || + !validDay(event.day) || + !Number.isInteger(event.ml) || + event.ml < 25 || + event.ml > 2000 + ) + return fail(); ids.add(event.id); } - return {version: 1, events: value.events.slice()}; + return { version: 1, events: value.events.slice() }; } + // Combine several versions of the log: every event once, sorted by time. + // The same id with different content is an error. function merge(values) { const byID = new Map(); for (const value of values) { for (const event of parse(value).events) { const previous = byID.get(event.id); - if (previous && (previous.at !== event.at || previous.day !== event.day || previous.ml !== event.ml)) return fail(); + if ( + previous && + (previous.at !== event.at || previous.day !== event.day || previous.ml !== event.ml) + ) + return fail(); byID.set(event.id, event); } } - const events = Array.from(byID.values()).sort((a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id)); - const result = {version: 1, events}; + const events = Array.from(byID.values()).sort( + (a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id), + ); + const result = { version: 1, events }; + // The result must stay within the limits: 64000 mL a day, 512 events, 60 KiB of JSON. const totals = new Map(); for (const event of events) { const total = (totals.get(event.day) ?? 0) + event.ml; - if (total > 64000) throw new Error("Conflicting additions exceed the daily record limit. The original revisions are preserved."); + if (total > 64000) + throw new Error( + "Conflicting additions exceed the daily record limit. The original revisions are preserved.", + ); totals.set(event.day, total); } if (events.length > maximumEvents || JSON.stringify(result).length > maximumJSONLength) { - throw new Error("Cloud hydration history is full. Copy its JSON revisions from iCloud Drive before starting a new data store."); + throw new Error( + "Cloud hydration history is full. Copy its JSON revisions from iCloud Drive before starting a new data store.", + ); } return result; } + // Turn what $icloud.readJSON returned into one log. The state is "cached" or "pending" + // with the document in `value`, or "conflict" with the diverging versions in + // `conflicts`; those are merged. function fromSnapshot(snapshot) { if (!snapshot || typeof snapshot.revision !== "string") return fail(); if (snapshot.state === "conflict") { - if (!Array.isArray(snapshot.conflicts) || snapshot.conflicts.length < 2 || - snapshot.conflicts.some((head) => !head || typeof head.id !== "string" || !head.value)) return fail(); + if ( + !Array.isArray(snapshot.conflicts) || + snapshot.conflicts.length < 2 || + snapshot.conflicts.some((head) => !head || typeof head.id !== "string" || !head.value) + ) + return fail(); return merge(snapshot.conflicts.map((head) => head.value)); } if (snapshot.state !== "cached" && snapshot.state !== "pending") return fail(); @@ -70,41 +123,55 @@ var cloudHydration = (() => { return merge([snapshot.value]); } + // A new event id: the time in hex (12 digits) followed by 20 random hex digits. function idFor(date) { const time = date.getTime().toString(16).padStart(12, "0"); - return time + Array.from({length: 20}, () => Math.floor(Math.random() * 16).toString(16)).join(""); + return ( + time + Array.from({ length: 20 }, () => Math.floor(Math.random() * 16).toString(16)).join("") + ); } + // readJSON returns the copy cached on this device: { value, revision, state, conflicts }. async function read() { const snapshot = await $icloud.readJSON(documentName); - return {snapshot, data: fromSnapshot(snapshot)}; + return { snapshot, data: fromSnapshot(snapshot) }; } + // Add one glass of `ml` millilitres: read, append, write. If the document changed in + // the meantime, read again and retry. async function add(ml) { if (!Number.isInteger(ml) || ml < 25 || ml > 2000) throw new Error("Set glassML to 25–2000."); const at = new Date(); - const event = {id: idFor(at), at: at.toISOString(), day: dayKey(at), ml}; + const event = { id: idFor(at), at: at.toISOString(), day: dayKey(at), ml }; for (let attempt = 0; attempt < 3; attempt++) { - const {snapshot, data} = await read(); + const { snapshot, data } = await read(); if (data.events.some((item) => item.id === event.id)) return; - const total = data.events.filter((item) => item.day === event.day).reduce((sum, item) => sum + item.ml, 0); - if (total > 64000 - ml) throw new Error("Today's record limit would be exceeded. Nothing was saved."); - const next = merge([data, {version: 1, events: [event]}]); + const total = data.events + .filter((item) => item.day === event.day) + .reduce((sum, item) => sum + item.ml, 0); + if (total > 64000 - ml) + throw new Error("Today's record limit would be exceeded. Nothing was saved."); + const next = merge([data, { version: 1, events: [event] }]); try { - if (snapshot.state === "conflict") await $icloud.resolveJSON(documentName, next, snapshot.revision); + // A write names the revision it was based on. A conflict has to be settled with + // resolveJSON; writeJSON is rejected while there is one. + if (snapshot.state === "conflict") + await $icloud.resolveJSON(documentName, next, snapshot.revision); else await $icloud.writeJSON(documentName, next, snapshot.revision); return; } catch (error) { + // A stale revision or a new conflict: try again. Any other error ends here. if (!/staleRevision|\[icloud:conflict\]/.test(String(error))) throw error; } } throw new Error("Cloud records changed while saving. Please tap again."); } + // Ask iCloud to exchange data now, then settle a conflict if there is one. async function sync() { await $icloud.sync(); for (let attempt = 0; attempt < 2; attempt++) { - const {snapshot, data} = await read(); + const { snapshot, data } = await read(); if (snapshot.state !== "conflict") return; try { await $icloud.resolveJSON(documentName, data, snapshot.revision); @@ -116,14 +183,24 @@ var cloudHydration = (() => { throw new Error("Cloud records changed while merging. Please sync again."); } + // The last `count` days, oldest first: { day, total, recorded }, with `total` in mL. function recent(data, count = 7, now = new Date()) { - return Array.from({length: count}, (_, index) => { - const date = new Date(now.getFullYear(), now.getMonth(), now.getDate() + index - count + 1, 12); + return Array.from({ length: count }, (_, index) => { + const date = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate() + index - count + 1, + 12, + ); const day = dayKey(date); const events = data.events.filter((event) => event.day === day); - return {day, total: events.reduce((sum, event) => sum + event.ml, 0), recorded: events.length > 0}; + return { + day, + total: events.reduce((sum, event) => sum + event.ml, 0), + recorded: events.length > 0, + }; }); } - return {read, add, sync, recent, dayKey, fromSnapshot}; + return { read, add, sync, recent, dayKey, fromSnapshot }; })(); diff --git a/Gallery/widgets/hydration-goal-icloud/main.jsx b/Gallery/widgets/hydration-goal-icloud/main.jsx index 946fa82c..0b825d7f 100644 --- a/Gallery/widgets/hydration-goal-icloud/main.jsx +++ b/Gallery/widgets/hydration-goal-icloud/main.jsx @@ -1,26 +1,63 @@ // Separate iCloud example. It does not migrate or change Hydration Goal's local records. // Connect this installation to the same iCloud Data store ID on each device. -if (!$import("lib/cloud-hydration.js")) throw new Error("Install the complete template, including lib/cloud-hydration.js."); +// Shows today's water like Hydration Goal, but keeps the log in iCloud so that several +// devices can share it. Try another goal or glass size with the widget parameter. +// The iCloud API runs on iPhone, iPad and Mac, and on Android with a sync folder the user picks +// (it cannot exchange data with an iPhone); not on Windows or Linux. +// widget.json must declare the permission "icloud"; the buttons need its "actions". + +// $import runs another file of this package; lib/cloud-hydration.js defines `cloudHydration`. +// It returns false when the file is missing. +if (!$import("lib/cloud-hydration.js")) + throw new Error("Install the complete template, including lib/cloud-hydration.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); +// The optional widget parameter, JSON such as {"goal":8,"glassML":250}. const parameter = ($getenv("widget-param") || "").trim(); -let options = {goal: 8, glassML: 250}; +let options = { goal: 8, glassML: 250 }; if (parameter) { - try { options = {...options, ...JSON.parse(parameter)}; } - catch (_) { throw new Error('Use a JSON object such as {"goal":8,"glassML":250}.'); } - if (!options || Array.isArray(options) || Object.keys(options).some((key) => !["goal", "glassML"].includes(key))) { + try { + options = { ...options, ...JSON.parse(parameter) }; + } catch (_) { + throw new Error('Use a JSON object such as {"goal":8,"glassML":250}.'); + } + if ( + !options || + Array.isArray(options) || + Object.keys(options).some((key) => !["goal", "glassML"].includes(key)) + ) { throw new Error("Hydration settings accept goal and glassML only."); } } -const {goal, glassML} = options; -if (!Number.isInteger(goal) || goal < 1 || goal > 32 || !Number.isInteger(glassML) || glassML < 25 || glassML > 2000) { +// `goal` is in glasses, `glassML` in millilitres per glass. +const { goal, glassML } = options; +if ( + !Number.isInteger(goal) || + goal < 1 || + goal > 32 || + !Number.isInteger(glassML) || + glassML < 25 || + glassML > 2000 +) { throw new Error("Set goal to 1–32 glasses and glassML to 25–2000."); } -async function addGlass() { await cloudHydration.add(glassML); $render(Glass saved locally; iCloud delivery may follow later); } -async function syncRecords() { await cloudHydration.sync(); $render(Cloud exchange requested; delivery may follow later); } +// The two functions below are named by the "actions" in widget.json; a tap on a - {hint} - {!(["small", "medium"].includes(size)) && Last 7 days · mL{days.map((day) => {day.day.slice(5)}{day.recorded ? String(day.total) : "—"})}} - ); + else if (size === "accessoryCircular") + $render( + + {`${Math.round(progress * 100)}%`} + , + ); + else if (size === "accessoryRectangular") + $render( + + , + ); + else + $render( + + + + {/* Small widget: a progress bar. Other sizes: a ring next to the text. */} + {size === "small" ? ( + + + {label} + + + + ) : ( + + + + {label} + + + )} + + + + + + {hint} + + {/* Large sizes also list the 7 days. day.day.slice(5) is the MM-DD part. */} + {!["small", "medium"].includes(size) && ( + + + Last 7 days · mL + + {days.map((day) => ( + + + {day.day.slice(5)} + + + + {day.recorded ? String(day.total) : "—"} + + + ))} + + )} + , + ); } catch (error) { + // Reading failed, for example because iCloud Data is not connected: say what to do. console.error(String(error)); - $render(Hydration Goal iCloudConnect iCloud Data in ScriptWidget, then sync.{String(error)}); + $render( + + Hydration Goal iCloud + Connect iCloud Data in ScriptWidget, then sync. + {String(error)} + , + ); } } diff --git a/Gallery/widgets/hydration-goal/lib/records.js b/Gallery/widgets/hydration-goal/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Gallery/widgets/hydration-goal/lib/records.js +++ b/Gallery/widgets/hydration-goal/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Gallery/widgets/hydration-goal/main.jsx b/Gallery/widgets/hydration-goal/main.jsx index 019baa73..f9dcf6dc 100644 --- a/Gallery/widgets/hydration-goal/main.jsx +++ b/Gallery/widgets/hydration-goal/main.jsx @@ -1,49 +1,188 @@ // Local hydration log. Optional widget-param: {"goal":8,"glassML":250}. // Legacy current,goal parameters retain the goal only; sample counts are never saved. // Tap to record a glass. Undo restores the most recent change; Reset clears today only. -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); +// Shows today's water against a goal, with buttons to add a glass, undo and reset. +// Try another goal or glass size with the widget parameter, or change the colors. +// Saving needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const parameter = ($getenv("widget-param") || "").trim(); +// The settings saved by Records & Configuration (or the defaults), then the parameter. let options = localRecords.configuration("hydration"); if (parameter.startsWith("{")) { - try { options = {...options, ...JSON.parse(parameter)}; } catch (_) { throw new Error("Use a JSON object for hydration settings."); } - if (!options || Array.isArray(options) || Object.keys(options).some((key) => !["goal", "glassML"].includes(key))) throw new Error("Hydration settings accept goal and glassML only."); + try { + options = { ...options, ...JSON.parse(parameter) }; + } catch (_) { + throw new Error("Use a JSON object for hydration settings."); + } + if ( + !options || + Array.isArray(options) || + Object.keys(options).some((key) => !["goal", "glassML"].includes(key)) + ) + throw new Error("Hydration settings accept goal and glassML only."); } else if (parameter) { + // The older form of the parameter: a number, or "current,goal" where only the goal counts. options.goal = Number(parameter.includes(",") ? parameter.split(",")[1] : parameter); } +// `goal` is in glasses, `glassML` in millilitres per glass. const goal = options.goal === undefined ? 8 : options.goal; const glassML = options.glassML === undefined ? 250 : options.glassML; -if (!Number.isInteger(goal) || goal < 1 || goal > 32 || !Number.isInteger(glassML) || glassML < 25 || glassML > 2000) throw new Error("Set goal to 1–32 glasses and glassML to 25–2000."); +if ( + !Number.isInteger(goal) || + goal < 1 || + goal > 32 || + !Number.isInteger(glassML) || + glassML < 25 || + glassML > 2000 +) + throw new Error("Set goal to 1–32 glasses and glassML to 25–2000."); +// One record per day under the key "hydration.v1": the total of the day in mL. // Store measured millilitres; changing glass size never reinterprets past records. -const log = localRecords.create("hydration.v1", (value) => Number.isInteger(value) && value >= 0 && value <= 64000, 0); +const log = localRecords.create( + "hydration.v1", + (value) => Number.isInteger(value) && value >= 0 && value <= 64000, + 0, +); +// The three functions below are named by the "actions" in widget.json. A tap on a +// ; +// A text to tap. actionID names the action to run. +const Action = ({ name, title }) => ( + +); +// A tap runs this script with the size "function" or "action": draw no widget then. if (size === "function" || size === "action") { // Named handlers alone mutate records. } else if (size === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({`Water · ${label}`}); } else if (size === "accessoryCircular") { - $render({`${Math.round(progress * 100)}%`}); + // Lock Screen, circular: a gauge with the percentage. + $render( + + {`${Math.round(progress * 100)}%`} + , + ); } else if (size === "accessoryRectangular") { - $render(); + // Lock Screen, rectangular: the total and a progress bar. + $render( + + , + ); } else { + // Home Screen sizes. Large ones (`expanded`) also list the last 7 days. const expanded = !["small", "medium"].includes(size); - $render( - - {size === "small" ? {label}{total === 0 ? "Start with a glass" : progress === 1 ? "Goal reached" : "Every glass counts"} : {label}{total === 0 ? "Start with a glass" : progress === 1 ? "Goal reached" : "Every glass counts"}} - {size !== "small" && } - {expanded && Last 7 days · mL{log.recent(state).map((day) => {day.date.slice(5)}{day.recorded ? String(day.value) : "—"})}} - ); + $render( + + {/* log.today is a day key such as 2026-03-08; slice(5) keeps the 03-08 part. */} + + + {/* Small widget: a progress bar. Other sizes: a ring next to the text. */} + {size === "small" ? ( + + + {label} + + + + {total === 0 + ? "Start with a glass" + : progress === 1 + ? "Goal reached" + : "Every glass counts"} + + + ) : ( + + + + + {label} + + + {total === 0 + ? "Start with a glass" + : progress === 1 + ? "Goal reached" + : "Every glass counts"} + + + + )} + {/* The small widget has no room for Reset. */} + + + + {size !== "small" && } + + {expanded && ( + + + Last 7 days · mL + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? String(day.value) : "—"} + + + ))} + + )} + , + ); } diff --git a/Gallery/widgets/layout-starter/main.jsx b/Gallery/widgets/layout-starter/main.jsx index c0e7a93d..4d3714da 100644 --- a/Gallery/widgets/layout-starter/main.jsx +++ b/Gallery/widgets/layout-starter/main.jsx @@ -1,13 +1,26 @@ // Open Layout in the editor to select, edit, add and move these layers. // Code remains the source of truth. This template needs no permissions. +// A plain card: an icon and a short line at the top, two lines of text at the bottom. +// Try changing the texts and the colors. + +// $render draws the widget. frame="max" fills the whole widget, alignment="leading" +// lines the children up on the left, and padding is the space in points around them. $render( + {/* places its children side by side, one below the other. */} - - A fresh start + + + A fresh start + - - Make today yours - A little space for your ideas. - + {/* takes all free space, which pushes the two texts to the bottom. */} + + + Make today yours + + + A little space for your ideas. + + , ); diff --git a/Gallery/widgets/local-weather/lib/weather.js b/Gallery/widgets/local-weather/lib/weather.js index 397b0829..bd6e6cdb 100644 --- a/Gallery/widgets/local-weather/lib/weather.js +++ b/Gallery/widgets/local-weather/lib/weather.js @@ -1,204 +1,527 @@ // MET Norway Locationforecast 2.0. Forecasts are model data, not observations. // https://api.met.no/doc/TermsOfService · https://api.met.no/doc/License +// main.jsx imports this file ("lib/weather.js") and then uses `localWeather`. +// It chooses the place, asks MET Norway for its forecast and keeps a copy in $storage. var localWeather = (() => { - const cacheKey = "weather.met.v1", hour = 3600000; - const defaults = {city:"",latitude:0,longitude:0,useLocation:true,unit:"c"}; - const numeric = (value,min,max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; - const keys = object => object && typeof object === "object" && !Array.isArray(object) ? Object.keys(object).sort().join(",") : ""; + // The storage key of the saved forecasts, and one hour in milliseconds. + const cacheKey = "weather.met.v1", + hour = 3600000; + // The settings. `unit` is "c" or "f"; `city` with its coordinates is the saved city. + const defaults = { city: "", latitude: 0, longitude: 0, useLocation: true, unit: "c" }; + // True for a real number between min and max. + const numeric = (value, min, max) => + typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; + // The keys of a plain object, sorted and joined ("a,b,c"); "" for anything else. + const keys = (object) => + object && typeof object === "object" && !Array.isArray(object) + ? Object.keys(object).sort().join(",") + : ""; function validOptions(value) { - return keys(value) === "city,latitude,longitude,unit,useLocation" && typeof value.city === "string" && value.city.length <= 60 && - numeric(value.latitude,-90,90) && numeric(value.longitude,-180,180) && typeof value.useLocation === "boolean" && ["c","f"].includes(value.unit); + return ( + keys(value) === "city,latitude,longitude,unit,useLocation" && + typeof value.city === "string" && + value.city.length <= 60 && + numeric(value.latitude, -90, 90) && + numeric(value.longitude, -180, 180) && + typeof value.useLocation === "boolean" && + ["c", "f"].includes(value.unit) + ); } - function options(raw,parameter) { - let value = {...defaults}; + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter: JSON, or latitude,longitude,City. + function options(raw, parameter) { + let value = { ...defaults }; if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || keys(state) !== "kind,values,version" || state.version !== 1 || state.kind !== "weather" || !validOptions(state.values)) throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); + } + if ( + typeof raw !== "string" || + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. + unescape(encodeURIComponent(raw)).length > 4096 || + keys(state) !== "kind,values,version" || + state.version !== 1 || + state.kind !== "weather" || + !validOptions(state.values) + ) + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); value = state.values; } parameter = (parameter || "").trim(); if (parameter) { if (parameter[0] === "{") { let custom; - try { custom = JSON.parse(parameter); } catch (_) { throw new Error("Weather parameters must be valid JSON."); } - if (!custom || Array.isArray(custom) || Object.keys(custom).some(key => !Object.prototype.hasOwnProperty.call(defaults,key))) throw new Error("Weather settings accept city, latitude, longitude, useLocation and unit only."); - value = {...value,...custom}; + try { + custom = JSON.parse(parameter); + } catch (_) { + throw new Error("Weather parameters must be valid JSON."); + } + if ( + !custom || + Array.isArray(custom) || + Object.keys(custom).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error( + "Weather settings accept city, latitude, longitude, useLocation and unit only.", + ); + value = { ...value, ...custom }; } else { - const parts = parameter.split(",").map(value => value.trim()); - if (parts.length < 2 || parts.length > 3 || parts.slice(0,2).some(value => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value))) throw new Error("Use latitude,longitude or JSON weather settings."); - value = {...value,city:parts[2] || "Selected city",latitude:Number(parts[0]),longitude:Number(parts[1]),useLocation:false}; + // latitude,longitude with an optional city name. A fixed place turns location off. + const parts = parameter.split(",").map((value) => value.trim()); + if ( + parts.length < 2 || + parts.length > 3 || + parts.slice(0, 2).some((value) => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) + ) + throw new Error("Use latitude,longitude or JSON weather settings."); + value = { + ...value, + city: parts[2] || "Selected city", + latitude: Number(parts[0]), + longitude: Number(parts[1]), + useLocation: false, + }; } } - if (!validOptions(value)) throw new Error("Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit."); + if (!validOptions(value)) + throw new Error( + "Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit.", + ); return value; } - const rounded = value => Number(value.toFixed(2)); - const placeKey = (source,latitude,longitude) => `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; - const validHTTPDate = value => typeof value === "string" && /^[A-Za-z0-9,: -]{1,128}$/.test(value) && Number.isFinite(Date.parse(value)); + // Coordinates are rounded to 2 decimals, roughly a kilometre, before use. + const rounded = (value) => Number(value.toFixed(2)); + // The name of a place in the saved copy, such as "manual:59.91,10.75". + const placeKey = (source, latitude, longitude) => + `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; + const validHTTPDate = (value) => + typeof value === "string" && + /^[A-Za-z0-9,: -]{1,128}$/.test(value) && + Number.isFinite(Date.parse(value)); + // One forecast point: time (ms), temperature (°C), humidity (%), wind (m/s), symbol code. function validPoint(point) { - return keys(point) === "humidity,symbol,temperature,time,wind" && Number.isSafeInteger(point.time) && point.time > 0 && - numeric(point.temperature,-100,70) && (point.humidity === null || numeric(point.humidity,0,100)) && - (point.wind === null || numeric(point.wind,0,160)) && typeof point.symbol === "string" && /^[a-z_]{1,64}$/.test(point.symbol); + return ( + keys(point) === "humidity,symbol,temperature,time,wind" && + Number.isSafeInteger(point.time) && + point.time > 0 && + numeric(point.temperature, -100, 70) && + (point.humidity === null || numeric(point.humidity, 0, 100)) && + (point.wind === null || numeric(point.wind, 0, 160)) && + typeof point.symbol === "string" && + /^[a-z_]{1,64}$/.test(point.symbol) + ); } - function validPlaceKey(key,source) { + function validPlaceKey(key, source) { if (typeof key !== "string") return false; const match = /^(manual|location):(-?\d{1,3}\.\d{2}),(-?\d{1,3}\.\d{2})$/.exec(key); - return !!match && match[1] === source && numeric(Number(match[2]),-90,90) && numeric(Number(match[3]),-180,180); + return ( + !!match && + match[1] === source && + numeric(Number(match[2]), -90, 90) && + numeric(Number(match[3]), -180, 180) + ); } - function packets(raw,now) { + // Read the saved copy: up to 4 places with up to 24 forecast points each. + // Anything unexpected gives an empty list, so a damaged copy is simply loaded again. + function packets(raw, now) { try { if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 64000) return []; const state = JSON.parse(raw); - if (keys(state) !== "entries,version" || state.version !== 1 || !Array.isArray(state.entries) || state.entries.length > 4) return []; + if ( + keys(state) !== "entries,version" || + state.version !== 1 || + !Array.isArray(state.entries) || + state.entries.length > 4 + ) + return []; const names = new Set(); for (const entry of state.entries) { - if (keys(entry) !== "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || - !["manual","location"].includes(entry.source) || !validPlaceKey(entry.key,entry.source) || names.has(entry.key) || - !Number.isSafeInteger(entry.checkedAt) || entry.checkedAt < 0 || entry.checkedAt > now+300000 || - !Number.isSafeInteger(entry.nextRequestAt) || entry.nextRequestAt < entry.checkedAt || entry.nextRequestAt > entry.checkedAt+7*24*hour || - !Number.isSafeInteger(entry.updatedAt) || entry.updatedAt < 0 || entry.updatedAt > now+300000 || - typeof entry.failed !== "boolean" || typeof entry.deprecated !== "boolean" || - (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || !Array.isArray(entry.points) || entry.points.length > 24 || - !entry.points.every(validPoint) || entry.points.some((point,index) => index > 0 && point.time <= entry.points[index-1].time) || - (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0)) return []; + if ( + keys(entry) !== + "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || + !["manual", "location"].includes(entry.source) || + !validPlaceKey(entry.key, entry.source) || + names.has(entry.key) || + !Number.isSafeInteger(entry.checkedAt) || + entry.checkedAt < 0 || + entry.checkedAt > now + 300000 || + !Number.isSafeInteger(entry.nextRequestAt) || + entry.nextRequestAt < entry.checkedAt || + entry.nextRequestAt > entry.checkedAt + 7 * 24 * hour || + !Number.isSafeInteger(entry.updatedAt) || + entry.updatedAt < 0 || + entry.updatedAt > now + 300000 || + typeof entry.failed !== "boolean" || + typeof entry.deprecated !== "boolean" || + (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || + !Array.isArray(entry.points) || + entry.points.length > 24 || + !entry.points.every(validPoint) || + entry.points.some( + (point, index) => index > 0 && point.time <= entry.points[index - 1].time, + ) || + (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0) + ) + return []; names.add(entry.key); } return state.entries; - } catch (_) { return []; } + } catch (_) { + return []; + } } - function publish(packet,now,projection) { + // Save the forecast of one place next to the others; only one place found by location + // is kept. compareAndSetString writes only if the stored text is still `raw`; if + // something else saved in between, read again and retry. + function publish(packet, now, projection) { if (projection) return false; - for (let attempt=0;attempt<4;attempt++) { - const raw = $storage.getString(cacheKey), entries = packets(raw,now); - const previous = entries.find(entry => entry.key === packet.key); - if (previous && (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt)) return true; - const next = [packet,...entries.filter(entry => entry.key !== packet.key && (packet.source !== "location" || entry.source !== "location"))].sort((a,b) => b.checkedAt-a.checkedAt).slice(0,4); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:next}))) return true; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + entries = packets(raw, now); + const previous = entries.find((entry) => entry.key === packet.key); + if ( + previous && + (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt) + ) + return true; + const next = [ + packet, + ...entries.filter( + (entry) => + entry.key !== packet.key && + (packet.source !== "location" || entry.source !== "location"), + ), + ] + .sort((a, b) => b.checkedAt - a.checkedAt) + .slice(0, 4); + if ( + $storage.compareAndSetString(cacheKey, raw, JSON.stringify({ version: 1, entries: next })) + ) + return true; } return false; } - function expires(headers,now) { + // When to ask again: when the response expires (Expires, else Cache-Control max-age), + // or in one hour without a usable time. Never sooner than 15 minutes, plus up to 5 + // random minutes. + function expires(headers, now) { let until = Date.parse(headers.expires || ""); const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"] || ""); - if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]),604800)*1000; - if (!Number.isFinite(until) || until > now+7*24*hour) until = now+hour; - return Math.round(Math.max(now+900000,until)+Math.random()*300000); + if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]), 604800) * 1000; + if (!Number.isFinite(until) || until > now + 7 * 24 * hour) until = now + hour; + return Math.round(Math.max(now + 900000, until) + Math.random() * 300000); } - function parseResponse(body,place,now,headers,status) { - if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) throw new Error("Invalid forecast"); - const data = JSON.parse(body), meta = data?.properties?.meta, times = data?.properties?.timeseries; + // Check the answer of MET Norway and keep up to 24 points, starting 2 hours ago. + function parseResponse(body, place, now, headers, status) { + if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) + throw new Error("Invalid forecast"); + const data = JSON.parse(body), + meta = data?.properties?.meta, + times = data?.properties?.timeseries; const updatedAt = Date.parse(meta?.updated_at || ""); - if (!Number.isFinite(updatedAt) || updatedAt > now+300000 || now-updatedAt > 24*hour || meta?.units?.air_temperature !== "celsius" || meta?.units?.wind_speed !== "m/s" || !Array.isArray(times) || times.length < 1 || times.length > 250) throw new Error("Invalid forecast"); + if ( + !Number.isFinite(updatedAt) || + updatedAt > now + 300000 || + now - updatedAt > 24 * hour || + meta?.units?.air_temperature !== "celsius" || + meta?.units?.wind_speed !== "m/s" || + !Array.isArray(times) || + times.length < 1 || + times.length > 250 + ) + throw new Error("Invalid forecast"); const points = []; for (const item of times) { const time = Date.parse(item?.time || ""); if (!Number.isFinite(time)) throw new Error("Invalid forecast time"); - if (time < now-2*hour || points.length >= 24) continue; - const details = item?.data?.instant?.details, summary = item?.data?.next_1_hours?.summary || item?.data?.next_6_hours?.summary || item?.data?.next_12_hours?.summary; - const point = {time,temperature:details?.air_temperature,humidity:meta.units.relative_humidity === "%" && numeric(details?.relative_humidity,0,100) ? details.relative_humidity : null, - wind:numeric(details?.wind_speed,0,160) ? details.wind_speed : null,symbol:summary?.symbol_code || "unknown"}; - if (!validPoint(point) || (points.length && time <= points[points.length-1].time)) throw new Error("Invalid forecast point"); + if (time < now - 2 * hour || points.length >= 24) continue; + const details = item?.data?.instant?.details, + summary = + item?.data?.next_1_hours?.summary || + item?.data?.next_6_hours?.summary || + item?.data?.next_12_hours?.summary; + const point = { + time, + temperature: details?.air_temperature, + humidity: + meta.units.relative_humidity === "%" && numeric(details?.relative_humidity, 0, 100) + ? details.relative_humidity + : null, + wind: numeric(details?.wind_speed, 0, 160) ? details.wind_speed : null, + symbol: summary?.symbol_code || "unknown", + }; + if (!validPoint(point) || (points.length && time <= points[points.length - 1].time)) + throw new Error("Invalid forecast point"); points.push(point); } - if (!points.some(point=>Math.abs(point.time-now)<=90*60000)) throw new Error("Forecast is unavailable"); - return {key:place.key,source:place.source,updatedAt,checkedAt:now,nextRequestAt:expires(headers,now), - lastModified:validHTTPDate(headers["last-modified"]) && Date.parse(headers["last-modified"]) <= now+300000 ? headers["last-modified"] : "",points,failed:false,deprecated:status===203}; + // One of the points must lie within 90 minutes of now. + if (!points.some((point) => Math.abs(point.time - now) <= 90 * 60000)) + throw new Error("Forecast is unavailable"); + // Status 203 is how MET Norway announces that this version of the service will end. + return { + key: place.key, + source: place.source, + updatedAt, + checkedAt: now, + nextRequestAt: expires(headers, now), + lastModified: + validHTTPDate(headers["last-modified"]) && + Date.parse(headers["last-modified"]) <= now + 300000 + ? headers["last-modified"] + : "", + points, + failed: false, + deprecated: status === 203, + }; } - function pointAt(packet,now) { - if (!packet || !packet.points.length || now-packet.updatedAt > 24*hour || packet.updatedAt > now+300000) return null; - const earlier = packet.points.filter(point => point.time <= now); - const point = earlier[earlier.length-1] || packet.points[0]; - return Math.abs(point.time-now) <= 90*60000 ? point : null; + // The forecast point for now: the latest one that is not in the future, provided it is + // within 90 minutes of now and the forecast is less than a day old. + function pointAt(packet, now) { + if ( + !packet || + !packet.points.length || + now - packet.updatedAt > 24 * hour || + packet.updatedAt > now + 300000 + ) + return null; + const earlier = packet.points.filter((point) => point.time <= now); + const point = earlier[earlier.length - 1] || packet.points[0]; + return Math.abs(point.time - now) <= 90 * 60000 ? point : null; } + // Turn a symbol code such as "partlycloudy_night" into a title and an SF Symbol name. function condition(symbol) { const night = symbol.endsWith("_night"); - if (symbol.includes("thunder")) return {title:"Thunderstorms",icon:"cloud.bolt.rain.fill"}; - if (symbol.includes("snow") || symbol.includes("sleet")) return {title:"Snow or sleet",icon:"cloud.snow.fill"}; - if (symbol.includes("rain")) return {title:"Rain",icon:"cloud.rain.fill"}; - if (symbol.includes("fog")) return {title:"Fog",icon:"cloud.fog.fill"}; - if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) return {title:"Partly cloudy",icon:night ? "cloud.moon.fill" : "cloud.sun.fill"}; - if (symbol.startsWith("clearsky")) return {title:"Clear",icon:night ? "moon.stars.fill" : "sun.max.fill"}; - if (symbol.startsWith("cloudy")) return {title:"Cloudy",icon:"cloud.fill"}; - return {title:"Forecast",icon:"cloud.fill"}; + if (symbol.includes("thunder")) return { title: "Thunderstorms", icon: "cloud.bolt.rain.fill" }; + if (symbol.includes("snow") || symbol.includes("sleet")) + return { title: "Snow or sleet", icon: "cloud.snow.fill" }; + if (symbol.includes("rain")) return { title: "Rain", icon: "cloud.rain.fill" }; + if (symbol.includes("fog")) return { title: "Fog", icon: "cloud.fog.fill" }; + if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) + return { title: "Partly cloudy", icon: night ? "cloud.moon.fill" : "cloud.sun.fill" }; + if (symbol.startsWith("clearsky")) + return { title: "Clear", icon: night ? "moon.stars.fill" : "sun.max.fill" }; + if (symbol.startsWith("cloudy")) return { title: "Cloudy", icon: "cloud.fill" }; + return { title: "Forecast", icon: "cloud.fill" }; } - const locationAllowed = () => $location.isAvailable() && ["authorizedWhenInUse","authorizedAlways"].includes($location.authorizationStatus()) && $location.isAuthorizedForWidgetUpdates(); - function clearLocationCache(now,projection) { + // True when location exists here, the app may use it and widgets may use it too. + const locationAllowed = () => + $location.isAvailable() && + ["authorizedWhenInUse", "authorizedAlways"].includes($location.authorizationStatus()) && + $location.isAuthorizedForWidgetUpdates(); + // Forget the forecast saved for a location once location is no longer allowed. + function clearLocationCache(now, projection) { if (projection) return; - for (let attempt=0;attempt<4;attempt++) { - const raw=$storage.getString(cacheKey), filtered=packets(raw,now).filter(entry=>entry.source!=="location"); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:filtered}))) return; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + filtered = packets(raw, now).filter((entry) => entry.source !== "location"); + if ( + $storage.compareAndSetString( + cacheKey, + raw, + JSON.stringify({ version: 1, entries: filtered }), + ) + ) + return; } } - async function revoked(config,now,projection) { - clearLocationCache(now,projection); - return config.city.trim() ? await load({...config,useLocation:false},now,projection) : {available:false,title:"Location access changed",hint:"Choose a saved city to continue."}; + // Location was allowed and no longer is: use the saved city, if there is one. + async function revoked(config, now, projection) { + clearLocationCache(now, projection); + return config.city.trim() + ? await load({ ...config, useLocation: false }, now, projection) + : { + available: false, + title: "Location access changed", + hint: "Choose a saved city to continue.", + }; } - async function load(config,now,projection) { - let entries = packets($storage.getString(cacheKey),now); + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which asks neither for the position + // nor for a new forecast. + async function load(config, now, projection) { + let entries = packets($storage.getString(cacheKey), now); const authorized = locationAllowed(); - if (!authorized && entries.some(entry => entry.source === "location")) { - entries = entries.filter(entry => entry.source !== "location"); - clearLocationCache(now,projection); + if (!authorized && entries.some((entry) => entry.source === "location")) { + entries = entries.filter((entry) => entry.source !== "location"); + clearLocationCache(now, projection); } + // Choose the place: the current position, else the last saved one, else the city. let place = null; if (config.useLocation && authorized) { if (!projection) { try { - const location = await $location.current({maxAge:3600}); - const stale = location.isStale === true || (typeof location.age === "number" && location.age > 3600); - if (!stale && numeric(location.latitude,-90,90) && numeric(location.longitude,-180,180)) place = {source:"location",name:location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area",latitude:rounded(location.latitude),longitude:rounded(location.longitude)}; + // maxAge: 3600 accepts a position up to one hour old; `age` is in seconds. + const location = await $location.current({ maxAge: 3600 }); + const stale = + location.isStale === true || (typeof location.age === "number" && location.age > 3600); + if ( + !stale && + numeric(location.latitude, -90, 90) && + numeric(location.longitude, -180, 180) + ) + place = { + source: "location", + name: + location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area", + latitude: rounded(location.latitude), + longitude: rounded(location.longitude), + }; } catch (_) {} } if (!place && (!config.city.trim() || projection)) { - const saved = entries.find(entry => entry.source === "location" && pointAt(entry,now)); - if (saved) place = {source:"location",name:"Last location",key:saved.key,skipNetwork:true}; + const saved = entries.find((entry) => entry.source === "location" && pointAt(entry, now)); + if (saved) + place = { source: "location", name: "Last location", key: saved.key, skipNetwork: true }; } } - if (!place && config.city.trim()) place = {source:"manual",name:config.city,latitude:rounded(config.latitude),longitude:rounded(config.longitude)}; - if (!place) return {available:false,title:"Choose a saved city",hint:"Open Records & Configuration. Location is optional."}; - place.key ??= placeKey(place.source,place.latitude,place.longitude); + if (!place && config.city.trim()) + place = { + source: "manual", + name: config.city, + latitude: rounded(config.latitude), + longitude: rounded(config.longitude), + }; + if (!place) + return { + available: false, + title: "Choose a saved city", + hint: "Open Records & Configuration. Location is optional.", + }; + place.key ??= placeKey(place.source, place.latitude, place.longitude); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } - let packet = entries.find(entry => entry.key === place.key), saved = true, fromCache = true; + let packet = entries.find((entry) => entry.key === place.key), + saved = true, + fromCache = true; + // Ask MET Norway only when there is no saved forecast for the place or it is due. if (!projection && !place.skipNetwork && (!packet || now >= packet.nextRequestAt)) { try { - const headers = {"User-Agent":"ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)","Accept":"application/json"}; + const headers = { + "User-Agent": "ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)", + Accept: "application/json", + }; if (packet?.lastModified) headers["If-Modified-Since"] = packet.lastModified; - const response = await $http.getResponse(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`,{headers,timeoutInterval:4}); + // The call resolves to { status, body, headers }, also for statuses such as 304. + const response = await $http.getResponse( + `https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`, + { headers, timeoutInterval: 4 }, + ); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } const responseHeaders = response.headers || {}; - if (response.status === 304 && pointAt(packet,now)) packet = {...packet,checkedAt:now,nextRequestAt:expires(responseHeaders,now),failed:false}; - else if (response.status === 200 || response.status === 203) { packet = parseResponse(response.body,place,now,responseHeaders,response.status);fromCache=false; } - else { + // 304: not changed since the last request, so the saved points stay. + if (response.status === 304 && pointAt(packet, now)) + packet = { + ...packet, + checkedAt: now, + nextRequestAt: expires(responseHeaders, now), + failed: false, + }; + else if (response.status === 200 || response.status === 203) { + packet = parseResponse(response.body, place, now, responseHeaders, response.status); + fromCache = false; + } else { + // Another status: retry at the Retry-After time, 15 minutes to 24 hours from now. const retry = responseHeaders["retry-after"] || ""; - let until = /^\d+$/.test(retry) ? now+Number(retry)*1000 : Date.parse(retry); - if (!Number.isFinite(until)) until = now+900000; - const error = new Error("Refresh unavailable");error.retryAt=Math.min(now+24*hour,Math.max(now+900000,until));throw error; + let until = /^\d+$/.test(retry) ? now + Number(retry) * 1000 : Date.parse(retry); + if (!Number.isFinite(until)) until = now + 900000; + const error = new Error("Refresh unavailable"); + error.retryAt = Math.min(now + 24 * hour, Math.max(now + 900000, until)); + throw error; } - saved = publish(packet,now,projection); + saved = publish(packet, now, projection); } catch (error) { - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const retryAt = numeric(error?.retryAt,now,now+24*hour) ? error.retryAt : now+900000; - packet = packet || {key:place.key,source:place.source,updatedAt:0,lastModified:"",points:[],deprecated:false}; - packet = {...packet,checkedAt:now,nextRequestAt:Math.round(retryAt),failed:true}; - saved = publish(packet,now,projection); + // No usable answer: keep the saved points and note the failure. + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const retryAt = numeric(error?.retryAt, now, now + 24 * hour) + ? error.retryAt + : now + 900000; + packet = packet || { + key: place.key, + source: place.source, + updatedAt: 0, + lastModified: "", + points: [], + deprecated: false, + }; + packet = { ...packet, checkedAt: now, nextRequestAt: Math.round(retryAt), failed: true }; + saved = publish(packet, now, projection); } } - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const point = pointAt(packet,now); - if (!point) return {available:false,title:"Forecast unavailable",hint:"Check your connection or saved city, then refresh."}; - const celsius = config.unit === "c", temperature = value => Math.round(celsius ? value : value*9/5+32) + (celsius ? "°C" : "°F"); - const age = Math.max(0,Math.floor((now-packet.updatedAt)/60000)); - const statusText = packet.deprecated ? "Service update needed" : !saved ? "Cache unavailable" : packet.failed ? "Saved forecast · refresh unavailable" : place.skipNetwork ? "Saved forecast · last location" : fromCache ? "Saved forecast" : "Forecast"; - const statusShort = packet.deprecated ? "Service update" : !saved ? "No cache" : packet.failed ? "Saved · refresh failed" : place.skipNetwork ? "Last location" : fromCache ? "Saved forecast" : "Forecast"; - return {available:true,statusShort,name:place.name,source:place.source,condition:condition(point.symbol),temperature:temperature(point.temperature), - humidity:point.humidity === null ? "—" : Math.round(point.humidity)+"%",wind:point.wind === null ? "—" : (point.wind*3.6).toFixed(1)+" km/h", - updated:age < 1 ? "Updated just now" : age < 60 ? `Updated ${age}m ago` : `Updated ${Math.floor(age/60)}h ago`,status:statusText, - upcoming:packet.points.filter(value => value.time > point.time).slice(0,4).map(value => ({label:"+"+Math.max(1,Math.round((value.time-now)/hour))+"h",temperature:temperature(value.temperature),condition:condition(value.symbol)}))}; + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const point = pointAt(packet, now); + if (!point) + return { + available: false, + title: "Forecast unavailable", + hint: "Check your connection or saved city, then refresh.", + }; + // Temperatures are saved in °C and converted for display. + const celsius = config.unit === "c", + temperature = (value) => + Math.round(celsius ? value : (value * 9) / 5 + 32) + (celsius ? "°C" : "°F"); + // Minutes since MET Norway updated the forecast. + const age = Math.max(0, Math.floor((now - packet.updatedAt) / 60000)); + const statusText = packet.deprecated + ? "Service update needed" + : !saved + ? "Cache unavailable" + : packet.failed + ? "Saved forecast · refresh unavailable" + : place.skipNetwork + ? "Saved forecast · last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + const statusShort = packet.deprecated + ? "Service update" + : !saved + ? "No cache" + : packet.failed + ? "Saved · refresh failed" + : place.skipNetwork + ? "Last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + // The result for main.jsx. Wind is converted from m/s to km/h (× 3.6). + // `upcoming` holds the next 4 points, with labels such as "+3h". + return { + available: true, + statusShort, + name: place.name, + source: place.source, + condition: condition(point.symbol), + temperature: temperature(point.temperature), + humidity: point.humidity === null ? "—" : Math.round(point.humidity) + "%", + wind: point.wind === null ? "—" : (point.wind * 3.6).toFixed(1) + " km/h", + updated: + age < 1 + ? "Updated just now" + : age < 60 + ? `Updated ${age}m ago` + : `Updated ${Math.floor(age / 60)}h ago`, + status: statusText, + upcoming: packet.points + .filter((value) => value.time > point.time) + .slice(0, 4) + .map((value) => ({ + label: "+" + Math.max(1, Math.round((value.time - now) / hour)) + "h", + temperature: temperature(value.temperature), + condition: condition(value.symbol), + })), + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Gallery/widgets/local-weather/main.jsx b/Gallery/widgets/local-weather/main.jsx index eefd33f5..c6f5cff6 100644 --- a/Gallery/widgets/local-weather/main.jsx +++ b/Gallery/widgets/local-weather/main.jsx @@ -2,25 +2,189 @@ // Optional instance parameter: latitude,longitude,City or JSON weather settings. // Forecast data: MET Norway (CC BY 4.0). No API key; Expires/conditional requests // and a bounded four-place cache reduce traffic. No exact refresh guarantee. -if (!$import("lib/weather.js")) throw new Error("Install the complete weather template, including lib/weather.js."); -const config = localWeather.options($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); -const weather = await localWeather.load(config,Date.now(),$getenv("timeline-is-projection") === "true"); -const size = $getenv("widget-size"), compact = size === "small"; +// Shows the forecast for where you are, or for a saved city, in every widget size. +// Try the widget parameter: 59.91,10.75,Oslo or {"unit":"f"}. +// The Location API runs on iPhone and iPad, and on Android (widgets see the position +// saved while the app was open); not on Mac, Windows or Linux. There the saved city is +// used. widget.json must declare the permissions "location", "storage" and "network", +// with the host api.met.no. + +// $import runs another file of this package; lib/weather.js defines `localWeather`. +// It returns false when the file is missing. +if (!$import("lib/weather.js")) + throw new Error("Install the complete weather template, including lib/weather.js."); +// The settings: defaults, then what the app saved in $storage, then the widget parameter +// ($getenv("widget-param"), a text you set on each widget you place). +const config = localWeather.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Read the forecast: from MET Norway when the saved copy is due for a refresh, else from +// $storage. "timeline-is-projection" is "true" when the script runs for a future timeline +// entry; no request is made then. +const weather = await localWeather.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +const size = $getenv("widget-size"), + compact = size === "small"; +// No forecast: show the reason in a form that fits the size. if (!weather.available) { if (size === "accessoryInline") $render({weather.title}); - else if (size === "accessoryCircular") $render(); - else if (size === "accessoryRectangular") $render({weather.title}Open ScriptWidget to configure weather.); - else $render({weather.title}{weather.hint}); + else if (size === "accessoryCircular") $render(); + else if (size === "accessoryRectangular") + $render( + + {weather.title} + Open ScriptWidget to configure weather. + , + ); + else + $render( + + + + {weather.title} + + + {weather.hint} + + , + ); } else if (size === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({weather.temperature + " · " + weather.condition.title}); } else if (size === "accessoryCircular") { - $render({weather.temperature}); + // Lock Screen, circular: an icon and the temperature. + $render( + + + + {weather.temperature} + + , + ); } else if (size === "accessoryRectangular") { - $render({weather.name + " · " + weather.temperature}{weather.condition.title}); + // Lock Screen, rectangular: place, temperature and condition. + $render( + + + + {weather.name + " · " + weather.temperature} + {weather.condition.title} + + , + ); } else if (compact) { - $render({Array.from(weather.name).slice(0,12).join("")}{weather.temperature}{weather.condition.title}{weather.statusShort}{weather.updated}MET Norway); + // Small widget. Array.from(name).slice(0, 12) keeps the first 12 characters of the name. + $render( + + + {Array.from(weather.name).slice(0, 12).join("")} + + + + {weather.temperature} + + + + + + {weather.condition.title} + + + {weather.statusShort} + + + {weather.updated} + + + MET Norway + + , + ); } else if (size === "medium") { - $render({weather.name}{weather.condition.title}{weather.temperature}{weather.updated}MET Norway{weather.status}); + // Medium widget: icon, place and temperature in one row. + $render( + + + + + + {weather.name} + + + {weather.condition.title} + + + + + {weather.temperature} + + + + + {weather.updated} + + + + MET Norway + + + + {weather.status} + + , + ); } else { - $render({weather.name}{weather.condition.title}{weather.temperature}{"Wind " + weather.wind}{"Humidity " + weather.humidity}{weather.upcoming.map(point => {point.label}{point.temperature})}{weather.status + " · " + weather.updated}MET Norway · CC BY 4.0); + // Large and extra large widgets: also wind, humidity and the next forecast points. + $render( + + + + + {weather.name} + + + {weather.condition.title} + + + + + + + {weather.temperature} + + + + {"Wind " + weather.wind} + + + + {"Humidity " + weather.humidity} + + + + {weather.upcoming.map((point) => ( + + + {point.label} + + + + {point.temperature} + + + ))} + + + {weather.status + " · " + weather.updated} + + + MET Norway · CC BY 4.0 + + , + ); } diff --git a/Gallery/widgets/material-study/main.jsx b/Gallery/widgets/material-study/main.jsx index f604d3a3..da83736b 100644 --- a/Gallery/widgets/material-study/main.jsx +++ b/Gallery/widgets/material-study/main.jsx @@ -1,24 +1,46 @@ // Public SwiftUI material blurs these shapes inside the widget, not the wallpaper. // The system supplies Clear/Tinted backgrounds. No timer or private animation. +// Shows a frosted card over two colored shapes. Try another backgroundMaterial: +// ultraThin, thin, regular, thick or ultraThick. + +// $device.isdarkmode() is true when the system uses the dark appearance. const dark = $device.isdarkmode(); +// The size being drawn. The Lock Screen sizes start with "accessory". const family = $getenv("widget-size"); +// "fullColor", "accented" or "vibrant". The colored shapes are hidden unless it is fullColor. const fullColor = ($getenv("widget-rendering-mode") || "fullColor") === "fullColor"; const ink = dark ? "#EFFAF5" : "#1C4C39"; const muted = dark ? "#C2DCD0" : "#4E7764"; if (family.startsWith("accessory")) { - $render({family === "accessoryCircular" ? "Calm" : "A little calm"}); + // Lock Screen: text only. + $render( + + {family === "accessoryCircular" ? "Calm" : "A little calm"} + , + ); } else { $render( + {/* The shapes behind the card. rotation3d="12,0,1,0" tilts them 12 degrees on the y axis. */} - - + + - - A little calm - Your own quiet corner. + {/* The card. `background` is what shows when Reduce Transparency is turned on. */} + + + A little calm + + + Your own quiet corner. + - + , ); } diff --git a/Gallery/widgets/mood-check-in/lib/records.js b/Gallery/widgets/mood-check-in/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Gallery/widgets/mood-check-in/lib/records.js +++ b/Gallery/widgets/mood-check-in/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Gallery/widgets/mood-check-in/main.jsx b/Gallery/widgets/mood-check-in/main.jsx index 8f0eae14..dc64f0b8 100644 --- a/Gallery/widgets/mood-check-in/main.jsx +++ b/Gallery/widgets/mood-check-in/main.jsx @@ -1,43 +1,171 @@ // Choose a mood to save today's entry. Render/refresh never checks in automatically. // Optional widget-param: an intention, or {"intention":"Take a pause"} (up to 80 characters). -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); -const size = $getenv("widget-size"), parameter = ($getenv("widget-param") || "").trim(); +// Shows five faces to tap, today's mood and the last 7 days. +// Try other faces and names in `moods` and `names`, or change the colors. +// Saving needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. +const size = $getenv("widget-size"), + parameter = ($getenv("widget-param") || "").trim(); +// The intention line: the parameter, else the one saved by Records & Configuration. let intention = parameter || localRecords.configuration("mood").intention; if (parameter.startsWith("{")) { let config; - try { config = JSON.parse(parameter); } catch (_) { throw new Error("Use a JSON object or a short intention."); } - if (!config || Array.isArray(config) || Object.keys(config).some((key) => key !== "intention") || typeof config.intention !== "string") throw new Error("Mood settings accept a text intention only."); + try { + config = JSON.parse(parameter); + } catch (_) { + throw new Error("Use a JSON object or a short intention."); + } + if ( + !config || + Array.isArray(config) || + Object.keys(config).some((key) => key !== "intention") || + typeof config.intention !== "string" + ) + throw new Error("Mood settings accept a text intention only."); intention = config.intention.trim(); } if (intention.length > 80) throw new Error("Keep your intention to 80 characters."); -const moods = ["😔", "😕", "😐", "🙂", "😊"], names = ["Low", "Uneasy", "Okay", "Good", "Great"]; -const log = localRecords.create("mood.v1", (value) => Number.isInteger(value) && value >= 1 && value <= 5, 0); -function saveMood(value) { log.edit(() => value); $render(Mood saved); } -function moodOne() { saveMood(1); } -function moodTwo() { saveMood(2); } -function moodThree() { saveMood(3); } -function moodFour() { saveMood(4); } -function moodFive() { saveMood(5); } -function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); } -function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); } +const moods = ["😔", "😕", "😐", "🙂", "😊"], + names = ["Low", "Uneasy", "Okay", "Good", "Great"]; +// One record per day under the key "mood.v1": 1 (Low) to 5 (Great); 0 means no record. +const log = localRecords.create( + "mood.v1", + (value) => Number.isInteger(value) && value >= 1 && value <= 5, + 0, +); +// Save today's mood. +function saveMood(value) { + log.edit(() => value); + $render(Mood saved); +} +// The functions below are named by the "actions" in widget.json. A tap on a )} - {caption} - {size !== "small" && {intention}} - - {!["small", "medium"].includes(size) && Last 7 days{log.recent(state).map((day) => {day.date.slice(5)}{day.recorded ? `${moods[day.value - 1]} ${names[day.value - 1]}` : "—"})}} - ); + // Home Screen sizes. frame="max" fills the widget; padding is the space around the content. + $render( + + + + {size === "small" ? "Mood" : "How are you?"} + + + + {log.today.slice(5)} + + + {/* One button per face. A filled dot marks today's mood. */} + + {moods.map((mood, index) => ( + + ))} + + + {caption} + + {/* The small widget leaves out the intention. */} + {size !== "small" && ( + + {intention} + + )} + + + + + {/* Large sizes also list the last 7 days. day.date.slice(5) is the MM-DD part. */} + {!["small", "medium"].includes(size) && ( + + + Last 7 days + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? `${moods[day.value - 1]} ${names[day.value - 1]}` : "—"} + + + ))} + + )} + , + ); } diff --git a/Gallery/widgets/music-playback/main.jsx b/Gallery/widgets/music-playback/main.jsx index aa134a6b..a957cd3f 100644 --- a/Gallery/widgets/music-playback/main.jsx +++ b/Gallery/widgets/music-playback/main.jsx @@ -1,39 +1,141 @@ // iOS Music app only. Allow Music access in ScriptWidget Settings. // The browser uses editable samples. No queue changes or playback actions. -const family = $getenv("widget-size"), accessory = family.startsWith("accessory"); -const dark = $device.isdarkmode(), compact = family === "small"; +// Shows what the system music player is playing: state, title, artist and position. +// Try changing the colors, or the texts in `states`. +// $music runs on iPhone and iPad, and on Android (the active media session of any app); +// not on Mac, Windows or Linux. widget.json must declare the permission "music". + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". +const family = $getenv("widget-size"), + accessory = family.startsWith("accessory"); +// $device.isdarkmode() is true when the system uses the dark appearance. +const dark = $device.isdarkmode(), + compact = family === "small"; +// Lock Screen sizes get a clear background and the system's own text colors. const background = accessory ? "clear" : dark ? "#262235" : "#f5f1fc"; const primary = accessory ? "primary" : dark ? "#f4ecff" : "#3e3159"; const secondary = accessory ? "secondary" : dark ? "#bfb1d4" : "#796b90"; -let playback = null, notice = "Allow Music access", detail = "Open Music access in ScriptWidget Settings."; +// Read the data. Without it, `notice` and `detail` say what to do. +let playback = null, + notice = "Allow Music access", + detail = "Open Music access in ScriptWidget Settings."; try { - if (!$music.isAvailable()) { notice = "Music unavailable"; detail = "This platform cannot read the system Music player."; } - else if ($music.authorizationStatus() === "authorized") playback = await $music.current(); + // isAvailable() is false on a system without this API. + if (!$music.isAvailable()) { + notice = "Music unavailable"; + detail = "This platform cannot read the system Music player."; + } else if ($music.authorizationStatus() === "authorized") playback = await $music.current(); } catch (error) { + // A failed call throws an error whose text contains a code such as music_permission. const permission = String(error).includes("music_permission"); notice = permission ? "Allow Music access" : "Unable to refresh"; - detail = permission ? "Review Music access in ScriptWidget Settings." : "Open ScriptWidget and refresh this widget."; + detail = permission + ? "Review Music access in ScriptWidget Settings." + : "Open ScriptWidget and refresh this widget."; } -const states = {playing:"Playing",paused:"Paused",stopped:"Stopped",interrupted:"Interrupted",seeking:"Seeking",unknown:"Playback snapshot"}; +// A text for each playback state. +const states = { + playing: "Playing", + paused: "Paused", + stopped: "Stopped", + interrupted: "Interrupted", + seeking: "Seeking", + unknown: "Playback snapshot", +}; +// The texts to show, with a fallback when a detail is missing. const status = playback ? states[playback.state] : notice; -const title = playback ? playback.title || (playback.state === "stopped" ? "No current track" : "Track details unavailable") : notice; -const subtitle = playback ? [playback.artist, playback.album].filter(Boolean).join(" · ") || "Music app" : detail; -const symbol = playback?.state === "paused" ? "pause.fill" : playback?.state === "playing" ? "waveform" : "music.note"; -const time = seconds => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2,"0")}`; -const progress = playback?.duration !== null && playback?.duration > 0 && playback?.position !== null ? Math.min(1,playback.position / playback.duration) : null; +const title = playback + ? playback.title || + (playback.state === "stopped" ? "No current track" : "Track details unavailable") + : notice; +const subtitle = playback + ? [playback.artist, playback.album].filter(Boolean).join(" · ") || "Music app" + : detail; +const symbol = + playback?.state === "paused" + ? "pause.fill" + : playback?.state === "playing" + ? "waveform" + : "music.note"; +// Seconds as m:ss, so 94 becomes "1:34". +const time = (seconds) => + `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`; +// The played share of the track, 0 to 1; null when position or duration is unknown. +const progress = + playback?.duration !== null && playback?.duration > 0 && playback?.position !== null + ? Math.min(1, playback.position / playback.duration) + : null; if (family === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({`${status} · ${title}`}); } else if (family === "accessoryCircular") { - $render({playback ? status : "Setup"}); + // Lock Screen, circular: a symbol and the state. + $render( + + + {playback ? status : "Setup"} + , + ); } else if (family === "accessoryRectangular") { - $render({title}{`${status} · ${playback ? playback.artist || "Music app" : "Open ScriptWidget"}`}); + // Lock Screen, rectangular: title, state and artist. + $render( + + {title} + {`${status} · ${playback ? playback.artist || "Music app" : "Open ScriptWidget"}`} + , + ); } else { - $render( - {compact && !playback ? "Setup" : status}Music - - {title} - {subtitle} - {progress !== null && {time(playback.position)}{time(playback.duration)}} - {!compact && family !== "medium" && <>A playback snapshot. Refresh to update.} - ); + // Home Screen sizes. frame="max" fills the widget; padding is the space around the content. + $render( + + + + + {compact && !playback ? "Setup" : status} + + + + Music + + + + + {title} + + + {subtitle} + + {/* The bar and the two times appear only when the position is known. */} + {progress !== null && ( + + + + + {time(playback.position)} + + + + {time(playback.duration)} + + + + )} + {/* Large sizes add a note. <>… groups children without adding a stack. */} + {!compact && family !== "medium" && ( + <> + + + A playback snapshot. Refresh to update. + + + )} + , + ); } diff --git a/Gallery/widgets/packing-checklist/lib/records.js b/Gallery/widgets/packing-checklist/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Gallery/widgets/packing-checklist/lib/records.js +++ b/Gallery/widgets/packing-checklist/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Gallery/widgets/packing-checklist/main.jsx b/Gallery/widgets/packing-checklist/main.jsx index c594a5e4..d2686f0e 100644 --- a/Gallery/widgets/packing-checklist/main.jsx +++ b/Gallery/widgets/packing-checklist/main.jsx @@ -1,12 +1,37 @@ // A real daily checklist. Optional widget-param: Passport,Charger,Headphones // Up to 8 unique labels. Exact labels identify items, so reordering preserves checks. // Reset affects today only; Undo restores the most recent change. Large shows history. -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); -const size = $getenv("widget-size"), parameter = ($getenv("widget-param") || "").trim(); -const items = parameter ? parameter.split(",").map((item) => item.trim().normalize("NFC")) : localRecords.configuration("checklist").items; -if (items.length > 8 || items.some((item) => !item || item.length > 60) || new Set(items).size !== items.length) throw new Error("Use 1–8 unique checklist labels, at most 60 characters each."); -const validChecks = (value) => Array.isArray(value) && value.length <= 8 && value.every((item) => typeof item === "string" && item.length > 0 && item.length <= 60) && new Set(value).size === value.length; +// Shows a checklist whose items you tick by tapping, with Undo and Reset. +// Try your own items in the widget parameter, or change the colors. +// Saving needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. +const size = $getenv("widget-size"), + parameter = ($getenv("widget-param") || "").trim(); +// The items: from the parameter, else those saved by Records & Configuration. +const items = parameter + ? parameter.split(",").map((item) => item.trim().normalize("NFC")) + : localRecords.configuration("checklist").items; +if ( + items.length > 8 || + items.some((item) => !item || item.length > 60) || + new Set(items).size !== items.length +) + throw new Error("Use 1–8 unique checklist labels, at most 60 characters each."); +// A day's record is the list of ticked labels: up to 8 different texts. +const validChecks = (value) => + Array.isArray(value) && + value.length <= 8 && + value.every((item) => typeof item === "string" && item.length > 0 && item.length <= 60) && + new Set(value).size === value.length; +// One record per day under the key "checklist.v1"; a day without a record is []. const log = localRecords.create("checklist.v1", validChecks, []); +// Tick or untick one item of today's list. function toggleItem(index) { const item = items[index]; if (!item) throw new Error("Checklist item is unavailable."); @@ -17,34 +42,149 @@ function toggleItem(index) { }); $render(Checklist saved); } -function toggleOne() { toggleItem(0); } -function toggleTwo() { toggleItem(1); } -function toggleThree() { toggleItem(2); } -function toggleFour() { toggleItem(3); } -function toggleFive() { toggleItem(4); } -function toggleSix() { toggleItem(5); } -function toggleSeven() { toggleItem(6); } -function toggleEight() { toggleItem(7); } -function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); } -function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); } -const actions = ["toggleOne", "toggleTwo", "toggleThree", "toggleFour", "toggleFive", "toggleSix", "toggleSeven", "toggleEight"]; -const state = log.read(), checked = log.value(state), completed = items.filter((item) => checked.includes(item)).length; -const dark = $device.isdarkmode(), ink = dark ? "#E0F2FE" : "#0C4A6E", muted = dark ? "#7DD3FC" : "#0369A1", background = dark ? "#082F49" : "#F0F9FF"; +// The functions below are named by the "actions" in widget.json. A tap on a )} - {items.length > limit && {size === "small" ? `+ ${items.length - limit} more · use Large` : `+ ${items.length - limit} items · use a larger widget`}} - - {!["small", "medium"].includes(size) && Recent days · completed items{log.recent(state, 3).map((day) => {day.date.slice(5)}{day.recorded ? String(day.value.length) : "—"})}} - ); + $render( + + + + {size === "small" ? "Pack" : "Ready to go"} + + + + {summary} + + + {/* One button per item. The icon shows whether it is ticked. */} + {items.slice(0, limit).map((item, index) => ( + + ))} + {/* Say how many items did not fit. */} + {items.length > limit && ( + + {size === "small" + ? `+ ${items.length - limit} more · use Large` + : `+ ${items.length - limit} items · use a larger widget`} + + )} + + + + + {/* Large sizes also show how many items were ticked on each of the last 3 days. */} + {!["small", "medium"].includes(size) && ( + + + Recent days · completed items + + {log.recent(state, 3).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? String(day.value.length) : "—"} + + + ))} + + )} + , + ); } diff --git a/Gallery/widgets/photo-album-rotator/main.jsx b/Gallery/widgets/photo-album-rotator/main.jsx index d3f86d3e..a813aa00 100644 --- a/Gallery/widgets/photo-album-rotator/main.jsx +++ b/Gallery/widgets/photo-album-rotator/main.jsx @@ -1,35 +1,121 @@ // Live selected Photos sources on iPhone, iPad and Mac; browser samples only. // In ScriptWidget Settings → Photos, authorize and select photos/albums. // Open the installed widget in ScriptWidget to prepare its private snapshot. +// Shows one of up to four selected photos, and the next one every six hours. +// Try other texts and colors, or another photo height. +// $photos runs on iPhone, iPad and Mac, and on Android for individual photos picked in +// the app (no albums); not on Windows or Linux. widget.json must declare the permission +// "photos"; its "timeline" plans an entry at 00:00, 06:00, 12:00 and 18:00. + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". const family = $getenv("widget-size"); const accessory = family.startsWith("accessory"); const small = family === "small" || family === "systemSmall"; const dark = $device.isdarkmode(); const background = accessory ? "clear" : dark ? "#162522" : "#eff7f3"; const foreground = accessory ? "primary" : dark ? "#e7f2eb" : "#204039"; -let photos = [], message = "", partial = false; +// Read the data. `message` says what to do when there is no photo. +let photos = [], + message = "", + partial = false; try { - if (!$photos.isAvailable() || !["authorized", "limited"].includes($photos.authorizationStatus())) message = "Connect Photos in ScriptWidget Settings."; + if (!$photos.isAvailable() || !["authorized", "limited"].includes($photos.authorizationStatus())) + message = "Connect Photos in ScriptWidget Settings."; else { - const result = await $photos.items({limit:4,maxAgeSeconds:3600}); - photos = result.items; partial = result.unavailableCount > 0; - if (!photos.length) message = partial ? "Download selected photos in Photos first." : "No photos in the selected sources."; + // Up to 4 photos (limit) from a snapshot at most one hour old (maxAgeSeconds). + const result = await $photos.items({ limit: 4, maxAgeSeconds: 3600 }); + photos = result.items; + // unavailableCount counts selected photos whose picture is not on this device. + partial = result.unavailableCount > 0; + if (!photos.length) + message = partial + ? "Download selected photos in Photos first." + : "No photos in the selected sources."; } } catch (error) { - message = String(error).includes("cache_miss") ? "Open this widget in ScriptWidget to prepare photos." : "Choose photos or albums in ScriptWidget Settings."; + // A failed call throws an error whose text contains a code such as cache_miss. + message = String(error).includes("cache_miss") + ? "Open this widget in ScriptWidget to prepare photos." + : "Choose photos or albums in ScriptWidget Settings."; } -const compactMessage = message.includes("Download") ? "Download in Photos\nthen refresh here." : message.includes("prepare") ? "Open in ScriptWidget\nto prepare photos." : "Choose photos in\nSettings → Photos"; +// A two-line form of the message for the small widget. +const compactMessage = message.includes("Download") + ? "Download in Photos\nthen refresh here." + : message.includes("prepare") + ? "Open in ScriptWidget\nto prepare photos." + : "Choose photos in\nSettings → Photos"; +// "timeline-date" is the time this entry is planned for. It is used instead of the +// current time because the system may draw an entry ahead of its time. const date = new Date($getenv("timeline-date") || Date.now()); -const photoHeight = family === "small" || family === "medium" ? 112 : family === "extraLargePortrait" ? 480 : 290; -const photo = photos.length ? photos[Math.floor(date.getHours()/6) % photos.length] : null; +// The height of the photo in points, by size. +const photoHeight = + family === "small" || family === "medium" ? 112 : family === "extraLargePortrait" ? 480 : 290; +// Hours 0 to 5 show the first photo, 6 to 11 the second, and so on, starting over at the end. +const photo = photos.length ? photos[Math.floor(date.getHours() / 6) % photos.length] : null; if (family === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({photo ? "My moments" : "Set up Photos"}); } else if (family === "accessoryCircular") { - $render({photos.length ? `${photos.length} photos` : "Set up"}); + // Lock Screen, circular: the number of photos. + $render( + + + {photos.length ? `${photos.length} photos` : "Set up"} + , + ); } else if (accessory) { - $render(My moments{photo ? `${photos.length} selected photos` : "Open ScriptWidget to connect Photos."}); + // Lock Screen, rectangular: two lines. + $render( + + My moments + + {photo ? `${photos.length} selected photos` : "Open ScriptWidget to connect Photos."} + + , + ); } else if (photo) { - $render(My moments{partial && }); + // A photo. `photo.image` is the picture as a data URL. + // mode="fill" with clip="rect" crops it to the frame. + $render( + + + + + My moments + + + {partial && } + + , + ); } else { - $render(My moments{small ? compactMessage : message}{small ? "Photos settings →" : "Open Photos settings →"}); + // No photo: a card that says why. opens its url when the card is tapped. + $render( + + + + + My moments + + + {small ? compactMessage : message} + + + + {small ? "Photos settings →" : "Open Photos settings →"} + + + , + ); } diff --git a/Gallery/widgets/photo-card/lib/configuration.js b/Gallery/widgets/photo-card/lib/configuration.js index e71f04cb..2d393b72 100644 --- a/Gallery/widgets/photo-card/lib/configuration.js +++ b/Gallery/widgets/photo-card/lib/configuration.js @@ -1,28 +1,83 @@ +// Settings for Photo Card. main.jsx loads this file and calls +// photoCardConfiguration.read(). A file loaded this way shares its top-level names +// with main.jsx, so everything else is kept private inside one function. var photoCardConfiguration = (() => { - const defaults = {title:"Little moments",caption:"",layout:"single",photos:[]}; - const valid = value => value && typeof value === "object" && !Array.isArray(value) && + // Used when nothing has been saved yet. + const defaults = { title: "Little moments", caption: "", layout: "single", photos: [] }; + // True when the settings have exactly the four expected keys and every value is in range: + // a title of 1–40 characters, a caption of up to 80, a known layout, and at most four + // different photo names of the form photo-. + const valid = (value) => + value && + typeof value === "object" && + !Array.isArray(value) && Object.keys(value).sort().join(",") === "caption,layout,photos,title" && - typeof value.title === "string" && value.title.trim().length > 0 && value.title.length <= 40 && - typeof value.caption === "string" && value.caption.length <= 80 && ["single","duo","grid"].includes(value.layout) && - Array.isArray(value.photos) && value.photos.length <= 4 && new Set(value.photos).size === value.photos.length && - value.photos.every(name => typeof name === "string" && /^photo-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(name)); + typeof value.title === "string" && + value.title.trim().length > 0 && + value.title.length <= 40 && + typeof value.caption === "string" && + value.caption.length <= 80 && + ["single", "duo", "grid"].includes(value.layout) && + Array.isArray(value.photos) && + value.photos.length <= 4 && + new Set(value.photos).size === value.photos.length && + value.photos.every( + (name) => + typeof name === "string" && + /^photo-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(name), + ); + // raw: the saved settings string ("" when nothing is saved). parameter: the widget + // parameter. Returns the settings to draw with, or throws an error for the widget to show. function read(raw, parameter) { - let values = {...defaults,photos:[]}; + let values = { ...defaults, photos: [] }; + // Saved settings look like {"version":1,"kind":"photoCard","values":{…}}. Anything else + // is refused instead of being guessed at. if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved photo settings are invalid. Open Records & Configuration to repair them."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || !state || - Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== "photoCard" || !valid(state.values)) throw new Error("Saved photo settings are invalid. Open Records & Configuration to repair them."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved photo settings are invalid. Open Records & Configuration to repair them.", + ); + } + // unescape(encodeURIComponent(raw)).length is the size in UTF-8 bytes; the limit is 4096. + if ( + typeof raw !== "string" || + unescape(encodeURIComponent(raw)).length > 4096 || + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== "photoCard" || + !valid(state.values) + ) + throw new Error( + "Saved photo settings are invalid. Open Records & Configuration to repair them.", + ); values = state.values; } + // The widget parameter may override some settings for one widget. Unknown keys are refused. if ((parameter || "").trim()) { let overrides; - try { overrides = JSON.parse(parameter); } catch (_) { throw new Error("Photo Card parameters must be a JSON object."); } - if (!overrides || Array.isArray(overrides) || Object.keys(overrides).some(key => !Object.prototype.hasOwnProperty.call(defaults,key))) throw new Error("Photo Card accepts title, caption, layout and photos only."); - values = {...values,...overrides}; + try { + overrides = JSON.parse(parameter); + } catch (_) { + throw new Error("Photo Card parameters must be a JSON object."); + } + if ( + !overrides || + Array.isArray(overrides) || + Object.keys(overrides).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error("Photo Card accepts title, caption, layout and photos only."); + values = { ...values, ...overrides }; } - if (!valid(values)) throw new Error("Choose up to 4 imported photos, a single/duo/grid layout and valid title/caption text."); + // Check the merged result too, because the parameter is typed by hand. + if (!valid(values)) + throw new Error( + "Choose up to 4 imported photos, a single/duo/grid layout and valid title/caption text.", + ); return values; } - return {read}; + return { read }; })(); diff --git a/Gallery/widgets/photo-card/main.jsx b/Gallery/widgets/photo-card/main.jsx index b41992d9..6c2cfd2b 100644 --- a/Gallery/widgets/photo-card/main.jsx +++ b/Gallery/widgets/photo-card/main.jsx @@ -1,25 +1,125 @@ // Import, crop, select and order photos in Records & Configuration, then save. // Assets stay inside the package. Export the package to back up photo files; // a record backup contains the settings only. No album or network access. -if (!$import("lib/configuration.js")) throw new Error("Install the complete Photo Card template, including lib/configuration.js."); -const options = photoCardConfiguration.read($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); +// +// This template shows how to draw image files stored in the package, in a layout that +// depends on the widget size. Try changing the frame heights or the background colors. + +// $import runs another file of this package and returns false when that fails. +// lib/configuration.js defines photoCardConfiguration, which reads and checks the settings. +if (!$import("lib/configuration.js")) + throw new Error("Install the complete Photo Card template, including lib/configuration.js."); +// $storage holds values saved for this package (widget.json declares the "storage" +// permission). $getenv("widget-param") is the parameter text set for this widget; here it +// may be JSON that overrides title, caption, layout or photos. +const options = photoCardConfiguration.read( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); +// How many photos the chosen layout shows. const limit = options.layout === "grid" ? 4 : options.layout === "duo" ? 2 : 1; -const photos = options.photos.slice(0,limit); -function Photo({name,height}) { return ; } +const photos = options.photos.slice(0, limit); +// One photo. name is an image file in the package; mode="fit" keeps the whole picture +// visible; frame "max,88" means as wide as possible and 88 points high. +function Photo({ name, height }) { + return ; +} if (size === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only). Inline: one line of text. $render({photos.length ? options.title : "Choose photos in ScriptWidget"}); } else if (size === "accessoryCircular") { - $render(photos.length ? : ); + // Lock Screen circle: the first photo, or an icon when none is chosen. + $render( + photos.length ? ( + + ) : ( + + ), + ); } else if (size === "accessoryRectangular") { - $render({photos.length ? : }{options.title}{photos.length ? options.caption : "Choose your photos in the app"}); + // Lock Screen rectangle: a thumbnail beside the title and caption. + $render( + + {photos.length ? ( + + ) : ( + + )} + + {options.title} + + {photos.length ? options.caption : "Choose your photos in the app"} + + + , + ); } else if (!photos.length) { - $render(Add your photosOpen Records & Configuration); + // No photos yet: say where to add them. frame="max" fills the widget; padding is the + // space around the content, in points. + $render( + + + + Add your photos + + + Open Records & Configuration + + , + ); } else if (size === "small") { - $render({Array.from(options.title).slice(0,16).join("")}); + // Small: one photo above the title, cut to 16 characters. Array.from splits the text + // by character, so an emoji is not cut in half. + $render( + + + + {Array.from(options.title).slice(0, 16).join("")} + + , + ); } else if (size === "medium") { - $render({photos.map(name => )}{options.title}{photos.length + (photos.length === 1 ? " photo" : " photos")}); + // Medium: the photos side by side, then the title and a count. + $render( + + + {photos.map((name) => ( + + ))} + + + + {options.title} + + + + {photos.length + (photos.length === 1 ? " photo" : " photos")} + + + , + ); } else { - const rows = photos.length > 2 ? [photos.slice(0,2),photos.slice(2)] : [photos]; - $render({options.title}{rows.map(row => {row.map(name => 1 ? "120" : "240"}/>)})}{options.caption ? {options.caption} : null}); + // Large and extra large: one or two rows of photos, the title above, the caption below. + const rows = photos.length > 2 ? [photos.slice(0, 2), photos.slice(2)] : [photos]; + $render( + + + {options.title} + + {rows.map((row) => ( + + {row.map((name) => ( + 1 ? "120" : "240"} /> + ))} + + ))} + {options.caption ? ( + + {options.caption} + + ) : null} + , + ); } diff --git a/Gallery/widgets/plant-care/lib/records.js b/Gallery/widgets/plant-care/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Gallery/widgets/plant-care/lib/records.js +++ b/Gallery/widgets/plant-care/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Gallery/widgets/plant-care/main.jsx b/Gallery/widgets/plant-care/main.jsx index 69010901..1b22d428 100644 --- a/Gallery/widgets/plant-care/main.jsx +++ b/Gallery/widgets/plant-care/main.jsx @@ -1,18 +1,184 @@ // A personal care journal, not a sensor reading. Rendering never creates records. +// +// This template shows a widget with buttons: a tap runs a function in this file, which +// saves a record in package storage. Try changing the status texts, the level names or the +// colors. + +// $import runs lib/records.js from this package and returns false when that fails. The +// file defines localRecords: a diary with one entry per calendar day, kept in package storage +// (widget.json declares the "storage" permission). if (!$import("lib/records.js")) throw new Error("Install the complete Plant Care template."); -const config=localRecords.configuration("plantCare"),parameter=$getenv("widget-param")||""; +// The saved settings (plant name, days between care) and the widget parameter: the +// parameter text set for this widget, empty when there is none. +const config = localRecords.configuration("plantCare"), + parameter = $getenv("widget-param") || ""; // Preserve the name from the earlier name,days demo; its invented countdown is not a care record. -const title=parameter?parameter.split(",")[0].trim():config.title; -if(!title||title.length>40)throw new Error("Use a plant name of 1–40 characters."); -const log=localRecords.create("plantCare.v1",value=>value===1,0,new Date($getenv("timeline-date")||Date.now())); -function waterPlant(){const changed=log.edit(()=>1);$render({changed?"Care recorded":"Already recorded today"});} -function undoRecord(){const changed=log.undo();$render({changed?"Change undone":"Nothing to undo"});} -function resetToday(){log.reset();$render(Today cleared; Undo can restore it);} -const state=log.read(),days=state.entries.filter(entry=>entry.date<=log.today).map(entry=>entry.date).sort(),last=days[days.length-1]||"",done=log.value(state)===1; -const ordinal=key=>{const [y,m,d]=key.split("-").map(Number);return Date.UTC(y,m-1,d)/86400000;}; -const elapsed=last?ordinal(log.today)-ordinal(last):null,remaining=elapsed===null?null:Math.max(0,config.intervalDays-elapsed); -const status=done?"Cared for today":last?(remaining>0?`Next care in ${remaining} ${remaining===1?"day":"days"}`:"Care due"):"No care recorded"; -const level=days.length>=15?"Blooming routine":days.length>=5?"Growing routine":"New beginning"; -const dark=$device.isdarkmode(),background=dark?"#102a22":"#f0fdf4",ink=dark?"#dcfce7":"#14532d",muted=dark?"#86efac":"#166534",family=$getenv("widget-size"); -const Plant=()=> ; -if(family==="function"||family==="action"){}else if(family==="accessoryInline"){$render({`${title} · ${status}`});}else if(family==="accessoryCircular"){$render({done?"Done":remaining===null?"Start":remaining===0?"Due":`${remaining}d`});}else if(family==="accessoryRectangular"){$render({title}{status});}else{$render({title}{family!=="small"&&CARE JOURNAL}{status}{family!=="small"&&{`${days.length} care ${days.length===1?"day":"days"} · last year`}}{family!=="small"&&{level}}{!["small","medium"].includes(family)&&{last?`Last care: ${last}`:"Your first care check-in starts the journal."}{`Personal interval: ${config.intervalDays} days`}{log.recent(state).map(day=>{day.date.slice(5)}{day.recorded?"✓":"—"})}});} +const title = parameter ? parameter.split(",")[0].trim() : config.title; +if (!title || title.length > 40) throw new Error("Use a plant name of 1–40 characters."); +// Open the diary stored under the key "plantCare.v1". A day's value is 1 when care was +// recorded; 0 stands for a day without an entry. "timeline-date" is the moment this entry +// is drawn for, which is later than now when the system prepares the widget in advance. +const log = localRecords.create( + "plantCare.v1", + (value) => value === 1, + 0, + new Date($getenv("timeline-date") || Date.now()), +); +// The next three functions are the actions listed in widget.json; a button with +// actionID="waterPlant" runs waterPlant(). Each one changes the diary and renders a short +// confirmation. edit() returns false when today already has that value. +function waterPlant() { + const changed = log.edit(() => 1); + $render({changed ? "Care recorded" : "Already recorded today"}); +} +function undoRecord() { + const changed = log.undo(); + $render({changed ? "Change undone" : "Nothing to undo"}); +} +function resetToday() { + log.reset(); + $render(Today cleared; Undo can restore it); +} +// Read the diary (reading never writes) and work out what to show. +// days: every recorded date up to today, as sorted "YYYY-MM-DD" strings. +const state = log.read(), + days = state.entries + .filter((entry) => entry.date <= log.today) + .map((entry) => entry.date) + .sort(), + last = days[days.length - 1] || "", + done = log.value(state) === 1; +// Turns "YYYY-MM-DD" into a day number, so that two dates can be subtracted. +const ordinal = (key) => { + const [y, m, d] = key.split("-").map(Number); + return Date.UTC(y, m - 1, d) / 86400000; +}; +// Days since the last care, and days until the next one is due (never below 0). +const elapsed = last ? ordinal(log.today) - ordinal(last) : null, + remaining = elapsed === null ? null : Math.max(0, config.intervalDays - elapsed); +// The sentence shown in the widget. +const status = done + ? "Cared for today" + : last + ? remaining > 0 + ? `Next care in ${remaining} ${remaining === 1 ? "day" : "days"}` + : "Care due" + : "No care recorded"; +// A label that grows with the number of recorded days. +const level = + days.length >= 15 ? "Blooming routine" : days.length >= 5 ? "Growing routine" : "New beginning"; +// Colors for light and dark mode, and the size being drawn ("small", "medium", …). +const dark = $device.isdarkmode(), + background = dark ? "#102a22" : "#f0fdf4", + ink = dark ? "#dcfce7" : "#14532d", + muted = dark ? "#86efac" : "#166534", + family = $getenv("widget-size"); +// The plant, drawn from shapes: two leaves, a stem and a pot. frame is "width,height" in +// points; rotation is in degrees. +const Plant = () => ( + + + + + + + + +); +// While a button or a Shortcuts action runs, widget-size is "function" or "action". The +// function above then renders its own message, so nothing is drawn here. +if (family === "function" || family === "action") { +} else if (family === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only): text and an icon. + $render({`${title} · ${status}`}); +} else if (family === "accessoryCircular") { + $render( + + + + {done ? "Done" : remaining === null ? "Start" : remaining === 0 ? "Due" : `${remaining}d`} + + , + ); +} else if (family === "accessoryRectangular") { + $render( + + {title} + {status} + , + ); +} else { + // Home Screen sizes share one layout; the parts marked family !== "small" are left out + // where there is no room. frame="max" fills the widget; padding is the space around the + // content, in points. + $render( + + + + {title} + + + {family !== "small" && ( + + CARE JOURNAL + + )} + + + + + + {status} + + {family !== "small" && ( + {`${days.length} care ${days.length === 1 ? "day" : "days"} · last year`} + )} + {family !== "small" && ( + + {level} + + )} + + + {/* Each button runs the action with this id from widget.json. */} + + + + + {/* Large sizes only: the last care, the interval and the last seven days. */} + {!["small", "medium"].includes(family) && ( + + + {last ? `Last care: ${last}` : "Your first care check-in starts the journal."} + + {`Personal interval: ${config.intervalDays} days`} + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? "✓" : "—"} + + + ))} + + )} + , + ); +} diff --git a/Gallery/widgets/pocket-pet/lib/records.js b/Gallery/widgets/pocket-pet/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Gallery/widgets/pocket-pet/lib/records.js +++ b/Gallery/widgets/pocket-pet/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Gallery/widgets/pocket-pet/main.jsx b/Gallery/widgets/pocket-pet/main.jsx index 0442b10c..604b3a74 100644 --- a/Gallery/widgets/pocket-pet/main.jsx +++ b/Gallery/widgets/pocket-pet/main.jsx @@ -1,19 +1,251 @@ // A local virtual companion. Only explicit daily care changes its journal. -if(!$import("lib/records.js"))throw new Error("Install the complete Pocket Pet template."); -const config=localRecords.configuration("pocketPet"),title=($getenv("widget-param")||config.title).trim(),order=["feed","play","rest"]; -if(!title||title.length>40)throw new Error("Use a pet name of 1–40 characters."); -const valid=value=>Array.isArray(value)&&value.length>=1&&value.length<=3&&new Set(value).size===value.length&&value.every(action=>order.includes(action)); -const log=localRecords.create("pocketPet.v1",valid,[],new Date($getenv("timeline-date")||Date.now())); -function care(action){const changed=log.edit(value=>order.filter(item=>value.includes(item)||item===action));$render({changed?"Care saved":"Already done today"});} -function feedPet(){care("feed");}function playPet(){care("play");}function restPet(){care("rest");} -function undoRecord(){const changed=log.undo();$render({changed?"Change undone":"Nothing to undo"});} -function resetToday(){log.reset();$render(Today cleared; Undo can restore it);} -const state=log.read(),today=log.value(state),days=state.entries.filter(entry=>entry.date<=log.today),careDays=days.length,rested=today.includes("rest"),complete=today.length===3; -const last=days.map(entry=>entry.date).sort().pop(),ordinal=key=>{const [y,m,d]=key.split("-").map(Number);return Date.UTC(y,m-1,d)/86400000;}; -const gap=last?ordinal(log.today)-ordinal(last):null,status=complete?"A lovely day":rested?"Resting happily":today.length?"Enjoying your company":gap!==null&&gap>=3?"Ready to reconnect":"Ready for care",level=careDays>=30?"Close companions":careDays>=7?"Good friends":"New friends"; -const dark=$device.isdarkmode(),background=dark?"#302443":"#faf5ff",ink=dark?"#f3e8ff":"#581c87",muted=dark?"#d8b4fe":"#7e22ce",family=$getenv("widget-size"); +// +// This template shows several buttons that each save a different action for today, and +// a face drawn from shapes that changes with the saved state. Try changing the status +// texts or the colors. + +// $import runs lib/records.js from this package and returns false when that fails. The +// file defines localRecords: a diary with one entry per calendar day, kept in package storage +// (widget.json declares the "storage" permission). +if (!$import("lib/records.js")) throw new Error("Install the complete Pocket Pet template."); +// The pet's name is the widget parameter (the parameter text set for this widget), or +// else the name from the saved settings. +const config = localRecords.configuration("pocketPet"), + title = ($getenv("widget-param") || config.title).trim(), + order = ["feed", "play", "rest"]; +if (!title || title.length > 40) throw new Error("Use a pet name of 1–40 characters."); +// A day's value is a list of one to three different actions, for example ["feed", "rest"]. +const valid = (value) => + Array.isArray(value) && + value.length >= 1 && + value.length <= 3 && + new Set(value).size === value.length && + value.every((action) => order.includes(action)); +// Open the diary stored under the key "pocketPet.v1"; [] stands for a day without care. +// "timeline-date" is the moment this entry is drawn for, which is later than now when the +// system prepares the widget in advance. +const log = localRecords.create( + "pocketPet.v1", + valid, + [], + new Date($getenv("timeline-date") || Date.now()), +); +// Adds one action to today's list, keeping the order feed, play, rest. edit() returns +// false when nothing changed. +function care(action) { + const changed = log.edit((value) => + order.filter((item) => value.includes(item) || item === action), + ); + $render({changed ? "Care saved" : "Already done today"}); +} +// The functions below are the actions listed in widget.json; a button with +// actionID="feedPet" runs feedPet(). +function feedPet() { + care("feed"); +} +function playPet() { + care("play"); +} +function restPet() { + care("rest"); +} +function undoRecord() { + const changed = log.undo(); + $render({changed ? "Change undone" : "Nothing to undo"}); +} +function resetToday() { + log.reset(); + $render(Today cleared; Undo can restore it); +} +// Read the diary (reading never writes) and work out what to show. +const state = log.read(), + today = log.value(state), + days = state.entries.filter((entry) => entry.date <= log.today), + careDays = days.length, + rested = today.includes("rest"), + complete = today.length === 3; +// The latest care date, and a helper that turns "YYYY-MM-DD" into a day number. +const last = days + .map((entry) => entry.date) + .sort() + .pop(), + ordinal = (key) => { + const [y, m, d] = key.split("-").map(Number); + return Date.UTC(y, m - 1, d) / 86400000; + }; +// gap: days since the last care. status and level are the two sentences in the widget. +const gap = last ? ordinal(log.today) - ordinal(last) : null, + status = complete + ? "A lovely day" + : rested + ? "Resting happily" + : today.length + ? "Enjoying your company" + : gap !== null && gap >= 3 + ? "Ready to reconnect" + : "Ready for care", + level = careDays >= 30 ? "Close companions" : careDays >= 7 ? "Good friends" : "New friends"; +// Colors for light and dark mode, and the size being drawn ("small", "medium", …). +const dark = $device.isdarkmode(), + background = dark ? "#302443" : "#faf5ff", + ink = dark ? "#f3e8ff" : "#581c87", + muted = dark ? "#d8b4fe" : "#7e22ce", + family = $getenv("widget-size"); // Original JSX geometry; static artwork works without animation or network resources. -const Pet=()=> {rested?"−":"•"}{complete?"ᴗ":"ω"}{rested?"−":"•"}; -const CareButton=({action})=>; -const UndoButton=()=> ; -if(family==="function"||family==="action"){}else if(family==="accessoryInline"){$render({`${title} · ${today.length}/3 care`});}else if(family==="accessoryCircular"){$render({`${today.length}/3`});}else if(family==="accessoryRectangular"){$render({title}{status});}else{$render({title}{`${today.length}/3`}{status}{family!=="small"&&{level}}{family!=="small"&&{`${careDays} care days · last year`}}{family==="small"?:{order.map(action=>)}}{!["small","medium"].includes(family)&&Last 7 days{log.recent(state).map(day=>{day.date.slice(5)}{day.recorded?`${day.value.length}/3`:"—"})}Care counts once per day. Nothing to catch up or buy.});} +// Two ears above a face. The eyes close after rest, and the mouth changes when all three +// actions are done. frame is "width,height" in points; rotation is in degrees. +const Pet = () => ( + + + + + + + + + + {rested ? "−" : "•"} + + + {complete ? "ᴗ" : "ω"} + + + {rested ? "−" : "•"} + + + + +); +// A button for one action. Its text tells whether the action is already done today. +const CareButton = ({ action }) => ( + +); +const UndoButton = () => ( + +); +// While a button or a Shortcuts action runs, widget-size is "function" or "action". The +// function above then renders its own message, so nothing is drawn here. +if (family === "function" || family === "action") { +} else if (family === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only). + $render({`${title} · ${today.length}/3 care`}); +} else if (family === "accessoryCircular") { + $render( + + + {`${today.length}/3`} + , + ); +} else if (family === "accessoryRectangular") { + $render( + + {title} + {status} + , + ); +} else { + // Home Screen sizes. frame="max" fills the widget; padding is the space around the + // content, in points. The small widget gets less of both. + $render( + + + + {title} + + + {`${today.length}/3`} + + + + + + {status} + + {family !== "small" && ( + + {level} + + )} + {family !== "small" && ( + {`${careDays} care days · last year`} + )} + + + {/* Buttons: two rows in the small widget, one row in the others. */} + {family === "small" ? ( + + + + + + + + + + + ) : ( + + {order.map((action) => ( + + ))} + + + )} + {/* Large sizes only: the last seven days. */} + {!["small", "medium"].includes(family) && ( + + + Last 7 days + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? `${day.value.length}/3` : "—"} + + + ))} + + Care counts once per day. Nothing to catch up or buy. + + + )} + , + ); +} diff --git a/Gallery/widgets/quick-launcher/lib/launcher.js b/Gallery/widgets/quick-launcher/lib/launcher.js index bd919728..10a44319 100644 --- a/Gallery/widgets/quick-launcher/lib/launcher.js +++ b/Gallery/widgets/quick-launcher/lib/launcher.js @@ -1,46 +1,179 @@ -var quickLauncher=(()=>{ - const icons=["globe","map.fill","play.fill","star.fill","music.note","envelope.fill","phone.fill","message.fill","house.fill","checkmark.circle.fill"]; - const defaults={title:"Quick Launch",accent:"blue",items:[ - {id:"github",title:"GitHub",icon:"globe",type:"web",target:"https://github.com",input:""}, - {id:"maps",title:"Maps",icon:"map.fill",type:"app",target:"maps://",input:""}, - {id:"search",title:"Search",icon:"star.fill",type:"web",target:"https://www.google.com",input:""} - ]}; - const closed=(value,keys)=>value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).sort().join(",")===keys.split(",").sort().join(","); - const plain=(value,max)=>typeof value==="string"&&value.length<=max&&value.trim().length>0&&!/[\p{Cc}\p{Cf}]/u.test(value); - const encode=value=>encodeURIComponent(value).replace(/[!'()*]/g,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase()); - function destination(item){ - if(!closed(item,"id,title,icon,type,target,input")||typeof item.id!=="string"||!/^[A-Za-z0-9][A-Za-z0-9-]{0,39}$/.test(item.id)||!plain(item.title,24)||!icons.includes(item.icon)||!["web","app","shortcut"].includes(item.type)||typeof item.input!=="string"||item.input.length>500||item.input.includes("\u0000"))throw new Error("Invalid launcher item. Open Records & Configuration."); - if(item.type==="shortcut"){ - if(!plain(item.target,128))throw new Error("Enter the name of a saved shortcut."); - return "shortcuts://run-shortcut?name="+encode(item.target)+(item.input?"&input=text&text="+encode(item.input):""); +// Settings for Quick Launcher. main.jsx loads this file and calls +// quickLauncher.options(). The checks are strict because a link is typed by the user and +// then opened by the system. +var quickLauncher = (() => { + // The SF Symbol names that an item may use as its icon. + const icons = [ + "globe", + "map.fill", + "play.fill", + "star.fill", + "music.note", + "envelope.fill", + "phone.fill", + "message.fill", + "house.fill", + "checkmark.circle.fill", + ]; + // Used when nothing has been saved. type is "web", "app" (an app's own URL scheme, such + // as maps://) or "shortcut" (target is the name of a shortcut in Apple's Shortcuts app, + // input is optional text passed to it). + const defaults = { + title: "Quick Launch", + accent: "blue", + items: [ + { + id: "github", + title: "GitHub", + icon: "globe", + type: "web", + target: "https://github.com", + input: "", + }, + { id: "maps", title: "Maps", icon: "map.fill", type: "app", target: "maps://", input: "" }, + { + id: "search", + title: "Search", + icon: "star.fill", + type: "web", + target: "https://www.google.com", + input: "", + }, + ], + }; + // True for a plain object that has exactly the listed keys. + const closed = (value, keys) => + value && + typeof value === "object" && + !Array.isArray(value) && + Object.keys(value).sort().join(",") === keys.split(",").sort().join(","); + // True for a non-blank string of at most `max` characters without control characters. + const plain = (value, max) => + typeof value === "string" && + value.length <= max && + value.trim().length > 0 && + !/[\p{Cc}\p{Cf}]/u.test(value); + // Percent-encodes text for a URL, including the characters encodeURIComponent leaves. + const encode = (value) => + encodeURIComponent(value).replace( + /[!'()*]/g, + (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(), + ); + // Checks one item and returns the URL to open for it. + function destination(item) { + if ( + !closed(item, "id,title,icon,type,target,input") || + typeof item.id !== "string" || + !/^[A-Za-z0-9][A-Za-z0-9-]{0,39}$/.test(item.id) || + !plain(item.title, 24) || + !icons.includes(item.icon) || + !["web", "app", "shortcut"].includes(item.type) || + typeof item.input !== "string" || + item.input.length > 500 || + item.input.includes("\u0000") + ) + throw new Error("Invalid launcher item. Open Records & Configuration."); + // A shortcut is run by name through the URL scheme of the Shortcuts app. + if (item.type === "shortcut") { + if (!plain(item.target, 128)) throw new Error("Enter the name of a saved shortcut."); + return ( + "shortcuts://run-shortcut?name=" + + encode(item.target) + + (item.input ? "&input=text&text=" + encode(item.input) : "") + ); } - if(item.input!==""||!plain(item.target,2048)||/[\s\\]/u.test(item.target)||/%(?![0-9a-f]{2})/i.test(item.target))throw new Error("Enter a valid URL without spaces or credentials."); - const match=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(item.target);if(!match)throw new Error("An absolute URL is required."); - const scheme=match[1].toLowerCase(),authority=item.target.slice(match[0].length).startsWith("//")?item.target.slice(match[0].length+2).split(/[/?#]/)[0]:""; - if(authority.includes("@"))throw new Error("URL credentials are not supported."); - if(item.type==="web"){ - const web=/^https?:\/\/(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::([0-9]{1,5}))?(?:[/?#]|$)/i.exec(item.target); - if(!web||(web[1]!==undefined&&(Number(web[1])<1||Number(web[1])>65535)))throw new Error("Use an HTTP(S) web link."); - }else if(["http","https","file","data","javascript","about","blob","widget-deeplink","scriptwidget","prefs","app-prefs"].includes(scheme))throw new Error("Use an external app URL scheme."); + // Web and app links: no input text, spaces, backslashes or broken percent escapes. + if ( + item.input !== "" || + !plain(item.target, 2048) || + /[\s\\]/u.test(item.target) || + /%(?![0-9a-f]{2})/i.test(item.target) + ) + throw new Error("Enter a valid URL without spaces or credentials."); + // Take the scheme ("https", "maps", …) and the host part, and refuse user:password@host. + const match = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(item.target); + if (!match) throw new Error("An absolute URL is required."); + const scheme = match[1].toLowerCase(), + authority = item.target.slice(match[0].length).startsWith("//") + ? item.target.slice(match[0].length + 2).split(/[/?#]/)[0] + : ""; + if (authority.includes("@")) throw new Error("URL credentials are not supported."); + if (item.type === "web") { + // A web link must be http or https with a host and, if given, a port from 1 to 65535. + const web = + /^https?:\/\/(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::([0-9]{1,5}))?(?:[/?#]|$)/i.exec( + item.target, + ); + if (!web || (web[1] !== undefined && (Number(web[1]) < 1 || Number(web[1]) > 65535))) + throw new Error("Use an HTTP(S) web link."); + } else if ( + [ + "http", + "https", + "file", + "data", + "javascript", + "about", + "blob", + "widget-deeplink", + "scriptwidget", + "prefs", + "app-prefs", + ].includes(scheme) + ) + // An app link must use the app's own scheme, not a web, file or ScriptWidget one. + throw new Error("Use an external app URL scheme."); return item.target; } - function validate(value){ - if(!closed(value,"title,accent,items")||!plain(value.title,40)||!["blue","green","rose"].includes(value.accent)||!Array.isArray(value.items)||value.items.length<1||value.items.length>6||new Set(value.items.map(item=>item?.id)).size!==value.items.length)throw new Error("Configure a title, accent and 1–6 unique launcher links."); + // Checks the whole settings object: a title, an accent color and 1–6 items with different ids. + function validate(value) { + if ( + !closed(value, "title,accent,items") || + !plain(value.title, 40) || + !["blue", "green", "rose"].includes(value.accent) || + !Array.isArray(value.items) || + value.items.length < 1 || + value.items.length > 6 || + new Set(value.items.map((item) => item?.id)).size !== value.items.length + ) + throw new Error("Configure a title, accent and 1–6 unique launcher links."); value.items.forEach(destination); - if(unescape(encodeURIComponent(JSON.stringify({version:1,kind:"launcher",values:value}))).length>32768)throw new Error("Launcher configuration exceeds 32 KiB."); + // The size limit is measured in UTF-8 bytes. + if ( + unescape(encodeURIComponent(JSON.stringify({ version: 1, kind: "launcher", values: value }))) + .length > 32768 + ) + throw new Error("Launcher configuration exceeds 32 KiB."); return value; } - function options(raw,parameter){ - let result={...defaults,items:defaults.items.map(item=>({...item}))}; - if(raw!==null&&raw!==undefined&&raw!==""){ - if(typeof raw!=="string"||raw.length>32768)throw new Error("Invalid launcher configuration."); - const saved=JSON.parse(raw);if(!closed(saved,"version,kind,values")||saved.version!==1||saved.kind!=="launcher")throw new Error("Invalid launcher configuration.");result=validate(saved.values); + // raw: the saved settings string. parameter: the widget parameter, a JSON object that may + // replace title, accent or items for one widget. Returns the settings with a url on + // every item. + function options(raw, parameter) { + let result = { ...defaults, items: defaults.items.map((item) => ({ ...item })) }; + if (raw !== null && raw !== undefined && raw !== "") { + if (typeof raw !== "string" || raw.length > 32768) + throw new Error("Invalid launcher configuration."); + const saved = JSON.parse(raw); + if (!closed(saved, "version,kind,values") || saved.version !== 1 || saved.kind !== "launcher") + throw new Error("Invalid launcher configuration."); + result = validate(saved.values); } - if(parameter){ - if(typeof parameter!=="string"||parameter.length>32768)throw new Error("Invalid launcher parameter."); - const overrides=JSON.parse(parameter);if(!overrides||typeof overrides!=="object"||Array.isArray(overrides)||Object.keys(overrides).some(key=>!Object.hasOwn(defaults,key)))throw new Error("Unknown launcher setting.");result={...result,...overrides}; + if (parameter) { + if (typeof parameter !== "string" || parameter.length > 32768) + throw new Error("Invalid launcher parameter."); + const overrides = JSON.parse(parameter); + if ( + !overrides || + typeof overrides !== "object" || + Array.isArray(overrides) || + Object.keys(overrides).some((key) => !Object.hasOwn(defaults, key)) + ) + throw new Error("Unknown launcher setting."); + result = { ...result, ...overrides }; } - validate(result);return {...result,items:result.items.map(item=>({...item,url:destination(item)}))}; + validate(result); + return { ...result, items: result.items.map((item) => ({ ...item, url: destination(item) })) }; } - return {options,destination}; + return { options, destination }; })(); diff --git a/Gallery/widgets/quick-launcher/main.jsx b/Gallery/widgets/quick-launcher/main.jsx index 5e4135d9..5232f471 100644 --- a/Gallery/widgets/quick-launcher/main.jsx +++ b/Gallery/widgets/quick-launcher/main.jsx @@ -1,17 +1,105 @@ // Configure web links, app URLs and saved Shortcuts in Records & Configuration. -if(!$import("lib/launcher.js"))throw new Error("Install the complete Quick Launcher template."); -const config=quickLauncher.options($storage.getString("recordTemplate.config.v1"),$getenv("widget-param")); -const size=$getenv("widget-size"),dark=$device.isdarkmode(),small=size==="small"; -const background=dark?"#111827":"#eff6ff",text=dark?"#f8fafc":"#1e3a8a",muted=dark?"#cbd5e1":"#475569",accent={blue:"#2563eb",green:"#15803d",rose:"#be185d"}[config.accent]; -const Tile=({item})=>{item.title}; -if(size==="accessoryInline"){ - const first=config.items[0];$render({first.title}); -}else if(size==="accessoryCircular"){ - const first=config.items[0];$render({first.title}); -}else if(size==="accessoryRectangular"){ - const first=config.items[0];$render({first.title}{config.title}); -}else{ - const columns=small?1:3,limit=small?1:size==="medium"?3:6,items=config.items.slice(0,limit),rows=[]; - for(let i=0;i{config.title}{rows.map(row=>{row.map(item=>)})}{!small&&size!=="medium"&&Tap a link · test and reorder in ScriptWidget}); +// +// This template shows tiles to tap: each opens a web page, an app or a Shortcut. +// Try changing the colors below, or the default links in lib/launcher.js. + +// $import runs lib/launcher.js from this package and returns false when that fails. +// The file defines quickLauncher. +if (!$import("lib/launcher.js")) throw new Error("Install the complete Quick Launcher template."); +// Read the saved settings from $storage (widget.json declares the "storage" permission) +// and the widget parameter: the parameter text set for this widget, here optional JSON. +// Every item comes back with a ready-to-open `url`. +const config = quickLauncher.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// The size being drawn, and whether the system is in dark mode. +const size = $getenv("widget-size"), + dark = $device.isdarkmode(), + small = size === "small"; +// Colors for light and dark mode; the accent color is chosen in the settings. +const background = dark ? "#111827" : "#eff6ff", + text = dark ? "#f8fafc" : "#1e3a8a", + muted = dark ? "#cbd5e1" : "#475569", + accent = { blue: "#2563eb", green: "#15803d", rose: "#be185d" }[config.accent]; +// One tile: an icon above a title. Tapping it opens item.url. +const Tile = ({ item }) => ( + + + + + {item.title} + + + +); +if (size === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only) show the first link only. + const first = config.items[0]; + $render( + + {first.title} + , + ); +} else if (size === "accessoryCircular") { + const first = config.items[0]; + $render( + + + + {first.title} + + , + ); +} else if (size === "accessoryRectangular") { + const first = config.items[0]; + $render( + + + + + {first.title} + {config.title} + + + , + ); +} else { + // Home Screen sizes: one tile in the small widget, three in the medium, up to six in the + // larger ones, in rows of `columns` tiles. + const columns = small ? 1 : 3, + limit = small ? 1 : size === "medium" ? 3 : 6, + items = config.items.slice(0, limit), + rows = []; + // Cut the list into rows. + for (let i = 0; i < items.length; i += columns) rows.push(items.slice(i, i + columns)); + // linkurl on the root element is the fallback target, the first link, for a tap that + // does not open a tile. frame="max" fills the widget; padding is the space around the + // content, in points. + $render( + + + {config.title} + + {rows.map((row) => ( + + {row.map((item) => ( + + ))} + + ))} + {!small && size !== "medium" && ( + + Tap a link · test and reorder in ScriptWidget + + )} + , + ); } diff --git a/Gallery/widgets/reminders-agenda/main.jsx b/Gallery/widgets/reminders-agenda/main.jsx index 8fac2240..0809063e 100644 --- a/Gallery/widgets/reminders-agenda/main.jsx +++ b/Gallery/widgets/reminders-agenda/main.jsx @@ -2,57 +2,113 @@ // Declare reminders, remindersWrite and storage. Grant access and select lists in Settings. // Optional widget parameter: comma-separated list IDs from $reminders.lists(). // Browser previews use editable samples; native templates never seed fake reminders. +// +// $reminders runs on iPhone and iPad, and on Mac. It does not run on Android, Windows +// or Linux. +// This template shows how to read system data that needs permission, how to show a +// helpful message for every way that can fail, and how a button changes data safely. +// Try changing `limit` or the colors. + +// The size being drawn. The Lock Screen sizes (iPhone and iPad only) start with "accessory". const size = $getenv("widget-size"); const accessory = size.startsWith("accessory"); +// Lock Screen widgets use the system's own colors ("primary", "secondary"). const dark = $device.isdarkmode(); -const foreground = accessory ? "primary" : (dark ? "#f3f4f6" : "#172033"); -const secondary = accessory ? "secondary" : (dark ? "#9ca3af" : "#68758b"); -const background = accessory ? "clear" : (dark ? "#131b2a" : "#f4f7fc"); +const foreground = accessory ? "primary" : dark ? "#f3f4f6" : "#172033"; +const secondary = accessory ? "secondary" : dark ? "#9ca3af" : "#68758b"; +const background = accessory ? "clear" : dark ? "#131b2a" : "#f4f7fc"; const accent = accessory ? "primary" : "#5274d9"; const small = size === "small" || size === "systemSmall"; -const limit = accessory || small ? 2 : (size === "medium" || size === "systemMedium" ? 3 : 6); -let items = [], message = "", authorized = false, stale = false, failed = false; +// How many reminders to ask for: 2 in small and Lock Screen sizes, 3 in medium, else 6. +const limit = accessory || small ? 2 : size === "medium" || size === "systemMedium" ? 3 : 6; +// What the query found. `message` is shown instead of the list, or below it. +let items = [], + message = "", + authorized = false, + stale = false, + failed = false; +// A "complete" request that was started and not yet confirmed; {} when there is none. +// $storage holds values saved for this package ("storage" permission in widget.json). const pendingWrite = $storage.getJSON("pending-reminder-write"); - +// Read the reminders, unless a button action is running: widget-size is then "action" or +// "function", and the action reads what it needs itself. if (size !== "action" && size !== "function") { -try { - if (!$reminders.isAvailable()) message = "Reminders is unavailable on this device."; - else if ($reminders.authorizationStatus() !== "authorized") message = small ? "Settings → Reminders in ScriptWidget." : "Connect Reminders in ScriptWidget Settings."; - else { - authorized = true; - const parameter = $getenv("widget-param").trim(); - const options = { limit, maxAgeSeconds: 60 }; - if (parameter) options.listIDs = parameter.split(",").map(id => id.trim()).filter(Boolean); - const result = await $reminders.items(options); - items = Array.isArray(result.items) ? result.items : []; - stale = result.stale; - if (!items.length) message = "No reminders due today."; + try { + // Check in order: does this system have Reminders, and has the user granted access? + if (!$reminders.isAvailable()) message = "Reminders is unavailable on this device."; + else if ($reminders.authorizationStatus() !== "authorized") + message = small + ? "Settings → Reminders in ScriptWidget." + : "Connect Reminders in ScriptWidget Settings."; + else { + authorized = true; + // The widget parameter (the parameter text set for this widget) may name the lists to + // read. maxAgeSeconds: a saved result up to 60 seconds old may be reused. + const parameter = $getenv("widget-param").trim(); + const options = { limit, maxAgeSeconds: 60 }; + if (parameter) + options.listIDs = parameter + .split(",") + .map((id) => id.trim()) + .filter(Boolean); + // Needs the "reminders" permission in widget.json. Without start and end, items() + // returns the reminders due today, from local midnight to the next. + const result = await $reminders.items(options); + items = Array.isArray(result.items) ? result.items : []; + // stale is true when the result is a saved one that is older than 60 seconds. + stale = result.stale; + if (!items.length) message = "No reminders due today."; + } + } catch (error) { + // The error text contains a code. Turn the known ones into a hint, shorter in small sizes. + failed = true; + message = String(error).includes("No Reminder lists") + ? small || accessory + ? "Choose reminder lists in Settings." + : "Choose reminder lists in ScriptWidget Settings." + : String(error).includes("invalid_options") + ? small || accessory + ? "Review Reminders selection." + : "Review your Reminders selection and widget parameter." + : small || accessory + ? "Open ScriptWidget to check access." + : "Reminders could not load. Open ScriptWidget to check access."; } -} catch (error) { - failed = true; - message = String(error).includes("No Reminder lists") ? (small || accessory ? "Choose reminder lists in Settings." : "Choose reminder lists in ScriptWidget Settings.") - : String(error).includes("invalid_options") ? (small || accessory ? "Review Reminders selection." : "Review your Reminders selection and widget parameter.") - : (small || accessory ? "Open ScriptWidget to check access." : "Reminders could not load. Open ScriptWidget to check access."); -} - } +// A random id in UUID format that names one write request. function newRequestID() { - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, key => { const value = Math.floor(Math.random() * 16); return (key === "x" ? value : (value & 3) | 8).toString(16); }); + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (key) => { + const value = Math.floor(Math.random() * 16); + return (key === "x" ? value : (value & 3) | 8).toString(16); + }); } +// The "complete-next" action from widget.json. The request is saved before it is sent +// and removed after it succeeded. If the outcome is unknown, the next tap sends the +// same request again, which cannot complete a second reminder. async function completeNext() { let request = $storage.getJSON("pending-reminder-write"); if (!request.requestID) { - const options = {limit: 1, maxAgeSeconds: 0}; + // maxAgeSeconds: 0 asks for fresh data, never a saved result. + const options = { limit: 1, maxAgeSeconds: 0 }; const parameter = $getenv("widget-param").trim(); - if (parameter) options.listIDs = parameter.split(",").map(id => id.trim()).filter(Boolean); + if (parameter) + options.listIDs = parameter + .split(",") + .map((id) => id.trim()) + .filter(Boolean); const result = await $reminders.items(options); - if (!result.items.length) { $render(Nothing due today); return; } + if (!result.items.length) { + $render(Nothing due today); + return; + } const item = result.items[0]; - request = {requestID: newRequestID(), listID: item.listID, id: item.id, completed: true}; - if (!$storage.setJSON("pending-reminder-write", request)) throw new Error("Could not save the reminder request. Nothing was changed."); + request = { requestID: newRequestID(), listID: item.listID, id: item.id, completed: true }; + if (!$storage.setJSON("pending-reminder-write", request)) + throw new Error("Could not save the reminder request. Nothing was changed."); } + // Needs the "remindersWrite" permission in widget.json. Always await a write. await $reminders.setCompleted(request); $storage.remove("pending-reminder-write"); $render(Reminder completed); @@ -64,34 +120,118 @@ function clearPending() { $render(Pending request cleared. Check Reminders before starting another action.); } +// The time of a reminder in the device's format, or "Today" for one without a time. function reminderTime(item) { if (!item.hasTime) return "Today"; return new Date(item.due).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); } +// Choose a layout. if (size === "action" || size === "function") { $render(Reminder action); } else if (small && (!authorized || failed)) { - $render( - Reminders - {failed ? "Review list access in Settings." : "Connect in ScriptWidget Settings."} - - Open Settings → - ); + // Small and not connected: the whole widget is a link into the ScriptWidget app. + $render( + + + + Reminders + + + {failed ? "Review list access in Settings." : "Connect in ScriptWidget Settings."} + + + + Open Settings → + + + , + ); } else if (size === "accessoryInline") { - $render({items.length ? `${reminderTime(items[0])} ${items[0].title}` : (failed ? "Check Reminders access" : authorized ? "Nothing due today" : "Connect Reminders")}); + // Lock Screen sizes (iPhone and iPad only). + $render( + + {items.length + ? `${reminderTime(items[0])} ${items[0].title}` + : failed + ? "Check Reminders access" + : authorized + ? "Nothing due today" + : "Connect Reminders"} + , + ); } else if (size === "accessoryCircular") { - $render({failed ? "Check" : authorized ? `${items.length} items` : "Connect"}); + $render( + + + + {failed ? "Check" : authorized ? `${items.length} items` : "Connect"} + + , + ); } else { + // Every other size: a header, the reminders, a message, and buttons where there is room. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - - {small ? "AGENDA" : "DUE TODAY"}{stale && Cached} - {items.map(item => {item.title || "Untitled reminder"}{reminderTime(item)})} - {!!message && {message}} - {(!authorized || failed) && !accessory && {small ? "Settings" : "Open ScriptWidget"}} - {!accessory && !small && pendingWrite.requestID && } - {!accessory && !small && authorized && !failed && items.length > 0 && } - {!accessory && } - + + + + + {small ? "AGENDA" : "DUE TODAY"} + + + {stale && ( + + Cached + + )} + + {items.map((item) => ( + + + + + {item.title || "Untitled reminder"} + + + {reminderTime(item)} + + + + + ))} + {/* The message: "No reminders due today.", or what to do about a problem. */} + {!!message && ( + + {message} + + )} + {(!authorized || failed) && !accessory && ( + + + + {small ? "Settings" : "Open ScriptWidget"} + + + )} + {/* The buttons run the actions with these ids from widget.json. */} + {!accessory && !small && pendingWrite.requestID && ( + + )} + {!accessory && !small && authorized && !failed && items.length > 0 && ( + + )} + {!accessory && } + , ); } diff --git a/Gallery/widgets/wallpaper-match/lib/configuration.js b/Gallery/widgets/wallpaper-match/lib/configuration.js index 26de913d..3d1d2d8b 100644 --- a/Gallery/widgets/wallpaper-match/lib/configuration.js +++ b/Gallery/widgets/wallpaper-match/lib/configuration.js @@ -1,39 +1,100 @@ // Package-relative native background selections; rendering never imports images or changes settings. +// +// Settings for Wallpaper Match. main.jsx loads this file and calls +// wallpaperConfiguration.load(). var wallpaperConfiguration = (() => { - const defaults = {title: "My space", caption: "", content: "none", ink: "adaptive", backgrounds: []}; + // Used when nothing has been saved. content is "none", "text" or "date"; ink is the + // text color: "adaptive" (follows dark mode), "light" or "dark". + const defaults = { + title: "My space", + caption: "", + content: "none", + ink: "adaptive", + backgrounds: [], + }; + // The widget sizes that can have a background. const families = ["small", "medium", "large", "extraLarge", "extraLargePortrait"]; const text = (value, length) => typeof value === "string" && value.length <= length; - const validImage = (value) => typeof value === "string" && /^background-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value); + // An image name has the form background-; its file is image/.png. + const validImage = (value) => + typeof value === "string" && + /^background-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value); + // True when the settings have exactly the expected keys and every value is in range. function validate(value) { - if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "backgrounds,caption,content,ink,title" || - !text(value.title, 40) || !text(value.caption, 80) || !["none", "text", "date"].includes(value.content) || !["adaptive", "light", "dark"].includes(value.ink) || - !Array.isArray(value.backgrounds) || value.backgrounds.length > 10) return false; + if ( + !value || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).sort().join(",") !== "backgrounds,caption,content,ink,title" || + !text(value.title, 40) || + !text(value.caption, 80) || + !["none", "text", "date"].includes(value.content) || + !["adaptive", "light", "dark"].includes(value.ink) || + !Array.isArray(value.backgrounds) || + value.backgrounds.length > 10 + ) + return false; + // Each background is one image for one size and one appearance; a pair may appear once. const seen = new Set(); return value.backgrounds.every((asset) => { - if (!asset || typeof asset !== "object" || Array.isArray(asset) || Object.keys(asset).sort().join(",") !== "appearance,family,image,label" || - !families.includes(asset.family) || !["light", "dark"].includes(asset.appearance) || !validImage(asset.image) || - !text(asset.label, 30) || !asset.label.trim() || /[\p{Cc}\p{Cf}]/u.test(asset.label)) return false; + if ( + !asset || + typeof asset !== "object" || + Array.isArray(asset) || + Object.keys(asset).sort().join(",") !== "appearance,family,image,label" || + !families.includes(asset.family) || + !["light", "dark"].includes(asset.appearance) || + !validImage(asset.image) || + !text(asset.label, 30) || + !asset.label.trim() || + /[\p{Cc}\p{Cf}]/u.test(asset.label) + ) + return false; const key = asset.family + "." + asset.appearance; if (seen.has(key)) return false; - seen.add(key); return true; + seen.add(key); + return true; }); } + // Parses a settings string of the form { version: 1, kind: "wallpaper", values }. + // Damaged settings throw an error instead of being replaced by the defaults. function read(raw) { if (raw === "") return defaults; let state; - try { if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096) throw new Error(); state = JSON.parse(raw); } - catch (_) { throw new Error("Saved background settings are invalid. Open Records & Configuration to repair them."); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== "wallpaper" || !validate(state.values)) - throw new Error("Saved background settings are invalid. Open Records & Configuration to repair them."); + try { + // At most 4096 bytes of UTF-8. + if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096) + throw new Error(); + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved background settings are invalid. Open Records & Configuration to repair them.", + ); + } + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== "wallpaper" || + !validate(state.values) + ) + throw new Error( + "Saved background settings are invalid. Open Records & Configuration to repair them.", + ); return state.values; } + // The settings saved in $storage come first; without them the optional file + // wallpaper.json of the package is used, and without that the defaults. function load() { const saved = $storage.getString("recordTemplate.config.v1"); if (saved !== "") return read(saved); if (!$file.exists("wallpaper.json")) return defaults; const portable = $file.read("wallpaper.json"); - if (portable === "") throw new Error("wallpaper.json is empty or unavailable. Restore or repair the package settings."); + if (portable === "") + throw new Error( + "wallpaper.json is empty or unavailable. Restore or repair the package settings.", + ); return read(portable); } - return {read, validate, load}; + return { read, validate, load }; })(); diff --git a/Gallery/widgets/wallpaper-match/main.jsx b/Gallery/widgets/wallpaper-match/main.jsx index aa76aafc..67db1db5 100644 --- a/Gallery/widgets/wallpaper-match/main.jsx +++ b/Gallery/widgets/wallpaper-match/main.jsx @@ -1,33 +1,122 @@ // Import and calibrate your own background in Records & Configuration. // Crops match one Home Screen size, position and light/dark appearance. -if (!$import("lib/configuration.js")) throw new Error("Install the complete Wallpaper Match template."); +// +// This template shows a full-size image behind text, chosen by widget size and by light +// or dark mode. Try changing the fonts, or the texts shown while no image is set. + +// $import runs lib/configuration.js from this package and returns false when that fails. +// The file defines wallpaperConfiguration. +if (!$import("lib/configuration.js")) + throw new Error("Install the complete Wallpaper Match template."); +// The saved settings: title, caption, what to show, text color and the list of crops. const options = wallpaperConfiguration.load(); -const family = $getenv("widget-size"), appearance = $device.isdarkmode() ? "dark" : "light"; -const color = options.ink === "light" || (options.ink === "adaptive" && appearance === "dark") ? "#ffffff" : "#111827"; +// The size being drawn ("small", "medium", …) and the current appearance. +const family = $getenv("widget-size"), + appearance = $device.isdarkmode() ? "dark" : "light"; +// Text color: white or near-black, as set in the settings or following dark mode. +const color = + options.ink === "light" || (options.ink === "adaptive" && appearance === "dark") + ? "#ffffff" + : "#111827"; +// "timeline-date" is the moment this entry is drawn for, which is later than now when the +// system prepares the widget in advance. const referenceDate = new Date($getenv("timeline-date") || Date.now()); if (family === "accessoryInline") { - $render(options.content === "date" ? : {options.title || "Wallpaper Match"}); + // Lock Screen sizes (iPhone and iPad only) have no background image: a text or the date. + $render( + options.content === "date" ? ( + + ) : ( + {options.title || "Wallpaper Match"} + ), + ); } else if (family === "accessoryCircular") { - $render({options.content === "date" ? String(referenceDate.getDate()) : "Match"}); + $render( + + + + {options.content === "date" ? String(referenceDate.getDate()) : "Match"} + + , + ); } else if (family === "accessoryRectangular") { - $render({options.title || "Wallpaper Match"}{options.content === "date" ? : {options.caption || "Backgrounds apply on the Home Screen"}}); + $render( + + {options.title || "Wallpaper Match"} + {options.content === "date" ? ( + + ) : ( + {options.caption || "Backgrounds apply on the Home Screen"} + )} + , + ); } else { - const asset = options.backgrounds.find((item) => item.family === family && item.appearance === appearance); + // Home Screen sizes: find the crop saved for this size and appearance. + const asset = options.backgrounds.find( + (item) => item.family === family && item.appearance === appearance, + ); + // $file.exists checks for a file inside this package; a crop is stored as image/.png. const available = asset && $file.exists("image/" + asset.image + ".png"); if (!available) { - $render( - - {asset ? "Restore this crop" : "Match your wallpaper"} - {asset ? "The selected image file is unavailable." : `Add a ${appearance} crop for this size in Records & Configuration.`} - ); + // No crop, or its file is gone: say what to do. frame="max" fills the widget; padding + // is the space around the content, in points. + $render( + + + {asset ? "Restore this crop" : "Match your wallpaper"} + + {asset + ? "The selected image file is unavailable." + : `Add a ${appearance} crop for this size in Records & Configuration.`} + + , + ); } else { - $render( - - {options.content !== "none" && - {options.content === "date" && } - {options.title && {family === "small" ? Array.from(options.title.replace(/\s+/g, " ")).slice(0, 16).join("") : options.title}} - {options.caption && {family === "small" ? Array.from(options.caption.replace(/\s+/g, " ")).slice(0, 24).join("") : options.caption}} - } - ); + // The image fills the widget and the text lies over it in a . + $render( + + {/* mode="fill" covers the whole frame and clip="rect" cuts off what sticks out. */} + {/* accentedRenderingMode="fullColor" keeps the colors in tinted widget appearances. */} + + {options.content !== "none" && ( + + {options.content === "date" && ( + + )} + {/* The small widget cuts long texts: 16 characters of title, 24 of caption. */} + {options.title && ( + + {family === "small" + ? Array.from(options.title.replace(/\s+/g, " ")).slice(0, 16).join("") + : options.title} + + )} + {options.caption && ( + + {family === "small" + ? Array.from(options.caption.replace(/\s+/g, " ")).slice(0, 24).join("") + : options.caption} + + )} + + )} + , + ); } } diff --git a/Gallery/widgets/weather-now/lib/weather.js b/Gallery/widgets/weather-now/lib/weather.js index 397b0829..bd6e6cdb 100644 --- a/Gallery/widgets/weather-now/lib/weather.js +++ b/Gallery/widgets/weather-now/lib/weather.js @@ -1,204 +1,527 @@ // MET Norway Locationforecast 2.0. Forecasts are model data, not observations. // https://api.met.no/doc/TermsOfService · https://api.met.no/doc/License +// main.jsx imports this file ("lib/weather.js") and then uses `localWeather`. +// It chooses the place, asks MET Norway for its forecast and keeps a copy in $storage. var localWeather = (() => { - const cacheKey = "weather.met.v1", hour = 3600000; - const defaults = {city:"",latitude:0,longitude:0,useLocation:true,unit:"c"}; - const numeric = (value,min,max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; - const keys = object => object && typeof object === "object" && !Array.isArray(object) ? Object.keys(object).sort().join(",") : ""; + // The storage key of the saved forecasts, and one hour in milliseconds. + const cacheKey = "weather.met.v1", + hour = 3600000; + // The settings. `unit` is "c" or "f"; `city` with its coordinates is the saved city. + const defaults = { city: "", latitude: 0, longitude: 0, useLocation: true, unit: "c" }; + // True for a real number between min and max. + const numeric = (value, min, max) => + typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; + // The keys of a plain object, sorted and joined ("a,b,c"); "" for anything else. + const keys = (object) => + object && typeof object === "object" && !Array.isArray(object) + ? Object.keys(object).sort().join(",") + : ""; function validOptions(value) { - return keys(value) === "city,latitude,longitude,unit,useLocation" && typeof value.city === "string" && value.city.length <= 60 && - numeric(value.latitude,-90,90) && numeric(value.longitude,-180,180) && typeof value.useLocation === "boolean" && ["c","f"].includes(value.unit); + return ( + keys(value) === "city,latitude,longitude,unit,useLocation" && + typeof value.city === "string" && + value.city.length <= 60 && + numeric(value.latitude, -90, 90) && + numeric(value.longitude, -180, 180) && + typeof value.useLocation === "boolean" && + ["c", "f"].includes(value.unit) + ); } - function options(raw,parameter) { - let value = {...defaults}; + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter: JSON, or latitude,longitude,City. + function options(raw, parameter) { + let value = { ...defaults }; if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || keys(state) !== "kind,values,version" || state.version !== 1 || state.kind !== "weather" || !validOptions(state.values)) throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); + } + if ( + typeof raw !== "string" || + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. + unescape(encodeURIComponent(raw)).length > 4096 || + keys(state) !== "kind,values,version" || + state.version !== 1 || + state.kind !== "weather" || + !validOptions(state.values) + ) + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); value = state.values; } parameter = (parameter || "").trim(); if (parameter) { if (parameter[0] === "{") { let custom; - try { custom = JSON.parse(parameter); } catch (_) { throw new Error("Weather parameters must be valid JSON."); } - if (!custom || Array.isArray(custom) || Object.keys(custom).some(key => !Object.prototype.hasOwnProperty.call(defaults,key))) throw new Error("Weather settings accept city, latitude, longitude, useLocation and unit only."); - value = {...value,...custom}; + try { + custom = JSON.parse(parameter); + } catch (_) { + throw new Error("Weather parameters must be valid JSON."); + } + if ( + !custom || + Array.isArray(custom) || + Object.keys(custom).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error( + "Weather settings accept city, latitude, longitude, useLocation and unit only.", + ); + value = { ...value, ...custom }; } else { - const parts = parameter.split(",").map(value => value.trim()); - if (parts.length < 2 || parts.length > 3 || parts.slice(0,2).some(value => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value))) throw new Error("Use latitude,longitude or JSON weather settings."); - value = {...value,city:parts[2] || "Selected city",latitude:Number(parts[0]),longitude:Number(parts[1]),useLocation:false}; + // latitude,longitude with an optional city name. A fixed place turns location off. + const parts = parameter.split(",").map((value) => value.trim()); + if ( + parts.length < 2 || + parts.length > 3 || + parts.slice(0, 2).some((value) => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) + ) + throw new Error("Use latitude,longitude or JSON weather settings."); + value = { + ...value, + city: parts[2] || "Selected city", + latitude: Number(parts[0]), + longitude: Number(parts[1]), + useLocation: false, + }; } } - if (!validOptions(value)) throw new Error("Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit."); + if (!validOptions(value)) + throw new Error( + "Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit.", + ); return value; } - const rounded = value => Number(value.toFixed(2)); - const placeKey = (source,latitude,longitude) => `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; - const validHTTPDate = value => typeof value === "string" && /^[A-Za-z0-9,: -]{1,128}$/.test(value) && Number.isFinite(Date.parse(value)); + // Coordinates are rounded to 2 decimals, roughly a kilometre, before use. + const rounded = (value) => Number(value.toFixed(2)); + // The name of a place in the saved copy, such as "manual:59.91,10.75". + const placeKey = (source, latitude, longitude) => + `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; + const validHTTPDate = (value) => + typeof value === "string" && + /^[A-Za-z0-9,: -]{1,128}$/.test(value) && + Number.isFinite(Date.parse(value)); + // One forecast point: time (ms), temperature (°C), humidity (%), wind (m/s), symbol code. function validPoint(point) { - return keys(point) === "humidity,symbol,temperature,time,wind" && Number.isSafeInteger(point.time) && point.time > 0 && - numeric(point.temperature,-100,70) && (point.humidity === null || numeric(point.humidity,0,100)) && - (point.wind === null || numeric(point.wind,0,160)) && typeof point.symbol === "string" && /^[a-z_]{1,64}$/.test(point.symbol); + return ( + keys(point) === "humidity,symbol,temperature,time,wind" && + Number.isSafeInteger(point.time) && + point.time > 0 && + numeric(point.temperature, -100, 70) && + (point.humidity === null || numeric(point.humidity, 0, 100)) && + (point.wind === null || numeric(point.wind, 0, 160)) && + typeof point.symbol === "string" && + /^[a-z_]{1,64}$/.test(point.symbol) + ); } - function validPlaceKey(key,source) { + function validPlaceKey(key, source) { if (typeof key !== "string") return false; const match = /^(manual|location):(-?\d{1,3}\.\d{2}),(-?\d{1,3}\.\d{2})$/.exec(key); - return !!match && match[1] === source && numeric(Number(match[2]),-90,90) && numeric(Number(match[3]),-180,180); + return ( + !!match && + match[1] === source && + numeric(Number(match[2]), -90, 90) && + numeric(Number(match[3]), -180, 180) + ); } - function packets(raw,now) { + // Read the saved copy: up to 4 places with up to 24 forecast points each. + // Anything unexpected gives an empty list, so a damaged copy is simply loaded again. + function packets(raw, now) { try { if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 64000) return []; const state = JSON.parse(raw); - if (keys(state) !== "entries,version" || state.version !== 1 || !Array.isArray(state.entries) || state.entries.length > 4) return []; + if ( + keys(state) !== "entries,version" || + state.version !== 1 || + !Array.isArray(state.entries) || + state.entries.length > 4 + ) + return []; const names = new Set(); for (const entry of state.entries) { - if (keys(entry) !== "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || - !["manual","location"].includes(entry.source) || !validPlaceKey(entry.key,entry.source) || names.has(entry.key) || - !Number.isSafeInteger(entry.checkedAt) || entry.checkedAt < 0 || entry.checkedAt > now+300000 || - !Number.isSafeInteger(entry.nextRequestAt) || entry.nextRequestAt < entry.checkedAt || entry.nextRequestAt > entry.checkedAt+7*24*hour || - !Number.isSafeInteger(entry.updatedAt) || entry.updatedAt < 0 || entry.updatedAt > now+300000 || - typeof entry.failed !== "boolean" || typeof entry.deprecated !== "boolean" || - (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || !Array.isArray(entry.points) || entry.points.length > 24 || - !entry.points.every(validPoint) || entry.points.some((point,index) => index > 0 && point.time <= entry.points[index-1].time) || - (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0)) return []; + if ( + keys(entry) !== + "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || + !["manual", "location"].includes(entry.source) || + !validPlaceKey(entry.key, entry.source) || + names.has(entry.key) || + !Number.isSafeInteger(entry.checkedAt) || + entry.checkedAt < 0 || + entry.checkedAt > now + 300000 || + !Number.isSafeInteger(entry.nextRequestAt) || + entry.nextRequestAt < entry.checkedAt || + entry.nextRequestAt > entry.checkedAt + 7 * 24 * hour || + !Number.isSafeInteger(entry.updatedAt) || + entry.updatedAt < 0 || + entry.updatedAt > now + 300000 || + typeof entry.failed !== "boolean" || + typeof entry.deprecated !== "boolean" || + (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || + !Array.isArray(entry.points) || + entry.points.length > 24 || + !entry.points.every(validPoint) || + entry.points.some( + (point, index) => index > 0 && point.time <= entry.points[index - 1].time, + ) || + (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0) + ) + return []; names.add(entry.key); } return state.entries; - } catch (_) { return []; } + } catch (_) { + return []; + } } - function publish(packet,now,projection) { + // Save the forecast of one place next to the others; only one place found by location + // is kept. compareAndSetString writes only if the stored text is still `raw`; if + // something else saved in between, read again and retry. + function publish(packet, now, projection) { if (projection) return false; - for (let attempt=0;attempt<4;attempt++) { - const raw = $storage.getString(cacheKey), entries = packets(raw,now); - const previous = entries.find(entry => entry.key === packet.key); - if (previous && (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt)) return true; - const next = [packet,...entries.filter(entry => entry.key !== packet.key && (packet.source !== "location" || entry.source !== "location"))].sort((a,b) => b.checkedAt-a.checkedAt).slice(0,4); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:next}))) return true; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + entries = packets(raw, now); + const previous = entries.find((entry) => entry.key === packet.key); + if ( + previous && + (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt) + ) + return true; + const next = [ + packet, + ...entries.filter( + (entry) => + entry.key !== packet.key && + (packet.source !== "location" || entry.source !== "location"), + ), + ] + .sort((a, b) => b.checkedAt - a.checkedAt) + .slice(0, 4); + if ( + $storage.compareAndSetString(cacheKey, raw, JSON.stringify({ version: 1, entries: next })) + ) + return true; } return false; } - function expires(headers,now) { + // When to ask again: when the response expires (Expires, else Cache-Control max-age), + // or in one hour without a usable time. Never sooner than 15 minutes, plus up to 5 + // random minutes. + function expires(headers, now) { let until = Date.parse(headers.expires || ""); const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"] || ""); - if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]),604800)*1000; - if (!Number.isFinite(until) || until > now+7*24*hour) until = now+hour; - return Math.round(Math.max(now+900000,until)+Math.random()*300000); + if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]), 604800) * 1000; + if (!Number.isFinite(until) || until > now + 7 * 24 * hour) until = now + hour; + return Math.round(Math.max(now + 900000, until) + Math.random() * 300000); } - function parseResponse(body,place,now,headers,status) { - if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) throw new Error("Invalid forecast"); - const data = JSON.parse(body), meta = data?.properties?.meta, times = data?.properties?.timeseries; + // Check the answer of MET Norway and keep up to 24 points, starting 2 hours ago. + function parseResponse(body, place, now, headers, status) { + if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) + throw new Error("Invalid forecast"); + const data = JSON.parse(body), + meta = data?.properties?.meta, + times = data?.properties?.timeseries; const updatedAt = Date.parse(meta?.updated_at || ""); - if (!Number.isFinite(updatedAt) || updatedAt > now+300000 || now-updatedAt > 24*hour || meta?.units?.air_temperature !== "celsius" || meta?.units?.wind_speed !== "m/s" || !Array.isArray(times) || times.length < 1 || times.length > 250) throw new Error("Invalid forecast"); + if ( + !Number.isFinite(updatedAt) || + updatedAt > now + 300000 || + now - updatedAt > 24 * hour || + meta?.units?.air_temperature !== "celsius" || + meta?.units?.wind_speed !== "m/s" || + !Array.isArray(times) || + times.length < 1 || + times.length > 250 + ) + throw new Error("Invalid forecast"); const points = []; for (const item of times) { const time = Date.parse(item?.time || ""); if (!Number.isFinite(time)) throw new Error("Invalid forecast time"); - if (time < now-2*hour || points.length >= 24) continue; - const details = item?.data?.instant?.details, summary = item?.data?.next_1_hours?.summary || item?.data?.next_6_hours?.summary || item?.data?.next_12_hours?.summary; - const point = {time,temperature:details?.air_temperature,humidity:meta.units.relative_humidity === "%" && numeric(details?.relative_humidity,0,100) ? details.relative_humidity : null, - wind:numeric(details?.wind_speed,0,160) ? details.wind_speed : null,symbol:summary?.symbol_code || "unknown"}; - if (!validPoint(point) || (points.length && time <= points[points.length-1].time)) throw new Error("Invalid forecast point"); + if (time < now - 2 * hour || points.length >= 24) continue; + const details = item?.data?.instant?.details, + summary = + item?.data?.next_1_hours?.summary || + item?.data?.next_6_hours?.summary || + item?.data?.next_12_hours?.summary; + const point = { + time, + temperature: details?.air_temperature, + humidity: + meta.units.relative_humidity === "%" && numeric(details?.relative_humidity, 0, 100) + ? details.relative_humidity + : null, + wind: numeric(details?.wind_speed, 0, 160) ? details.wind_speed : null, + symbol: summary?.symbol_code || "unknown", + }; + if (!validPoint(point) || (points.length && time <= points[points.length - 1].time)) + throw new Error("Invalid forecast point"); points.push(point); } - if (!points.some(point=>Math.abs(point.time-now)<=90*60000)) throw new Error("Forecast is unavailable"); - return {key:place.key,source:place.source,updatedAt,checkedAt:now,nextRequestAt:expires(headers,now), - lastModified:validHTTPDate(headers["last-modified"]) && Date.parse(headers["last-modified"]) <= now+300000 ? headers["last-modified"] : "",points,failed:false,deprecated:status===203}; + // One of the points must lie within 90 minutes of now. + if (!points.some((point) => Math.abs(point.time - now) <= 90 * 60000)) + throw new Error("Forecast is unavailable"); + // Status 203 is how MET Norway announces that this version of the service will end. + return { + key: place.key, + source: place.source, + updatedAt, + checkedAt: now, + nextRequestAt: expires(headers, now), + lastModified: + validHTTPDate(headers["last-modified"]) && + Date.parse(headers["last-modified"]) <= now + 300000 + ? headers["last-modified"] + : "", + points, + failed: false, + deprecated: status === 203, + }; } - function pointAt(packet,now) { - if (!packet || !packet.points.length || now-packet.updatedAt > 24*hour || packet.updatedAt > now+300000) return null; - const earlier = packet.points.filter(point => point.time <= now); - const point = earlier[earlier.length-1] || packet.points[0]; - return Math.abs(point.time-now) <= 90*60000 ? point : null; + // The forecast point for now: the latest one that is not in the future, provided it is + // within 90 minutes of now and the forecast is less than a day old. + function pointAt(packet, now) { + if ( + !packet || + !packet.points.length || + now - packet.updatedAt > 24 * hour || + packet.updatedAt > now + 300000 + ) + return null; + const earlier = packet.points.filter((point) => point.time <= now); + const point = earlier[earlier.length - 1] || packet.points[0]; + return Math.abs(point.time - now) <= 90 * 60000 ? point : null; } + // Turn a symbol code such as "partlycloudy_night" into a title and an SF Symbol name. function condition(symbol) { const night = symbol.endsWith("_night"); - if (symbol.includes("thunder")) return {title:"Thunderstorms",icon:"cloud.bolt.rain.fill"}; - if (symbol.includes("snow") || symbol.includes("sleet")) return {title:"Snow or sleet",icon:"cloud.snow.fill"}; - if (symbol.includes("rain")) return {title:"Rain",icon:"cloud.rain.fill"}; - if (symbol.includes("fog")) return {title:"Fog",icon:"cloud.fog.fill"}; - if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) return {title:"Partly cloudy",icon:night ? "cloud.moon.fill" : "cloud.sun.fill"}; - if (symbol.startsWith("clearsky")) return {title:"Clear",icon:night ? "moon.stars.fill" : "sun.max.fill"}; - if (symbol.startsWith("cloudy")) return {title:"Cloudy",icon:"cloud.fill"}; - return {title:"Forecast",icon:"cloud.fill"}; + if (symbol.includes("thunder")) return { title: "Thunderstorms", icon: "cloud.bolt.rain.fill" }; + if (symbol.includes("snow") || symbol.includes("sleet")) + return { title: "Snow or sleet", icon: "cloud.snow.fill" }; + if (symbol.includes("rain")) return { title: "Rain", icon: "cloud.rain.fill" }; + if (symbol.includes("fog")) return { title: "Fog", icon: "cloud.fog.fill" }; + if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) + return { title: "Partly cloudy", icon: night ? "cloud.moon.fill" : "cloud.sun.fill" }; + if (symbol.startsWith("clearsky")) + return { title: "Clear", icon: night ? "moon.stars.fill" : "sun.max.fill" }; + if (symbol.startsWith("cloudy")) return { title: "Cloudy", icon: "cloud.fill" }; + return { title: "Forecast", icon: "cloud.fill" }; } - const locationAllowed = () => $location.isAvailable() && ["authorizedWhenInUse","authorizedAlways"].includes($location.authorizationStatus()) && $location.isAuthorizedForWidgetUpdates(); - function clearLocationCache(now,projection) { + // True when location exists here, the app may use it and widgets may use it too. + const locationAllowed = () => + $location.isAvailable() && + ["authorizedWhenInUse", "authorizedAlways"].includes($location.authorizationStatus()) && + $location.isAuthorizedForWidgetUpdates(); + // Forget the forecast saved for a location once location is no longer allowed. + function clearLocationCache(now, projection) { if (projection) return; - for (let attempt=0;attempt<4;attempt++) { - const raw=$storage.getString(cacheKey), filtered=packets(raw,now).filter(entry=>entry.source!=="location"); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:filtered}))) return; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + filtered = packets(raw, now).filter((entry) => entry.source !== "location"); + if ( + $storage.compareAndSetString( + cacheKey, + raw, + JSON.stringify({ version: 1, entries: filtered }), + ) + ) + return; } } - async function revoked(config,now,projection) { - clearLocationCache(now,projection); - return config.city.trim() ? await load({...config,useLocation:false},now,projection) : {available:false,title:"Location access changed",hint:"Choose a saved city to continue."}; + // Location was allowed and no longer is: use the saved city, if there is one. + async function revoked(config, now, projection) { + clearLocationCache(now, projection); + return config.city.trim() + ? await load({ ...config, useLocation: false }, now, projection) + : { + available: false, + title: "Location access changed", + hint: "Choose a saved city to continue.", + }; } - async function load(config,now,projection) { - let entries = packets($storage.getString(cacheKey),now); + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which asks neither for the position + // nor for a new forecast. + async function load(config, now, projection) { + let entries = packets($storage.getString(cacheKey), now); const authorized = locationAllowed(); - if (!authorized && entries.some(entry => entry.source === "location")) { - entries = entries.filter(entry => entry.source !== "location"); - clearLocationCache(now,projection); + if (!authorized && entries.some((entry) => entry.source === "location")) { + entries = entries.filter((entry) => entry.source !== "location"); + clearLocationCache(now, projection); } + // Choose the place: the current position, else the last saved one, else the city. let place = null; if (config.useLocation && authorized) { if (!projection) { try { - const location = await $location.current({maxAge:3600}); - const stale = location.isStale === true || (typeof location.age === "number" && location.age > 3600); - if (!stale && numeric(location.latitude,-90,90) && numeric(location.longitude,-180,180)) place = {source:"location",name:location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area",latitude:rounded(location.latitude),longitude:rounded(location.longitude)}; + // maxAge: 3600 accepts a position up to one hour old; `age` is in seconds. + const location = await $location.current({ maxAge: 3600 }); + const stale = + location.isStale === true || (typeof location.age === "number" && location.age > 3600); + if ( + !stale && + numeric(location.latitude, -90, 90) && + numeric(location.longitude, -180, 180) + ) + place = { + source: "location", + name: + location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area", + latitude: rounded(location.latitude), + longitude: rounded(location.longitude), + }; } catch (_) {} } if (!place && (!config.city.trim() || projection)) { - const saved = entries.find(entry => entry.source === "location" && pointAt(entry,now)); - if (saved) place = {source:"location",name:"Last location",key:saved.key,skipNetwork:true}; + const saved = entries.find((entry) => entry.source === "location" && pointAt(entry, now)); + if (saved) + place = { source: "location", name: "Last location", key: saved.key, skipNetwork: true }; } } - if (!place && config.city.trim()) place = {source:"manual",name:config.city,latitude:rounded(config.latitude),longitude:rounded(config.longitude)}; - if (!place) return {available:false,title:"Choose a saved city",hint:"Open Records & Configuration. Location is optional."}; - place.key ??= placeKey(place.source,place.latitude,place.longitude); + if (!place && config.city.trim()) + place = { + source: "manual", + name: config.city, + latitude: rounded(config.latitude), + longitude: rounded(config.longitude), + }; + if (!place) + return { + available: false, + title: "Choose a saved city", + hint: "Open Records & Configuration. Location is optional.", + }; + place.key ??= placeKey(place.source, place.latitude, place.longitude); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } - let packet = entries.find(entry => entry.key === place.key), saved = true, fromCache = true; + let packet = entries.find((entry) => entry.key === place.key), + saved = true, + fromCache = true; + // Ask MET Norway only when there is no saved forecast for the place or it is due. if (!projection && !place.skipNetwork && (!packet || now >= packet.nextRequestAt)) { try { - const headers = {"User-Agent":"ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)","Accept":"application/json"}; + const headers = { + "User-Agent": "ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)", + Accept: "application/json", + }; if (packet?.lastModified) headers["If-Modified-Since"] = packet.lastModified; - const response = await $http.getResponse(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`,{headers,timeoutInterval:4}); + // The call resolves to { status, body, headers }, also for statuses such as 304. + const response = await $http.getResponse( + `https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`, + { headers, timeoutInterval: 4 }, + ); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } const responseHeaders = response.headers || {}; - if (response.status === 304 && pointAt(packet,now)) packet = {...packet,checkedAt:now,nextRequestAt:expires(responseHeaders,now),failed:false}; - else if (response.status === 200 || response.status === 203) { packet = parseResponse(response.body,place,now,responseHeaders,response.status);fromCache=false; } - else { + // 304: not changed since the last request, so the saved points stay. + if (response.status === 304 && pointAt(packet, now)) + packet = { + ...packet, + checkedAt: now, + nextRequestAt: expires(responseHeaders, now), + failed: false, + }; + else if (response.status === 200 || response.status === 203) { + packet = parseResponse(response.body, place, now, responseHeaders, response.status); + fromCache = false; + } else { + // Another status: retry at the Retry-After time, 15 minutes to 24 hours from now. const retry = responseHeaders["retry-after"] || ""; - let until = /^\d+$/.test(retry) ? now+Number(retry)*1000 : Date.parse(retry); - if (!Number.isFinite(until)) until = now+900000; - const error = new Error("Refresh unavailable");error.retryAt=Math.min(now+24*hour,Math.max(now+900000,until));throw error; + let until = /^\d+$/.test(retry) ? now + Number(retry) * 1000 : Date.parse(retry); + if (!Number.isFinite(until)) until = now + 900000; + const error = new Error("Refresh unavailable"); + error.retryAt = Math.min(now + 24 * hour, Math.max(now + 900000, until)); + throw error; } - saved = publish(packet,now,projection); + saved = publish(packet, now, projection); } catch (error) { - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const retryAt = numeric(error?.retryAt,now,now+24*hour) ? error.retryAt : now+900000; - packet = packet || {key:place.key,source:place.source,updatedAt:0,lastModified:"",points:[],deprecated:false}; - packet = {...packet,checkedAt:now,nextRequestAt:Math.round(retryAt),failed:true}; - saved = publish(packet,now,projection); + // No usable answer: keep the saved points and note the failure. + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const retryAt = numeric(error?.retryAt, now, now + 24 * hour) + ? error.retryAt + : now + 900000; + packet = packet || { + key: place.key, + source: place.source, + updatedAt: 0, + lastModified: "", + points: [], + deprecated: false, + }; + packet = { ...packet, checkedAt: now, nextRequestAt: Math.round(retryAt), failed: true }; + saved = publish(packet, now, projection); } } - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const point = pointAt(packet,now); - if (!point) return {available:false,title:"Forecast unavailable",hint:"Check your connection or saved city, then refresh."}; - const celsius = config.unit === "c", temperature = value => Math.round(celsius ? value : value*9/5+32) + (celsius ? "°C" : "°F"); - const age = Math.max(0,Math.floor((now-packet.updatedAt)/60000)); - const statusText = packet.deprecated ? "Service update needed" : !saved ? "Cache unavailable" : packet.failed ? "Saved forecast · refresh unavailable" : place.skipNetwork ? "Saved forecast · last location" : fromCache ? "Saved forecast" : "Forecast"; - const statusShort = packet.deprecated ? "Service update" : !saved ? "No cache" : packet.failed ? "Saved · refresh failed" : place.skipNetwork ? "Last location" : fromCache ? "Saved forecast" : "Forecast"; - return {available:true,statusShort,name:place.name,source:place.source,condition:condition(point.symbol),temperature:temperature(point.temperature), - humidity:point.humidity === null ? "—" : Math.round(point.humidity)+"%",wind:point.wind === null ? "—" : (point.wind*3.6).toFixed(1)+" km/h", - updated:age < 1 ? "Updated just now" : age < 60 ? `Updated ${age}m ago` : `Updated ${Math.floor(age/60)}h ago`,status:statusText, - upcoming:packet.points.filter(value => value.time > point.time).slice(0,4).map(value => ({label:"+"+Math.max(1,Math.round((value.time-now)/hour))+"h",temperature:temperature(value.temperature),condition:condition(value.symbol)}))}; + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const point = pointAt(packet, now); + if (!point) + return { + available: false, + title: "Forecast unavailable", + hint: "Check your connection or saved city, then refresh.", + }; + // Temperatures are saved in °C and converted for display. + const celsius = config.unit === "c", + temperature = (value) => + Math.round(celsius ? value : (value * 9) / 5 + 32) + (celsius ? "°C" : "°F"); + // Minutes since MET Norway updated the forecast. + const age = Math.max(0, Math.floor((now - packet.updatedAt) / 60000)); + const statusText = packet.deprecated + ? "Service update needed" + : !saved + ? "Cache unavailable" + : packet.failed + ? "Saved forecast · refresh unavailable" + : place.skipNetwork + ? "Saved forecast · last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + const statusShort = packet.deprecated + ? "Service update" + : !saved + ? "No cache" + : packet.failed + ? "Saved · refresh failed" + : place.skipNetwork + ? "Last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + // The result for main.jsx. Wind is converted from m/s to km/h (× 3.6). + // `upcoming` holds the next 4 points, with labels such as "+3h". + return { + available: true, + statusShort, + name: place.name, + source: place.source, + condition: condition(point.symbol), + temperature: temperature(point.temperature), + humidity: point.humidity === null ? "—" : Math.round(point.humidity) + "%", + wind: point.wind === null ? "—" : (point.wind * 3.6).toFixed(1) + " km/h", + updated: + age < 1 + ? "Updated just now" + : age < 60 + ? `Updated ${age}m ago` + : `Updated ${Math.floor(age / 60)}h ago`, + status: statusText, + upcoming: packet.points + .filter((value) => value.time > point.time) + .slice(0, 4) + .map((value) => ({ + label: "+" + Math.max(1, Math.round((value.time - now) / hour)) + "h", + temperature: temperature(value.temperature), + condition: condition(value.symbol), + })), + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Gallery/widgets/weather-now/main.jsx b/Gallery/widgets/weather-now/main.jsx index eefd33f5..883547ca 100644 --- a/Gallery/widgets/weather-now/main.jsx +++ b/Gallery/widgets/weather-now/main.jsx @@ -2,25 +2,189 @@ // Optional instance parameter: latitude,longitude,City or JSON weather settings. // Forecast data: MET Norway (CC BY 4.0). No API key; Expires/conditional requests // and a bounded four-place cache reduce traffic. No exact refresh guarantee. -if (!$import("lib/weather.js")) throw new Error("Install the complete weather template, including lib/weather.js."); -const config = localWeather.options($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); -const weather = await localWeather.load(config,Date.now(),$getenv("timeline-is-projection") === "true"); -const size = $getenv("widget-size"), compact = size === "small"; +// +// The location API runs on iPhone and iPad, and on Android, where widgets see the position +// saved while the app was open. It does not run on Mac, Windows or Linux; there the saved +// city is used. +// This template shows a widget that downloads data, keeps a cache and explains every +// failure. That work is in lib/weather.js; try changing the layouts and colors here. +// widget.json declares the "location", "network" and "storage" permissions, and the host +// api.met.no in networkDomains. + +// $import runs lib/weather.js from this package and returns false when that fails. +// The file defines localWeather. +if (!$import("lib/weather.js")) + throw new Error("Install the complete weather template, including lib/weather.js."); +// The settings: those saved in $storage, changed by the widget parameter (the parameter +// text set for this widget) when there is one. +const config = localWeather.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Load the forecast. The third argument is true when the system draws a future timeline +// entry in advance; such an entry only reads the cache. +const weather = await localWeather.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … +const size = $getenv("widget-size"), + compact = size === "small"; +// No forecast to show: a title and a hint, in a form that fits each size. if (!weather.available) { if (size === "accessoryInline") $render({weather.title}); - else if (size === "accessoryCircular") $render(); - else if (size === "accessoryRectangular") $render({weather.title}Open ScriptWidget to configure weather.); - else $render({weather.title}{weather.hint}); + else if (size === "accessoryCircular") $render(); + else if (size === "accessoryRectangular") + $render( + + {weather.title} + Open ScriptWidget to configure weather. + , + ); + else + $render( + + + + {weather.title} + + + {weather.hint} + + , + ); } else if (size === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only). $render({weather.temperature + " · " + weather.condition.title}); } else if (size === "accessoryCircular") { - $render({weather.temperature}); + $render( + + + + {weather.temperature} + + , + ); } else if (size === "accessoryRectangular") { - $render({weather.name + " · " + weather.temperature}{weather.condition.title}); + $render( + + + + {weather.name + " · " + weather.temperature} + {weather.condition.title} + + , + ); } else if (compact) { - $render({Array.from(weather.name).slice(0,12).join("")}{weather.temperature}{weather.condition.title}{weather.statusShort}{weather.updated}MET Norway); + // Small: place, temperature, condition and how fresh the data is. The forecast is + // licensed CC BY 4.0, so the Home Screen layouts name the source. + $render( + + + {Array.from(weather.name).slice(0, 12).join("")} + + + + {weather.temperature} + + + + + + {weather.condition.title} + + + {weather.statusShort} + + + {weather.updated} + + + MET Norway + + , + ); } else if (size === "medium") { - $render({weather.name}{weather.condition.title}{weather.temperature}{weather.updated}MET Norway{weather.status}); + // Medium: icon, place and temperature in one row. + $render( + + + + + + {weather.name} + + + {weather.condition.title} + + + + + {weather.temperature} + + + + + {weather.updated} + + + + MET Norway + + + + {weather.status} + + , + ); } else { - $render({weather.name}{weather.condition.title}{weather.temperature}{"Wind " + weather.wind}{"Humidity " + weather.humidity}{weather.upcoming.map(point => {point.label}{point.temperature})}{weather.status + " · " + weather.updated}MET Norway · CC BY 4.0); + // Large and extra large add wind, humidity and the next forecast points. + $render( + + + + + {weather.name} + + + {weather.condition.title} + + + + + + + {weather.temperature} + + + + {"Wind " + weather.wind} + + + + {"Humidity " + weather.humidity} + + + + {weather.upcoming.map((point) => ( + + + {point.label} + + + + {point.temperature} + + + ))} + + + {weather.status + " · " + weather.updated} + + + MET Norway · CC BY 4.0 + + , + ); } diff --git a/Linux/Cargo.lock b/Linux/Cargo.lock index 189cedb2..0a0fcd83 100644 --- a/Linux/Cargo.lock +++ b/Linux/Cargo.lock @@ -6164,7 +6164,7 @@ dependencies = [ [[package]] name = "sw-cli" -version = "0.1.3" +version = "0.1.4" dependencies = [ "flate2", "getrandom 0.3.4", @@ -6179,7 +6179,7 @@ dependencies = [ [[package]] name = "sw-core" -version = "0.1.3" +version = "0.1.4" dependencies = [ "cc", "flate2", @@ -6203,7 +6203,7 @@ dependencies = [ [[package]] name = "sw-host" -version = "0.1.3" +version = "0.1.4" dependencies = [ "getrandom 0.3.4", "libc", @@ -6217,14 +6217,14 @@ dependencies = [ [[package]] name = "sw-quickjs" -version = "0.1.3" +version = "0.1.4" dependencies = [ "cc", ] [[package]] name = "sw-render" -version = "0.1.3" +version = "0.1.4" dependencies = [ "serde", "serde_json", @@ -6235,7 +6235,7 @@ dependencies = [ [[package]] name = "sw-studio" -version = "0.1.3" +version = "0.1.4" dependencies = [ "futures", "getrandom 0.3.4", diff --git a/Linux/Cargo.toml b/Linux/Cargo.toml index 972bcde8..d6e2ddfb 100644 --- a/Linux/Cargo.toml +++ b/Linux/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/sw-quickjs", "crates/sw-core", "crates/sw-render", "crates/sw-cli", "crates/sw-host", "crates/sw-studio"] [workspace.package] -version = "0.1.3" +version = "0.1.4" edition = "2024" license = "Apache-2.0" publish = false diff --git a/Linux/crates/sw-studio/src/launch.rs b/Linux/crates/sw-studio/src/launch.rs index 1baeb357..106924f8 100644 --- a/Linux/crates/sw-studio/src/launch.rs +++ b/Linux/crates/sw-studio/src/launch.rs @@ -14,7 +14,7 @@ usage: scriptwidget-studio [options] [file.swt] --help print this text For development: - --page start on library, templates, settings, template: or editor: + --page start on library, templates, components, apis, settings, template: or editor: --no-single-instance always open a window of its own "; @@ -23,6 +23,8 @@ For development: pub enum StartPage { Library, Templates, + Components, + Apis, Settings, Template(String), Editor(String), @@ -75,6 +77,8 @@ pub fn parse(arguments: &[String], current: Option<&std::path::Path>) -> Result< launch.page = Some(match (page.as_str(), page.split_once(':')) { ("library", _) => StartPage::Library, ("templates", _) => StartPage::Templates, + ("components", _) => StartPage::Components, + ("apis", _) => StartPage::Apis, ("settings", _) => StartPage::Settings, (_, Some(("template", reference))) if !reference.is_empty() => StartPage::Template(reference.to_owned()), (_, Some(("editor", name))) if !name.is_empty() => StartPage::Editor(name.to_owned()), @@ -115,6 +119,8 @@ mod tests { assert_eq!((launch.data, launch.page, launch.single_instance), (Some("/tmp/data".into()), Some(StartPage::Template("template/Clock".into())), false)); assert_eq!(run(&["--page", "editor:Clock"]).unwrap().page, Some(StartPage::Editor("Clock".into()))); assert_eq!(run(&["--page", "settings"]).unwrap().page, Some(StartPage::Settings)); + assert_eq!(run(&["--page", "components"]).unwrap().page, Some(StartPage::Components)); + assert_eq!(run(&["--page", "apis"]).unwrap().page, Some(StartPage::Apis)); } #[test] diff --git a/Linux/crates/sw-studio/src/strings.rs b/Linux/crates/sw-studio/src/strings.rs index 5f70ed98..fabb3278 100644 --- a/Linux/crates/sw-studio/src/strings.rs +++ b/Linux/crates/sw-studio/src/strings.rs @@ -15,6 +15,8 @@ pub const TEXT: &[(&str, &str, &str)] = &[ ("app.title", "ScriptWidget", "ScriptWidget"), ("nav.library", "My widgets", "我的小组件"), ("nav.templates", "Templates", "模板"), + ("nav.components", "Components", "组件"), + ("nav.apis", "APIs", "API"), ("nav.settings", "Settings", "设置"), // ("library.title", "My widgets", "我的小组件"), @@ -41,9 +43,10 @@ pub const TEXT: &[(&str, &str, &str)] = &[ ("templates.title", "Templates", "模板"), ("templates.detail", "Ready-made widgets. Open one to see what it shows and how it is written, then make it yours.", "现成的小组件。点开可以看它的效果和代码,再变成你自己的。"), ("templates.none", "No templates are installed with this program.", "这个程序没有附带模板。"), - ("templates.group.template", "Widgets", "小组件"), - ("templates.group.component", "Component examples", "组件示例"), - ("templates.group.api", "API examples", "API 示例"), + ("components.title", "Components", "组件"), + ("components.detail", "What a widget is built from. Open one to see an example of it and how it is written.", "小组件由这些组件搭成。点开可以看它的示例和写法。"), + ("apis.title", "APIs", "API"), + ("apis.detail", "What a widget's code can call. Open one to see an example that uses it.", "小组件代码可以调用的接口。点开可以看用到它的示例。"), ("templates.network", "Uses the network", "会访问网络"), // ("detail.code", "Code", "代码"), @@ -296,7 +299,7 @@ mod tests { } assert!(used.len() > 40, "the scan found only {} keys", used.len()); // Keys that are built at run time or used by this module. - let indirect = |key: &str| key.starts_with("size.") || key.starts_with("bytes.") || key.starts_with("templates.group.") || ["settings.hour", "settings.hours", "settings.minutes"].contains(&key); + let indirect = |key: &str| key.starts_with("size.") || key.starts_with("bytes.") || ["settings.hour", "settings.hours", "settings.minutes"].contains(&key); let unused: Vec<&str> = TEXT.iter().map(|(key, _, _)| *key).filter(|key| !used.contains(*key) && !indirect(key)).collect(); assert!(unused.is_empty(), "texts nothing shows: {unused:?}"); } diff --git a/Linux/crates/sw-studio/src/ui/templates.rs b/Linux/crates/sw-studio/src/ui/templates.rs index 5d967ab0..4fb18153 100644 --- a/Linux/crates/sw-studio/src/ui/templates.rs +++ b/Linux/crates/sw-studio/src/ui/templates.rs @@ -1,5 +1,5 @@ -//! "Templates": the bundled templates in their groups, and one template -//! opened with its preview beside its code. +//! "Templates", "Components" and "APIs": one group of the bundled packages +//! each, and one of them opened with its preview beside its code. use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::input::{Editor, EditorState}; @@ -22,12 +22,18 @@ pub(super) struct TemplateSession { impl StudioWindow { pub(super) fn render_templates(&self, cx: &mut Context) -> impl IntoElement { let muted = cx.theme().muted_foreground; - let mut page = v_flex().p_6().gap_5().child(v_flex().gap_1().child(div().text_2xl().font_semibold().child(t("templates.title"))).child(div().text_color(muted).child(t("templates.detail")))); - if self.template_groups.is_empty() { + let (title, detail) = match self.group { + "component" => (t("components.title"), t("components.detail")), + "api" => (t("apis.title"), t("apis.detail")), + _ => (t("templates.title"), t("templates.detail")), + }; + let mut page = v_flex().p_6().gap_5().child(v_flex().gap_1().child(div().text_2xl().font_semibold().child(title)).child(div().text_color(muted).child(detail))); + let shown = || self.template_groups.iter().filter(|group| group.group == self.group); + if shown().all(|group| group.templates.is_empty()) { page = page.child(div().pt_8().text_color(muted).child(t("templates.none"))); } let mut index = 0; - for group in &self.template_groups { + for group in shown() { let cards: Vec<_> = group .templates .iter() @@ -36,7 +42,7 @@ impl StudioWindow { self.template_card(index, card, cx) }) .collect(); - page = page.child(v_flex().gap_3().child(div().text_lg().font_semibold().child(t(&format!("templates.group.{}", group.group)))).child(h_flex().flex_wrap().items_start().gap_4().children(cards))); + page = page.child(h_flex().flex_wrap().items_start().gap_4().children(cards)); } div().id("templates").size_full().overflow_y_scrollbar().child(page) } @@ -64,6 +70,12 @@ impl StudioWindow { } pub(super) fn open_template(&mut self, reference: &str, window: &mut Window, cx: &mut Context) { + // The list this one belongs to, so the sidebar and the back button agree with it. + self.group = match reference.split_once('/').map(|(group, _)| group) { + Some("component") => "component", + Some("api") => "api", + _ => "template", + }; let Some(detail) = self.studio.template(reference) else { self.page = Page::Templates; return; diff --git a/Linux/crates/sw-studio/src/ui/window.rs b/Linux/crates/sw-studio/src/ui/window.rs index f2cb1847..dcfdc8b3 100644 --- a/Linux/crates/sw-studio/src/ui/window.rs +++ b/Linux/crates/sw-studio/src/ui/window.rs @@ -44,6 +44,8 @@ pub(super) enum Page { pub(super) enum Target { Library, Templates, + Components, + Apis, Settings, Template(String), Editor(String), @@ -58,6 +60,8 @@ pub struct StudioWindow { pub(super) widgets: Vec, pub(super) library_error: Option, pub(super) template_groups: Vec, + /// Which list the Templates page shows: "template", "component" or "api". + pub(super) group: &'static str, /// Small pictures of widgets ("w/") and templates ("t/"). pub(super) thumbnails: HashMap, thumbnail_run: u64, @@ -115,6 +119,7 @@ impl StudioWindow { widgets: Vec::new(), library_error: None, template_groups: studio.template_groups(), + group: "template", thumbnails: HashMap::new(), thumbnail_run: 0, template: None, @@ -138,6 +143,8 @@ impl StudioWindow { match page { Some(StartPage::Library) | None => {} Some(StartPage::Templates) => this.go(Target::Templates, window, cx), + Some(StartPage::Components) => this.go(Target::Components, window, cx), + Some(StartPage::Apis) => this.go(Target::Apis, window, cx), Some(StartPage::Settings) => this.go(Target::Settings, window, cx), Some(StartPage::Template(reference)) => this.go(Target::Template(reference), window, cx), Some(StartPage::Editor(name)) => this.go(Target::Editor(name), window, cx), @@ -186,7 +193,12 @@ impl StudioWindow { self.page = Page::Library; self.reload_library(cx); } - Target::Templates => { + Target::Templates | Target::Components | Target::Apis => { + self.group = match target { + Target::Components => "component", + Target::Apis => "api", + _ => "template", + }; self.page = Page::Templates; self.make_thumbnails(cx); } @@ -241,7 +253,7 @@ impl StudioWindow { match self.page { Page::Templates => { // A template that asks the network is drawn only when it is opened. - for card in self.template_groups.iter().flat_map(|group| &group.templates).filter(|card| !card.network) { + for card in self.template_groups.iter().filter(|group| group.group == self.group).flat_map(|group| &group.templates).filter(|card| !card.network) { wanted.push((format!("t/{}", card.reference), request(PreviewSource::Bundled(card.reference.clone()), "medium"))); } } @@ -496,9 +508,12 @@ impl StudioWindow { Button::new(id).child(h_flex().w_full().gap_2().child(gpui_kit::component::Icon::new(icon)).child(label)).ghost().selected(selected).w_full().on_click(cx.listener(move |this, _, window, cx| this.navigate(target.clone(), window, cx))) }; let library = entry("nav-library", IconName::LayoutDashboard, t("nav.library"), matches!(self.page, Page::Library | Page::Editor), Target::Library, cx); - let templates = entry("nav-templates", IconName::GalleryVerticalEnd, t("nav.templates"), matches!(self.page, Page::Templates | Page::Template), Target::Templates, cx); + let listing = matches!(self.page, Page::Templates | Page::Template); + let templates = entry("nav-templates", IconName::GalleryVerticalEnd, t("nav.templates"), listing && self.group == "template", Target::Templates, cx); + let components = entry("nav-components", IconName::Frame, t("nav.components"), listing && self.group == "component", Target::Components, cx); + let apis = entry("nav-apis", IconName::SquareTerminal, t("nav.apis"), listing && self.group == "api", Target::Apis, cx); let settings = entry("nav-settings", IconName::Settings, t("nav.settings"), self.page == Page::Settings, Target::Settings, cx); - v_flex().w(px(208.)).h_full().flex_shrink_0().p_2().gap_1().bg(background).border_r_1().border_color(border).child(library).child(templates).child(div().flex_1()).child(settings) + v_flex().w(px(208.)).h_full().flex_shrink_0().p_2().gap_1().bg(background).border_r_1().border_color(border).child(library).child(templates).child(components).child(apis).child(div().flex_1()).child(settings) } } @@ -545,11 +560,20 @@ impl Render for StudioWindow { } impl StudioWindow { + /// The list of one group of bundled packages. + pub(super) fn list_of(group: &str) -> Target { + match group { + "component" => Target::Components, + "api" => Target::Apis, + _ => Target::Templates, + } + } + /// The page above the one shown: the list a template or a widget was opened from. pub(super) fn back(&mut self, window: &mut Window, cx: &mut Context) { match self.page { Page::Editor => self.navigate(Target::Library, window, cx), - Page::Template => self.navigate(Target::Templates, window, cx), + Page::Template => self.navigate(Self::list_of(self.group), window, cx), _ => {} } } diff --git a/Linux/omarchy-plugin/manifest.json b/Linux/omarchy-plugin/manifest.json index 1484b2c9..e62bf48d 100644 --- a/Linux/omarchy-plugin/manifest.json +++ b/Linux/omarchy-plugin/manifest.json @@ -2,7 +2,7 @@ "schemaVersion": 1, "id": "com.atomsprout.scriptwidget", "name": "ScriptWidget", - "version": "0.1.3", + "version": "0.1.4", "author": "AtomSprout", "description": "Shows the widgets ScriptWidget draws on the desktop layer and passes clicks back to it", "license": "Apache-2.0", diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock-shortcut.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock-shortcut.jsx index 7be44d9f..90c38f9b 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock-shortcut.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock-shortcut.jsx @@ -1,28 +1,30 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // another basic clock animation +// Three dots that go round like the hands of a clock. The animation prop turns a view: +// "clockHour" once in 12 hours, "clockMinute" once an hour, "clockSecond" once a minute. +// Try other sizes and colors. // - $render( - - - - - - - - - - - - - - - + {/* puts its children on top of each other, so all three turn around one center. */} + + {/* The pushes the dot to the top of its stack, away from the center. */} + + + + + + + + + + + + + + , ); - diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock.jsx index 5fb2ccc0..0344c0bf 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/clock.jsx @@ -3,22 +3,26 @@ // https://atomsprout.com/scriptwidget // // Animation Clock with more parameters +// $animation(...) turns a description object into a value for the animation prop. +// Try another interval or time zone. // - +// type "clock" keeps turning the view. anchor is the point it turns around. +// interval is in seconds: the view makes half a turn in that time, so here one full +// turn takes 60 seconds. let animationDefinition = { type: "clock", timezone: "current", // "America/New_York" , "America/Los_Angeles" , "Asia/Shanghai" anchor: "center", interval: 30, -} - +}; +// The animation is on the stack, so the four circles turn together. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/main.jsx index 6ca66e2a..7c11fe09 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/main.jsx @@ -1,28 +1,31 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // basic clock animation +// A clock with three hands. The animation prop turns a view like a clock hand: +// "clockSecond" once a minute, "clockMinute" once an hour, "clockHour" once in 12 hours. +// Try other lengths and colors for the hands. // - $render( - - - - - - - - - - - - - - - + {/* puts its children on top of each other, so the hands share one center. */} + + {/* A hand is a colored bar above a clear bar of the same size ("width,height" in points). */} + {/* The stack turns around its middle, which is the lower end of the colored bar. */} + + + + + + + + + + + + + + , ); - diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/swing.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/swing.jsx index 6f89dc72..5c5f2710 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/swing.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/animation/swing.jsx @@ -3,27 +3,38 @@ // https://atomsprout.com/scriptwidget // // Swing Sample +// type "swing" moves a view back and forth. $animation(...) turns the description +// object into a value for the animation prop. Try another duration or distance. // - +// distance: how far the view moves to each side of its place, in points. +// duration: seconds for one way and back to the middle; a full swing takes twice that. let animationHorizontalDefinition = { type: "swing", duration: 2, direction: "horizontal", // "horizontal", "vertical" distance: 100, -} +}; let animationVerticalDefinition = { type: "swing", duration: 2, direction: "vertical", // "horizontal", "vertical" distance: 100, -} - +}; +// Each circle has its own animation: one moves sideways, one up and down. $render( - - - + + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/calendar/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/calendar/main.jsx index fc0a1386..0d5ee46d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/calendar/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/calendar/main.jsx @@ -2,14 +2,27 @@ // In the main app, explicitly request access when the user selects Connect: // await $calendar.requestAuthorization(); // Widgets never present the authorization prompt. +// Runs on iPhone, iPad and Mac, and on Android for calendars selected in the app. +// Not on Windows or Linux: check isAvailable() first. +// This example shows the titles of up to five events. Try another limit. + +// The text to show when the calendar cannot be read. let message = "Allow Calendar access in ScriptWidget."; if ($calendar.isAvailable() && $calendar.authorizationStatus() === "authorized") { + // Reading can still fail, so there is a message for that case too. try { const calendars = await $calendar.calendars(); // up to 64 {id,title} entries const result = await $calendar.events({ limit: 5, maxAgeSeconds: 60 }); // Optional: calendarIDs: [calendars[0].id], start/end ISO-8601 timestamps. // Limit: 1–50 events, 31-day window, 1–16 selected calendar IDs. - message = result.items.map(event => event.title).join(" · ") || "No events today"; - } catch (error) { message = "Calendar unavailable. Check access in the app."; } + // Join the titles into one line; the text after || is used when there are none. + message = result.items.map((event) => event.title).join(" · ") || "No events today"; + } catch (error) { + message = "Calendar unavailable. Check access in the app."; + } } -$render({message}); +$render( + + {message} + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/console/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/console/main.jsx index ed85caf1..34ec0001 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/console/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/console/main.jsx @@ -1,12 +1,15 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api console -// +// console.log writes a line to the Console of the editor. +// Nothing is drawn here, so the widget itself only shows "#UI Not Found#". +// console.log("Hello ScriptWidget"); +// A long text is fine too. console.log( - "1. A grammatical unit that is syntactically independent and has a subject that is expressed or, as in imperative sentences, understood and a predicate that contains at least one finite verb. 2. The penalty imposed by a law court or other authority upon someone found guilty of a crime or other offense." + "1. A grammatical unit that is syntactically independent and has a subject that is expressed or, as in imperative sentences, understood and a predicate that contains at least one finite verb. 2. The penalty imposed by a law court or other authority upon someone found guilty of a crime or other offense.", ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/device/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/device/main.jsx index 921e3267..a99f1c89 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/device/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/device/main.jsx @@ -1,16 +1,22 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $device -// +// Prints what $device knows about this device to the Console. +// Nothing is drawn here, so the widget itself only shows "#UI Not Found#". +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. +// console.log($device.name()); console.log($device.model()); console.log($device.language()); console.log($device.systemVersion()); +// screen() and battery() return objects. JSON.stringify(value, null, 2) prints them +// with one field per line. console.log(JSON.stringify($device.screen(), null, 2)); console.log(JSON.stringify($device.battery(), null, 2)); +// true in dark appearance, false in light. console.log($device.isdarkmode()); console.log($device.totalDiskSpace()); console.log($device.freeDiskSpace()); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/fetch-header.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/fetch-header.jsx index e889473f..4bb61f99 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/fetch-header.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/fetch-header.jsx @@ -1,14 +1,19 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $fetch -// +// Loads JSON with a request header and shows one field of it. Try another URL. +// A Package 2.0 widget needs the "network" permission in widget.json, and the host +// of the URL in networkDomains. +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. +// // query json example with header // https://docs.github.com/en/rest/reference/projects const url = "https://api.github.com/users/everettjf/orgs"; +// fetch gives back the body of the response as text. headers are sent with the request. const result = await fetch(url, { headers: { Accept: "application/vnd.github.inertia-preview+json", @@ -16,10 +21,13 @@ const result = await fetch(url, { }); console.log(result); +// Turn the JSON text into a JavaScript value: here an array. const models = JSON.parse(result); +// models[2] is the third entry. With fewer than three entries, or without a network, +// the script fails here; a real widget should draw a fallback instead. $render( Org Description: {models[2].description} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/main.jsx index d2d7f2d0..0c88029c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/fetch/main.jsx @@ -1,21 +1,27 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $fetch -// +// Loads one JSON document and shows its title. Try another URL and another field. +// A Package 2.0 widget needs the "network" permission in widget.json, and the host +// of the URL in networkDomains. +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. +// // query json example // https://jsonplaceholder.typicode.com/ const url = "https://jsonplaceholder.typicode.com/todos/1"; +// fetch gives back the body of the response as text. const result = await fetch(url); console.log(result); +// Turn the JSON text into an object. const model = JSON.parse(result); $render( receive title: {model.title} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/file/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/file/main.jsx index e25348e7..b82c1d63 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/file/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/file/main.jsx @@ -3,6 +3,10 @@ // https://atomsprout.com/scriptwidget // // Usage for api file +// Reads data.json, a file inside this widget package. Paths start at the package folder. +// The results go to the Console. +// Nothing is drawn here, so the widget itself only shows "#UI Not Found#". +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. // // read as string diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/getenv/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/getenv/main.jsx index 5b85729a..de74ad8d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/getenv/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/getenv/main.jsx @@ -1,9 +1,11 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component $getenv -// +// $getenv(name) reads a value that the system hands to the script. +// Try: add the widget in each size, and type a parameter when you configure it. +// /* widget-size @@ -18,9 +20,10 @@ const widget_size = $getenv("widget-size"); */ const widget_param = $getenv("widget-param"); +// frame="max" makes the stack fill the whole widget. $render( Widget Size : {widget_size} Widget Parameter : {widget_param} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/angular.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/angular.jsx index 6c0761eb..602f3446 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/angular.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/angular.jsx @@ -1,18 +1,22 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $gradient -// +// $gradient(...) turns a description object into a value for the background prop. +// Try other colors, or more of them. +// +// An angular gradient sweeps through the colors around the center, like a color wheel. let angularGradient = { type: "angular", colors: ["green", "blue", "black", "green", "blue", "black", "green"], center: "center", }; +// frame="max" makes the stack, and with it the gradient, fill the whole widget. $render( AngularGradient - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/linear.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/linear.jsx index b6c7b0cd..6bc7d5cc 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/linear.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/linear.jsx @@ -1,10 +1,13 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $gradient -// +// $gradient(...) turns a description object into a value for the background prop. +// Try other colors, or more of them. +// +// A linear gradient runs in a straight line from startPoint to endPoint. let linearGradient = { type: "linear", colors: ["blue", "white", "pink"], @@ -12,8 +15,9 @@ let linearGradient = { endPoint: "bottomTrailing", }; +// frame="max" makes the stack, and with it the gradient, fill the whole widget. $render( LinearGradient - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/main.jsx index 6c0761eb..602f3446 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/main.jsx @@ -1,18 +1,22 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $gradient -// +// $gradient(...) turns a description object into a value for the background prop. +// Try other colors, or more of them. +// +// An angular gradient sweeps through the colors around the center, like a color wheel. let angularGradient = { type: "angular", colors: ["green", "blue", "black", "green", "blue", "black", "green"], center: "center", }; +// frame="max" makes the stack, and with it the gradient, fill the whole widget. $render( AngularGradient - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/radial.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/radial.jsx index 157a69fa..8bc01c26 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/radial.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/gradient/radial.jsx @@ -1,10 +1,13 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $gradient -// +// $gradient(...) turns a description object into a value for the background prop. +// Try other colors, or more of them. +// +// A radial gradient spreads out in circles from the center, between the two radii. let radialGradient = { type: "radial", colors: ["orange", "red", "white"], @@ -13,8 +16,9 @@ let radialGradient = { endRadius: 470, }; +// frame="max" makes the stack, and with it the gradient, fill the whole widget. $render( RadialGradient - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/health/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/health/main.jsx index 6fb583bb..25892aec 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/health/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/health/main.jsx @@ -5,37 +5,63 @@ // Usage for api health // Note: HealthKit requires main app permission and capability. // This API reads health data only (no write). +// Shows today's steps, today's active energy and the latest heart rate. +// Runs on iPhone and iPad, and on Android through Health Connect. +// Not on Mac, Windows or Linux: check isAvailable() first. +// A Package 2.0 widget must list "health" under permissions in widget.json. // +// Fallback for a system without health data. if (!$health.isAvailable()) { $render( - HealthKit Unavailable - This platform does not support HealthKit. - + + HealthKit Unavailable + + + This platform does not support HealthKit. + + , ); } else { + // Ask for read access. Do this while the script runs in the app. const granted = await $health.requestAuthorization(); + // Fallback when the request did not succeed. if (!granted) { $render( - Permission Needed - Enable Health access in the main app. - + + Permission Needed + + + Enable Health access in the main app. + + , ); } else { + // Each reading is an object. Its value is a number: a count of steps, kcal, and + // beats per minute. const steps = await $health.stepCountToday(); const energy = await $health.activeEnergyToday(); const heart = await $health.heartRateLatest(); + // toFixed(0) rounds the number and drops the decimals. $render( - Health Today - Steps: {steps.value.toFixed(0)} - Active Energy: {energy.value.toFixed(0)} kcal - Latest HR: {heart.value.toFixed(0)} bpm - + + Health Today + + + Steps: {steps.value.toFixed(0)} + + + Active Energy: {energy.value.toFixed(0)} kcal + + + Latest HR: {heart.value.toFixed(0)} bpm + + , ); } } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/http/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/http/main.jsx index c1732bef..5acfe531 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/http/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/http/main.jsx @@ -1,12 +1,16 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for api $http -// +// Calls $http.get and $http.post in several forms and prints each answer to the Console. +// A Package 2.0 widget needs the "network" permission in widget.json, and the host +// of the URL in networkDomains. +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. +// // $http.get -// $http.get is identity to $fetch or fetch api +// $http.get works like fetch and $fetch: it gives back the body of the response as text. const get_result = await $http.get("https://jsonplaceholder.typicode.com/todos/1"); console.log(get_result); @@ -19,18 +23,19 @@ const get_with_header_result = await $http.get("https://api.github.com/users/eve }); console.log(get_with_header_result); - // $http.post +// The body here is an object. const post_result = await $http.post("https://jsonplaceholder.typicode.com/posts", { body: { userId: 1, id: 1, title: "Hello ScriptWidget", - } + }, }); console.log(post_result); -const post_with_header_result = await $http.post("https://jsonplaceholder.typicode.com/posts", { +// A POST request with a header. +const post_with_header_result = await $http.post("https://jsonplaceholder.typicode.com/posts", { headers: { Accept: "application/vnd.github.inertia-preview+json", }, @@ -38,16 +43,20 @@ const post_with_header_result = await $http.post("https://jsonplaceholder.typico userId: 1, id: 1, title: "Hello ScriptWidget", - } + }, }); console.log(post_with_header_result); -const post_string_with_header_result = await $http.post("https://jsonplaceholder.typicode.com/posts", { - headers: { - Accept: "application/vnd.github.inertia-preview+json", +// The body can also be text, here form fields. +const post_string_with_header_result = await $http.post( + "https://jsonplaceholder.typicode.com/posts", + { + headers: { + Accept: "application/vnd.github.inertia-preview+json", + }, + body: "password=123&name=321", }, - body: "password=123&name=321" -}); +); console.log(post_string_with_header_result); // $http.put (same to post) @@ -68,8 +77,9 @@ console.log(post_string_with_header_result); // // ); +// Draw something, so the widget is not empty. The results are in the Console. $render( $http example - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/define.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/define.js index 646c1d36..e01c732a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/define.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/define.js @@ -1,5 +1,4 @@ - - +// Loaded by main.jsx. A function defined here can be called there. function sum(a, b) { return a + b; -} \ No newline at end of file +} diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/main.jsx index 94670647..36e695ed 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/main.jsx @@ -2,15 +2,19 @@ // https://atomsprout.com/scriptwidget // // import other js/jsx files +// $import(name) runs another file of this package in the same global scope, so this +// file can use what that file defines. Try adding a function to define.js. // +// util.jsx defines textItems; define.js defines sum(). $import("util.jsx"); $import("define.js"); $render( test + {/* An array of elements in braces is drawn as that many children. */} {textItems} {sum(1, 2)} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/util.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/util.jsx index 24fb1cc4..925c3d91 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/util.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/import/util.jsx @@ -1,5 +1,8 @@ +// Loaded by main.jsx. An imported file may contain JSX. textItems is used there. + const values = ["one", "two", "three", "four"]; +// One element per value. const textItems = values.map((value) => { return {value}; }); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/location/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/location/main.jsx index 587aa8f1..11e59746 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/location/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/location/main.jsx @@ -7,51 +7,74 @@ // This API reads current location only. // Options are optional; default accuracy is reduced. // Use maxAge/maxAgeMs for cached location to return faster. +// This example shows the position, its accuracy and its age. +// Runs on iPhone, iPad and Android. Not on Mac, Windows or Linux: check isAvailable() first. +// A Package 2.0 widget must list "location" under permissions in widget.json. // +// Fallback for a system without location. if (!$location.isAvailable()) { $render( - Location Unavailable - This device does not support location services. - + + Location Unavailable + + + This device does not support location services. + + , ); } else { + // Ask for access only when it was not given before. const status = $location.authorizationStatus(); let granted = status === "authorizedWhenInUse" || status === "authorizedAlways"; if (!granted) { + // timeout is in seconds. granted = await $location.requestAuthorization({ timeout: 10 }); } + // Fallback when access was refused or the request ran out of time. if (!granted) { $render( - Permission Needed - Enable Location access in the main app. - + + Permission Needed + + + Enable Location access in the main app. + + , ); } else { + // accuracy: "full" asks for the precise position. timeout is in seconds. const location = await $location.current({ timeout: 10, accuracy: "full", - purposeKey: "ScriptWidgetLocation" + purposeKey: "ScriptWidgetLocation", }); $render( - Current Location + + Current Location + + {/* Latitude and longitude, with five decimals. */} {location.latitude.toFixed(5)}, {location.longitude.toFixed(5)} + {/* accuracy is in metres; accuracyAuthorization is "full" or "reduced". */} Accuracy: {Math.round(location.accuracy)}m ({location.accuracyAuthorization}) + {/* age is in seconds. isStale marks a saved position that is old. */} Age: {location.age.toFixed(1)}s {location.isStale ? "(stale)" : ""} - Updated: {location.timestamp} - + + Updated: {location.timestamp} + + , ); } } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/scheme/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/scheme/main.jsx index df3b217a..4396c878 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/scheme/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/scheme/main.jsx @@ -2,6 +2,7 @@ // https://atomsprout.com/scriptwidget // // app schemes +// URLs that open the ScriptWidget app. Use one where a URL is accepted, such as . // /* diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/storage/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/storage/main.jsx index 051241ca..b57a289c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/storage/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/storage/main.jsx @@ -3,25 +3,41 @@ // https://atomsprout.com/scriptwidget // // Usage for api storage +// $storage keeps small values for this widget package between runs. +// A Package 2.0 widget must list "storage" under permissions in widget.json. +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. +// Try: store a number and add 1 to it on every run. // +// A text value. A key that was never set reads back as an empty string. $storage.setString("greeting", "Hello ScriptWidget"); const greeting = $storage.getString("greeting"); +// An object, stored as JSON. A missing key reads back as an empty object. $storage.setJSON("profile", { name: "Alex", city: "Shanghai", - updatedAt: new Date().toISOString() + updatedAt: new Date().toISOString(), }); const profile = $storage.getJSON("profile"); +// Every key this package has stored. const allKeys = $storage.keys(); +// frame="max" makes the stack fill the whole widget. $render( - Storage - {greeting} - Name: {profile.name} - Keys: {allKeys.join(", ")} - + + Storage + + + {greeting} + + + Name: {profile.name} + + + Keys: {allKeys.join(", ")} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/system/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/system/main.jsx index 08cd3599..f58ca327 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/system/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/system/main.jsx @@ -3,34 +3,70 @@ // https://atomsprout.com/scriptwidget // // Usage for api system +// Shows what $system reports about the app and the system. Try showing other values. +// Runs on iPhone, iPad, Mac, Android, Windows and Linux. // +// Read the values first. Some of them are objects with several fields. const app = $system.appInfo(); const tz = $system.timeZone(); const calendar = $system.calendarInfo(); const memory = $system.memory(); +// systemUptime() is in seconds; dividing by 3600 gives hours. const uptimeHours = ($system.systemUptime() / 3600).toFixed(1); const cpuCount = $system.processorCount(); const activeCpuCount = $system.activeProcessorCount(); +// frame="max" makes the stack fill the whole widget. $render( - System - {app.name} - Bundle: {app.bundleId} - Version: {app.version} ({app.build}) + + System + + + {app.name} + + + Bundle: {app.bundleId} + + + Version: {app.version} ({app.build}) + + {/* takes the free room between the app lines and the system lines. */} - Platform: {$system.platform()} - Locale: {$system.locale()} - Timezone: {tz.identifier} ({tz.abbreviation}) - Calendar: {calendar.identifier} - Uptime: {uptimeHours}h - OS: {$system.osVersionString()} - Host: {$system.hostName()} - CPU: {cpuCount} ({activeCpuCount} active) - Memory: {(memory.physical / 1024 / 1024 / 1024).toFixed(1)} GB - Low Power: {$system.lowPowerMode() ? "On" : "Off"} - + {/* platform() names the system the script runs on, for example "android". */} + + Platform: {$system.platform()} + + + Locale: {$system.locale()} + + + Timezone: {tz.identifier} ({tz.abbreviation}) + + + Calendar: {calendar.identifier} + + + Uptime: {uptimeHours}h + + + OS: {$system.osVersionString()} + + + Host: {$system.hostName()} + + + CPU: {cpuCount} ({activeCpuCount} active) + + {/* memory.physical is in bytes; dividing by 1024 three times gives GB. */} + + Memory: {(memory.physical / 1024 / 1024 / 1024).toFixed(1)} GB + + + Low Power: {$system.lowPowerMode() ? "On" : "Off"} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-es2020/main.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-es2020/main.js index 9d8a1ad5..9bd85eec 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-es2020/main.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-es2020/main.js @@ -1,16 +1,17 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // +// Newer JavaScript syntax works in a widget script. This example uses ?? and ?. and +// prints the results to the Console. // - - -const foo = null ?? 'default string'; +// a ?? b gives b only when a is null or undefined. +const foo = null ?? "default string"; console.log(foo); // expected output: "default string" +// 0 is a real value, so ?? keeps it. const baz = 0 ?? 42; console.log(baz); // expected output: 0 @@ -18,14 +19,16 @@ console.log(baz); const someArray = [0, 1, 2, 3]; console.log(someArray); +// Despite the name, nothing fails: reading past the end of an array gives undefined. const thisWillError = someArray[5]; console.log(thisWillError); +// ?.[5] gives undefined too, and would not fail even if someArray were null. const thisWillBeUndefined = someArray?.[5]; console.log(thisWillBeUndefined); $render( Hello ES2020 - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-map/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-map/main.jsx index 49276b73..f7be8ccb 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-map/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/api/usage-map/main.jsx @@ -1,19 +1,22 @@ -// ScriptWidget +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Mapping over an array // Thanks for Reina for telling me this good idea -// +// Builds one per array entry with map(). Try adding a value to the array. +// const values = ["one", "two", "three", "four"]; -const test = values.map((value) => { - return({value}) -}) +// map() returns an array with one element per value. +const test = values.map((value) => { + return {value}; +}); $render( test + {/* An array of elements in braces is drawn as that many children. */} {test} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/main.jsx index 3a106919..6f3ccf15 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/main.jsx @@ -1,9 +1,11 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component attribute frame -// +// frame sets the size of a view in points, as "width,height". "max" stands for all the +// room there is. Try the forms listed below on the two rectangles. +// /* @@ -29,9 +31,10 @@ "bottomLeading" "bottomTrailing" */ +// The stack fills the widget. Each rectangle is 50 points wide and 30 high. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-height.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-height.jsx index 566b7112..29bd932f 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-height.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-height.jsx @@ -1,13 +1,15 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component attribute frame -// +// frame="50,max": 50 points wide and as high as the stack lets it be. +// +// frame="max" makes the stack fill the whole widget. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-width.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-width.jsx index bf9936dc..9e1ed647 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-width.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/attribute-frame/max-width.jsx @@ -1,13 +1,15 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component attribute frame -// +// frame="max,30": as wide as the stack lets it be and 30 points high. +// +// frame="max" makes the stack fill the whole widget. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/badge/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/badge/main.jsx index 3adf2b4c..ede4bead 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/badge/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/badge/main.jsx @@ -3,11 +3,13 @@ // https://atomsprout.com/scriptwidget // // component: badge +// A badge is a short text on a colored background. Try other texts and colors. // +// frame="max" makes the stack fill the widget; spacing is the gap between its children. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/button/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/button/main.jsx index 803ca6d4..91d3eb3c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/button/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/button/main.jsx @@ -1,24 +1,29 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component button -// - +// Two buttons in a widget. Buttons need iOS 17 or macOS 14; on older systems they are +// shown but cannot be tapped. Try changing what onButtonClick does. +// +// Runs when the first button is tapped. onClick takes the name of this function as text. const onButtonClick = () => { console.log("button tapped"); }; +// The size of this widget, for example "small". It is shown as the label of the button. const widget_size = $getenv("widget-size"); $render( + {/* The children of a button are its label. */} + {/* action="reload" refreshes the widget. */} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/capsule/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/capsule/main.jsx index e2ae304a..0b7885d4 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/capsule/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/capsule/main.jsx @@ -1,12 +1,14 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component capsule -// +// A capsule is a rectangle with round ends. Try another frame ("width,height") or color. +// +// frame="max" makes the stack fill the whole widget. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/area.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/area.jsx index 5e6a4f9b..69753c3d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/area.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/area.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// An area chart: a line with the room below it filled. Try other values. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ { label: "jan/22", value: 5 }, { label: "feb/22", value: 4 }, @@ -13,16 +15,16 @@ let data = [ { label: "may/22", value: 14 }, { label: "jun/22", value: 27 }, { label: "jul/22", value: 27 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-category.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-category.jsx index 0d175472..b9c73cca 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-category.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-category.jsx @@ -1,30 +1,33 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A bar chart with colored groups. category={true} colors the bars by their category. +// +// Three labels with three entries each. Entries with the same label share one place +// on the x axis; category decides the color. let data = [ - { label: "Production", value: 4000, category: "Gizmos" }, - { label: "Production", value: 5000, category: "Gadgets" }, - { label: "Production", value: 6000, category: "Widgets" }, - { label: "Marketing", value: 2000, category: "Gizmos" }, - { label: "Marketing", value: 1000, category: "Gadgets" }, - { label: "Marketing", value: 5000.9, category: "Widgets" }, - { label: "Finance", value: 2000.5, category: "Gizmos" }, - { label: "Finance", value: 3000, category: "Gadgets" }, - { label: "Finance", value: 5000, category: "Widgets" }, -] + { label: "Production", value: 4000, category: "Gizmos" }, + { label: "Production", value: 5000, category: "Gadgets" }, + { label: "Production", value: 6000, category: "Widgets" }, + { label: "Marketing", value: 2000, category: "Gizmos" }, + { label: "Marketing", value: 1000, category: "Gadgets" }, + { label: "Marketing", value: 5000.9, category: "Widgets" }, + { label: "Finance", value: 2000.5, category: "Gizmos" }, + { label: "Finance", value: 3000, category: "Gadgets" }, + { label: "Finance", value: 5000, category: "Widgets" }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-gantt.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-gantt.jsx index 841b3836..2ec856ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-gantt.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-gantt.jsx @@ -1,27 +1,29 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A Gantt chart: a bar from start to end for every entry, in the row of its job. +// +// start and end are positions on the x axis. Entries with the same job share a row. let data = [ - { job: "Job 1", start: 0, end: 15}, - { job: "Job 2", start: 5, end: 25}, - { job: "Job 1", start: 20, end: 35}, - { job: "Job 1", start: 40, end: 55}, - { job: "Job 2", start: 30, end: 60}, - { job: "Job 2", start: 30, end: 60}, -] + { job: "Job 1", start: 0, end: 15 }, + { job: "Job 2", start: 5, end: 25 }, + { job: "Job 1", start: 20, end: 35 }, + { job: "Job 1", start: 40, end: 55 }, + { job: "Job 2", start: 30, end: 60 }, + { job: "Job 2", start: 30, end: 60 }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-x.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-x.jsx index 129d03af..ddb83bd5 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-x.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-x.jsx @@ -1,24 +1,26 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A single horizontal bar: the values are laid along the x axis; label is not used. +// +// Three values. category decides the color of each part. let data = [ - { label: "Production", value: 4000, category: "Gizmos" }, - { label: "Production", value: 5000, category: "Gadgets" }, - { label: "Production", value: 6000, category: "Widgets" }, -] + { label: "Production", value: 4000, category: "Gizmos" }, + { label: "Production", value: 5000, category: "Gadgets" }, + { label: "Production", value: 6000, category: "Widgets" }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-y.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-y.jsx index 3f179d24..05f77955 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-y.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar-y.jsx @@ -1,24 +1,26 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A single vertical bar: the values are laid along the y axis; label is not used. +// +// Three values. category decides the color of each part. let data = [ - { label: "Production", value: 4000, category: "Gizmos" }, - { label: "Production", value: 5000, category: "Gadgets" }, - { label: "Production", value: 6000, category: "Widgets" }, -] + { label: "Production", value: 4000, category: "Gizmos" }, + { label: "Production", value: 5000, category: "Gadgets" }, + { label: "Production", value: 6000, category: "Widgets" }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar.jsx index 729325de..0f187907 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/bar.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A bar chart: one bar per entry. Try other values, or another color. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ { label: "jan/22", value: 5 }, { label: "feb/22", value: 4 }, @@ -13,16 +15,16 @@ let data = [ { label: "may/22", value: 14 }, { label: "jun/22", value: 27 }, { label: "jul/22", value: 27 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/hide.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/hide.jsx index 229c1a90..dadc3d11 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/hide.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/hide.jsx @@ -1,32 +1,33 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// The bar chart again, with the legend and both axes hidden. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ - { label: "jan/22", value: 5 }, - { label: "feb/22", value: 4 }, - { label: "mar/22", value: 7 }, - { label: "apr/22", value: 15 }, - { label: "may/22", value: 14 }, - { label: "jun/22", value: 27 }, - { label: "jul/22", value: 27 }, -] + { label: "jan/22", value: 5 }, + { label: "feb/22", value: 4 }, + { label: "mar/22", value: 7 }, + { label: "apr/22", value: 15 }, + { label: "may/22", value: 14 }, + { label: "jun/22", value: 27 }, + { label: "jul/22", value: 27 }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - - - ); - + + + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-category.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-category.jsx index 630856a2..02e7e7d6 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-category.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-category.jsx @@ -1,30 +1,33 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// One line per category. category={true} colors the lines by their category. +// +// Three labels with three entries each. Entries with the same label share one place +// on the x axis; category decides the color. let data = [ - { label: "Production", value: 4000, category: "Gizmos" }, - { label: "Production", value: 5000, category: "Gadgets" }, - { label: "Production", value: 6000, category: "Widgets" }, - { label: "Marketing", value: 2000, category: "Gizmos" }, - { label: "Marketing", value: 1000, category: "Gadgets" }, - { label: "Marketing", value: 5000.9, category: "Widgets" }, - { label: "Finance", value: 2000.5, category: "Gizmos" }, - { label: "Finance", value: 3000, category: "Gadgets" }, - { label: "Finance", value: 5000, category: "Widgets" }, -] + { label: "Production", value: 4000, category: "Gizmos" }, + { label: "Production", value: 5000, category: "Gadgets" }, + { label: "Production", value: 6000, category: "Widgets" }, + { label: "Marketing", value: 2000, category: "Gizmos" }, + { label: "Marketing", value: 1000, category: "Gadgets" }, + { label: "Marketing", value: 5000.9, category: "Widgets" }, + { label: "Finance", value: 2000.5, category: "Gizmos" }, + { label: "Finance", value: 3000, category: "Gadgets" }, + { label: "Finance", value: 5000, category: "Widgets" }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-point.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-point.jsx index 4cb3861a..fe54d69e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-point.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line-point.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A line chart with a dot on every point. Try other values. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ { label: "jan/22", value: 5 }, { label: "feb/22", value: 4 }, @@ -13,16 +15,16 @@ let data = [ { label: "may/22", value: 14 }, { label: "jun/22", value: 27 }, { label: "jul/22", value: 27 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line.jsx index 2e37de45..6685262c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/line.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A line chart: the points joined by a line. Try other values. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ { label: "jan/22", value: 5 }, { label: "feb/22", value: 4 }, @@ -13,16 +15,16 @@ let data = [ { label: "may/22", value: 14 }, { label: "jun/22", value: 27 }, { label: "jul/22", value: 27 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/main.jsx index d83421fd..b9109431 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/main.jsx @@ -1,32 +1,33 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A bar chart. Try the three hide lines below: remove the // in front of one. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ - { label: "jan/22", value: 5 }, - { label: "feb/22", value: 4 }, - { label: "mar/22", value: 7 }, - { label: "apr/22", value: 15 }, - { label: "may/22", value: 14 }, - { label: "jun/22", value: 27 }, - { label: "jul/22", value: 27 }, -] + { label: "jan/22", value: 5 }, + { label: "feb/22", value: 4 }, + { label: "mar/22", value: 7 }, + { label: "apr/22", value: 15 }, + { label: "may/22", value: 14 }, + { label: "jun/22", value: 27 }, + { label: "jul/22", value: 27 }, +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - - - ); - + + + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/point.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/point.jsx index 9baa9682..1cc259e4 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/point.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/point.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A point chart: one dot per entry, no line. Try other values. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ { label: "jan/22", value: 5 }, { label: "feb/22", value: 4 }, @@ -13,16 +15,16 @@ let data = [ { label: "may/22", value: 14 }, { label: "jun/22", value: 27 }, { label: "jul/22", value: 27 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rect.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rect.jsx index 5298df5a..b5866065 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rect.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rect.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// A chart that marks every entry with a rectangle. Try other values. +// +// One entry per point: label goes on the x axis, value on the y axis. let data = [ { label: "jan/22", value: 5 }, { label: "feb/22", value: 4 }, @@ -13,16 +15,16 @@ let data = [ { label: "may/22", value: 14 }, { label: "jun/22", value: 27 }, { label: "jul/22", value: 27 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rule-x.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rule-x.jsx index f826df04..4f3a8a0d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rule-x.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chart/rule-x.jsx @@ -1,24 +1,26 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component chart -// +// Horizontal lines: each entry runs from xstart to xend at the height y. +// +// One entry per line. let data = [ { xstart: 1, xend: 12, y: 2.5 }, { xstart: 9, xend: 16, y: 1.5 }, { xstart: 3, xend: 10, y: 0.5 }, -] +]; +// $json(data) is short for JSON.stringify(data): the chart takes its data as JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chip/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chip/main.jsx index d697c5f4..76c2bbe0 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chip/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/chip/main.jsx @@ -3,11 +3,13 @@ // https://atomsprout.com/scriptwidget // // component: chip +// A chip is a small rounded label. Try other texts and colors. // +// frame="max" makes the stack fill the widget; spacing is the gap between its children. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/circle/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/circle/main.jsx index 9d313581..7acb39bd 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/circle/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/circle/main.jsx @@ -1,15 +1,19 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component circle -// +// Four circles: filled, as a ring, as a part of a ring, and that part turned. +// $render( + {/* stroke draws only the outline, with this line width. */} + {/* trim leaves out the start of the outline: 0.2 is the first 20%. */} + {/* rotation turns the view, in degrees. */} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/custom-component/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/custom-component/main.jsx index 58a10a76..be8928dd 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/custom-component/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/custom-component/main.jsx @@ -1,60 +1,57 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // Custom Component // Thanks for Reina for telling me this good idea -// - +// // Custom component is a JavaScript function // with one parameter composed with : prop1,prop2... and children -// As a convention, +// As a convention, // the first letter of custom component's name must be uppercase. // For example : LeftAlign , MyCustomComponent ... etc... - // prototype: // 1. new style // const MyComponent = ({prop1, prop2, children}) => { /* ... */ } -// +// // 2. old style -// const MyComponent = (props) => { +// const MyComponent = (props) => { // let prop1 = props.prop1; // let prop2 = props.prop2; // let children = props.children; // } +// Puts its children at the left: the takes the rest of the row. const LeftAlign = ({ message, children }) => { - return ( - - {children} - ({message}) - - - ) -} + return ( + + {children} + ({message}) + + + ); +}; +// The same with the spacer first, so the children end up at the right. const RightAlign = ({ message, children }) => { - return ( - - - ({message}) - {children} - - ) -} + return ( + + + ({message}) + {children} + + ); +}; +// A component is used like a tag. Its attributes and its children arrive in the +// parameter of the function. Try writing a component of your own. $render( - - - this text left aligned - - - text right aligned - - + + + this text left aligned + + + text right aligned + + , ); - diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/main.jsx index 4a3ea632..fcfcbdce 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/main.jsx @@ -1,15 +1,20 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component date -// +// shows a date, or a running time that the system keeps up to date by itself. +// Try style="relative" or style="offset", or date="tomorrow". +// $render( + {/* style="time" shows the time of day; style="date" shows the calendar date. */} + {/* style="timer" counts the time since the date: here since midnight. */} + {/* date also takes a time in milliseconds, which is what Date.now() returns. */} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/width.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/width.jsx index 409c0a52..465ae33b 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/width.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/date/width.jsx @@ -1,16 +1,19 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component date // try to fix the expanding issue , we can add a frame attribute : frame="50,max,leading" +// Left alone, a takes all the width it can get. A fixed width keeps it by the label. // $render( + {/* font="10" is a size in points; "#aaaaaa,0.5" is a color with 50% opacity. */} Last update: + {/* frame="50,max,leading": 50 points wide, full height, content at the leading edge. */} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/divider/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/divider/main.jsx index f694de64..29e90e54 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/divider/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/divider/main.jsx @@ -3,12 +3,14 @@ // https://atomsprout.com/scriptwidget // // component: divider +// A divider is a thin line between two parts. Try another thickness or color. // +// frame="max" makes the stack fill the widget; padding keeps the content off its edges. $render( Section A Section B - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ellipse/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ellipse/main.jsx index ec939fd8..b533d2fe 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ellipse/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ellipse/main.jsx @@ -1,12 +1,14 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component ellipse -// +// An ellipse fills its frame ("width,height" in points). Try a square frame. +// +// frame="max" makes the stack fill the whole widget. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/fragment/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/fragment/main.jsx index 88073bd8..8d0d6f3e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/fragment/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/fragment/main.jsx @@ -2,18 +2,21 @@ // ScriptWidget // https://atomsprout.com/scriptwidget // +// A fragment, written <>..., groups elements without adding a view of its own. // +// Two texts kept in one variable. var aaa = ( - <> - a text - a text - -) + <> + a text + a text + +); $render( - - {aaa} - a text - + + {/* The two texts become children of this stack, next to the third one. */} + {aaa} + a text + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/current.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/current.jsx index 96165c86..b1af67ab 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/current.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/current.jsx @@ -1,19 +1,20 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// current is the label for the current value. A circular gauge shows it and not text. +// +// frame="max" makes the stack fill the whole widget. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/main.jsx index 3525dc54..caf2ac3e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/main.jsx @@ -1,18 +1,20 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// A system gauge (type="system"). value is how full it is, from 0 to 1. +// Try style="linear". +// +// frame="max" makes the stack fill the whole widget. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/min-max.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/min-max.jsx index 6d81d8d7..9e640e42 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/min-max.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/min-max.jsx @@ -1,13 +1,16 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// min and max are the labels at the two ends of the gauge. They are text only: how +// full the gauge is still comes from value, from 0 to 1. +// +// frame="max" makes the stack fill the whole widget. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-automatic.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-automatic.jsx index 5f9f5229..935dbfb7 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-automatic.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-automatic.jsx @@ -1,18 +1,14 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// style="automatic" lets the system choose the look of the gauge. +// +// frame="max" makes the stack fill the whole widget. $render( - - - + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-circular.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-circular.jsx index 3525dc54..22e11a90 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-circular.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-circular.jsx @@ -1,18 +1,19 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// style="circular" draws the gauge as a ring. It is the default. +// +// frame="max" makes the stack fill the whole widget. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-linear.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-linear.jsx index dc75e1be..c38dcb33 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-linear.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/style-linear.jsx @@ -1,18 +1,14 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// style="linear" draws the gauge as a bar. +// +// frame="max" makes the stack fill the whole widget. $render( - - - + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/text-only.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/text-only.jsx index 3525dc54..0ed790e3 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/text-only.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/text-only.jsx @@ -1,18 +1,19 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// A gauge with only text set: no current, min or max. value is from 0 to 1. +// +// frame="max" makes the stack fill the whole widget. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/z-the-old.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/z-the-old.jsx index cf466a43..a5e2957d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/z-the-old.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gauge/z-the-old.jsx @@ -1,29 +1,36 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component guage -// +// +// Usage for component gauge +// The older gauge, drawn by ScriptWidget itself: a dial with a needle and colored +// sections. Leave type out, or set type="original", to get it. +// +// The colored parts of the dial, in order. The four values add up to 1. let gaugeSections = [ - {color: "yellow", value: 0.1}, - {color: "blue", value: 0.2}, - {color: "orange", value: 0.3}, - {color: "green", value: 0.4}, + { color: "yellow", value: 0.1 }, + { color: "blue", value: 0.2 }, + { color: "orange", value: 0.3 }, + { color: "green", value: 0.4 }, ]; +// $json(gaugeSections) is short for JSON.stringify: the prop takes JSON text. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gif/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gif/main.jsx index 732b943c..319da5a9 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gif/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/gif/main.jsx @@ -2,15 +2,15 @@ // ScriptWidget // https://atomsprout.com/scriptwidget // -// Shape Template +// Usage for component gif // -// Description: Shape Example +// Description: shows image/test.gif from this package. +// file is the name of a GIF in the image folder of the package; ".gif" may be left out. +// On Mac the GIF does not move: its first picture is shown. // - - $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hgrid/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hgrid/main.jsx index 5920bbd8..0c3d19d8 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hgrid/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hgrid/main.jsx @@ -1,10 +1,11 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // grid component -// +// fills column after column. Its "columns" prop describes the rows. +// Try the other descriptions below, or more circles. +// /* iOS @@ -33,22 +34,22 @@ macOS // { type: "fixed", value: "30"}, // ] -let columns = [ - { type: "adaptive", min: "70", max: "100"}, -] +// One adaptive entry: as many rows as fit, each from 70 to 100 points. +let columns = [{ type: "adaptive", min: "70", max: "100" }]; +// $json(columns) is short for JSON.stringify(columns): the prop takes JSON text. $render( - - - - - - - - - + + + + + + + + + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hstack/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hstack/main.jsx index 93d2d16d..1906a2ce 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hstack/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/hstack/main.jsx @@ -3,11 +3,12 @@ // https://atomsprout.com/scriptwidget // // Usage for component hstack +// puts its children next to each other. Try spacing="12", or more children. // $render( First Second - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/icon/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/icon/main.jsx index 0c7647aa..202bdc31 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/icon/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/icon/main.jsx @@ -3,11 +3,13 @@ // https://atomsprout.com/scriptwidget // // component: icon +// An icon is an SF Symbol, chosen with systemName, with a size and a color. // +// frame="max" makes the stack fill the widget; spacing is the gap between its children. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/base64.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/base64.jsx index 86825d3b..dfcbd4e3 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/base64.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/base64.jsx @@ -3,6 +3,7 @@ // https://atomsprout.com/scriptwidget // // Usage for component image +// An image can be written into the script itself as a data URL. url and src are the same prop. // /* @@ -11,6 +12,7 @@ data:image/png;base64, data:image/jpeg;base64, */ +// frame="50,50" shows each image 50 by 50 points. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/main.jsx index 86b6fe16..c06b664c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/main.jsx @@ -1,9 +1,10 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component image -// +// An image from the web (url) and one from the package (id). Try the forms listed below. +// /* @@ -26,7 +27,9 @@ $render( - - - + {/* url loads the image from the web. */} + + {/* id names a file in the image folder of the package; the extension may be left out. */} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/system-image-size.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/system-image-size.jsx index 0ce71989..2dccd1ca 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/system-image-size.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/image/system-image-size.jsx @@ -7,6 +7,7 @@ // Description: image with systemName is special. // Attribute frame does not work with image with systemName. // But it's sizes can be set by attribute font with a number size. +// Try other symbol names from Apple's SF Symbols, and other sizes. // $render( @@ -15,5 +16,5 @@ $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/label/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/label/main.jsx index 0df2213c..2f4daf18 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/label/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/label/main.jsx @@ -3,11 +3,13 @@ // https://atomsprout.com/scriptwidget // // component: label +// A label is an icon and a title side by side. systemName is the name of an SF Symbol. // +// frame="max" makes the stack fill the widget; spacing is the gap between its children. $render( + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/line/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/line/main.jsx index b794d976..419ab69f 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/line/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/line/main.jsx @@ -3,8 +3,10 @@ // https://atomsprout.com/scriptwidget // // component: line +// A line with a length and a thickness. axis="vertical" makes it stand upright. // +// frame="max" makes the stack fill the widget; spacing is the gap between its children. $render( @@ -12,5 +14,5 @@ $render( Vertical line - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/link/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/link/main.jsx index 4c651dcc..691396c8 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/link/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/link/main.jsx @@ -1,12 +1,15 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component link -// +// Tapping a link opens its url. Try your own URLs. +// linkurl on a view, here the outer stack, is the URL for a tap on that view. +// $render( + {/* The children of a link are what the user sees and taps. */} Hello Baidu @@ -22,6 +25,5 @@ $render( Bing - + , ); - diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/live-activity/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/live-activity/main.jsx index 0747525f..0e9bfac9 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/live-activity/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/live-activity/main.jsx @@ -1,29 +1,33 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component Live Activity and Dynamic Island -// - +// Live Activities run on iPhone and iPad. Android shows a Live Update notification and +// does not draw this layout. Mac, Windows and Linux have no Live Activities. +// Start one in the app under Settings > Live Activities. +// // $render is also for lock screen live activity $render( - - hello live activity - + + hello live activity + , ); - // $dynamic_island is for dynamic island // on iPhone 14 Pro/ProMax and iOS16.1+ $dynamic_island({ - expanded: { // expanded is required , at least one of the four child below is required - leading: leading, - trailing: trailing, - center: center, - bottom: bottom, - }, - compactLeading: compactLeading, // required - compactTrailing: compactTrailing, // required - minimal: minimal, // required + expanded: { + // expanded is required , at least one of the four child below is required + leading: leading, + trailing: trailing, + center: center, + bottom: bottom, + }, + // The island in its small form has a left and a right side. + compactLeading: compactLeading, // required + compactTrailing: compactTrailing, // required + // The smallest form, used when several activities share the island. + minimal: minimal, // required }); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/progress/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/progress/main.jsx index 9e4717b6..428493b9 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/progress/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/progress/main.jsx @@ -3,12 +3,15 @@ // https://atomsprout.com/scriptwidget // // component: progress +// A progress bar and a round one. value is how far it is; total is the value that +// means finished. Try other values. // $render( Loading + {/* style="circular" draws a ring; frame="32" makes it 32 by 32 points. */} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/rect/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/rect/main.jsx index c1b203fa..061e07a4 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/rect/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/rect/main.jsx @@ -1,13 +1,15 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component rect -// +// A rectangle with a frame ("width,height" in points) and a color. corner rounds it. +// +// frame="max" makes the stack fill the whole widget. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ring/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ring/main.jsx index 3d441ffb..3295d96a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ring/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/ring/main.jsx @@ -3,10 +3,12 @@ // https://atomsprout.com/scriptwidget // // component: ring +// A ring filled up to value, from 0 to 1. trackColor is the color of the unfilled part. +// frame="72" makes it 72 by 72 points. Try another value or thickness. // $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/roundedrect/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/roundedrect/main.jsx index 7e3dff55..3d3ba042 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/roundedrect/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/roundedrect/main.jsx @@ -3,10 +3,11 @@ // https://atomsprout.com/scriptwidget // // component: roundedrect +// A rectangle with rounded corners. radius is the corner radius. Try a larger one. // $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/stat/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/stat/main.jsx index 096b2978..5f776c43 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/stat/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/stat/main.jsx @@ -3,11 +3,13 @@ // https://atomsprout.com/scriptwidget // // component: stat +// A stat shows a title, a value and a subtitle. color is the color of the value. // +// frame="max" makes the stack fill the widget; spacing is the gap between its children. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/text/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/text/main.jsx index cf493e36..9e2e8166 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/text/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/text/main.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component text -// +// Text with a font, a color and a background. Try other fonts, such as "headline". +// +// frame="max" makes the stack fill the whole widget. $render( Hello ScriptWidget @@ -14,5 +16,5 @@ $render( Hello ScriptWidget - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/toggle/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/toggle/main.jsx index c079c766..e8726bb2 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/toggle/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/toggle/main.jsx @@ -1,23 +1,28 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Usage for component capsule -// - +// +// Usage for component toggle +// A switch in a widget. Toggles need iOS 17 or macOS 14; on older systems they are +// shown but cannot be tapped. +// +// Runs when the toggle is tapped. onClick takes the name of this function as text. const onToggleClick = () => { console.log("toggle tapped"); -} +}; const widget_size = $getenv("widget-size"); +// A random on/off state, only for this demo: it changes with every redraw. +// A real widget would keep the state, for example in $storage. const value = Math.random() >= 0.5; $render( + {/* on is the state shown; the children are the label. */} {widget_size} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vgrid/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vgrid/main.jsx index 96978265..30f0079c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vgrid/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vgrid/main.jsx @@ -1,10 +1,11 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // grid component -// +// fills row after row. columns describes its columns. +// Try the other descriptions below, or more circles. +// /* iOS @@ -33,22 +34,22 @@ macOS // { type: "fixed", value: "30"}, // ] -let columns = [ - { type: "adaptive", min: "70", max: "100"}, -] +// One adaptive entry: as many columns as fit, each from 70 to 100 points. +let columns = [{ type: "adaptive", min: "70", max: "100" }]; +// $json(columns) is short for JSON.stringify(columns): the prop takes JSON text. $render( - - - - - - - - - + + + + + + + + + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vstack/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vstack/main.jsx index d96f6346..33187f8d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vstack/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/vstack/main.jsx @@ -3,11 +3,12 @@ // https://atomsprout.com/scriptwidget // // Usage for component vstack +// puts its children below each other. Try spacing="12", or more children. // $render( First Second - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/zstack/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/zstack/main.jsx index 9e47a9b4..0c487917 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/zstack/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/component/zstack/main.jsx @@ -2,12 +2,13 @@ // ScriptWidget // https://atomsprout.com/scriptwidget // -// Usage for component vstack +// Usage for component zstack +// puts its children on top of each other, so the two texts overlap here. // $render( First Second - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Activity Rings/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Activity Rings/main.jsx index 5ae2accf..acfb355d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Activity Rings/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Activity Rings/main.jsx @@ -1,6 +1,13 @@ // Activity Rings · an offline design example with editable sample values. // These values are illustrative, not live Apple Health readings. +// Shows three progress rings, with a layout for every widget size. +// Try changing the numbers in `goals` and `week` below. +// +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", "extraLargePortrait", or one of the Lock Screen sizes +// "accessoryCircular", "accessoryRectangular" and "accessoryInline". const size = $getenv("widget-size"); +// true in dark mode. Every color below has a dark and a light value. const dark = $device.isdarkmode(); const palette = { background: dark ? "#172522" : "#F5FAF7", @@ -8,67 +15,222 @@ const palette = { secondary: dark ? "#B0C5BA" : "#5C7568", track: dark ? "#2B4138" : "#E0EBE4", }; +// Sample data. `value` is today's amount and `goal` the target, both in `unit`. const goals = [ { name: "Move", value: 420, goal: 500, unit: "cal", color: dark ? "#F2AC83" : "#AC582D" }, { name: "Exercise", value: 24, goal: 30, unit: "min", color: dark ? "#74C8A2" : "#287A59" }, { name: "Stand", value: 9, goal: 12, unit: "hr", color: dark ? "#8BBBE0" : "#3D739E" }, ]; -const week = [["M", 510], ["T", 380], ["W", 620], ["T", 450], ["F", 290], ["S", 540], ["S", 420]]; +// Move calories for each day of the week, Monday first. +const week = [ + ["M", 510], + ["T", 380], + ["W", 620], + ["T", 450], + ["F", 290], + ["S", 540], + ["S", 420], +]; +// Small components used by the layouts below. A component is a function that returns JSX. +// frame="max,14" means: as wide as possible and 14 points high. const Header = () => ( - Activity + + Activity + - Sample + + Sample + ); +// Three rings, one inside the other. draws its children on top of each other. const Rings = ({ side, thickness }) => ( {goals.map((goal, index) => { + // Each ring is smaller than the one before by its thickness plus a 3-point gap. const inset = index * (thickness + 3); - return ; + // `value` is the filled share of the ring, from 0 to 1; Math.min stops it at a full ring. + return ( + + ); })} ); +// One line of the list: a colored dot, the name, the value and the unit. const Stat = ({ goal }) => ( - {goal.name} + + {goal.name} + - {goal.value} - {goal.unit} + + {goal.value} + + + {goal.unit} + ); +// The three values side by side, each above its name. const Summary = () => ( - {goals.map((goal) => - {goal.value}{goal.unit} - {goal.name} - )} + {goals.map((goal) => ( + + + + {goal.value} + + + {goal.unit} + + + + {goal.name} + + + ))} ); +// A bar chart of the week, with the day letters under it. const Week = () => ( - MOVE THIS WEEK500 cal goal + + + MOVE THIS WEEK + + + + 500 cal goal + + - {week.map(([, calories]) => = goals[0].goal ? goals[0].color : palette.track} />).flatMap((bar, index) => index ? [, bar] : [bar])} + {/* Bar height in points: the busiest day (620 cal) is 42 high. */} + {/* Days that reach the Move goal get its color. flatMap puts a between bars. */} + {week + .map(([, calories]) => ( + = goals[0].goal ? goals[0].color : palette.track} + /> + )) + .flatMap((bar, index) => (index ? [, bar] : [bar]))} - {week.map(([day]) => {day}).flatMap((label, index) => index ? [, label] : [label])} + {week + .map(([day]) => ( + + {day} + + )) + .flatMap((label, index) => (index ? [, label] : [label]))} ); +// Choose a layout for the widget size. $render draws the JSX it is given. +// The three "accessory" sizes are Lock Screen widgets (iPhone and iPad only). The system +// tints them, so they set no background and no colors. if (size === "accessoryCircular") { - $render({Math.round(100 * goals[0].value / goals[0].goal)}%); + // Lock Screen circle: the Move ring with its percentage. + $render( + + + + {Math.round((100 * goals[0].value) / goals[0].goal)}% + + , + ); } else if (size === "accessoryRectangular") { - $render({goals.map((goal) => {goal.value}/{goal.goal} {goal.unit})}); + // Lock Screen rectangle: small rings beside the three values. + $render( + + + + {goals.map((goal) => ( + + {goal.value}/{goal.goal} {goal.unit} + + ))} + + , + ); } else if (size === "accessoryInline") { - $render(Move {goals[0].value}/{goals[0].goal} · Exercise {goals[1].value} min); + // Lock Screen line: text only. + $render( + + Move {goals[0].value}/{goals[0].goal} · Exercise {goals[1].value} min + , + ); } else if (size === "small") { - $render(
{goals.map((goal) => {goal.value}{goal.unit})}); + // Small widget: the rings with the three numbers under them. + // frame="max" fills the whole widget. padding keeps the content away from the edges and + // spacing is the gap between children, both in points. + $render( + +
+ + + {goals.map((goal) => ( + + + {goal.value} + + + {goal.unit} + + + ))} + + , + ); } else if (size === "medium") { - $render(
{goals.map((goal) => )}); + // Medium widget: the rings on the left, the list on the right. + $render( + +
+ + + + {goals.map((goal) => ( + + ))} + + + , + ); } else if (size === "extraLarge") { - $render(
{goals.map((goal) => )}); + // Extra-large widget: rings, list and the week chart in one row. + $render( + +
+ + + + {goals.map((goal) => ( + + ))} + + + + , + ); } else { - $render(
); + // Large widget, and any other size: everything stacked from top to bottom. + $render( + +
+ + + + + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Air Quality Now/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Air Quality Now/main.jsx index 3de19a0b..36d1317d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Air Quality Now/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Air Quality Now/main.jsx @@ -5,11 +5,17 @@ // Air Quality Now - Open-Meteo (no API key) // widget-param: "lat,lon" (optional) // +// Shows live air quality numbers for one place, read from a web API. +// Try changing the default coordinates below, or set them for each widget with the parameter. +// +// The default place: San Francisco, as latitude and longitude in degrees. let lat = 37.7749; let lon = -122.4194; +// $getenv("widget-param") is the parameter set for this widget (an empty string if none). const param = $getenv("widget-param"); if (param) { + // Use the parameter only if it holds two valid numbers; otherwise keep the default. const parts = param.split(",").map((p) => p.trim()); if (parts.length >= 2) { const latValue = parseFloat(parts[0]); @@ -21,24 +27,43 @@ if (param) { } } +// Read the data from Open-Meteo. +// Here fetch returns the response body as text, so it is parsed with JSON.parse. +// This template has no widget.json. In a package that has one, fetch only works when +// widget.json declares the "network" permission and lists this host in "networkDomains". const url = `https://air-quality-api.open-meteo.com/v1/air-quality?latitude=${lat}&longitude=${lon}¤t=pm2_5,pm10,us_aqi&timezone=auto`; const result = await fetch(url); const data = JSON.parse(result); +// `current` can be missing from an answer; {} keeps the lines below from failing. const current = data.current || {}; +// frame="max" makes the stack fill the whole widget. +// `??` shows "-" when a value is missing. $render( - Air Quality - AQI {current.us_aqi ?? "-"} + + Air Quality + + + AQI {current.us_aqi ?? "-"} + - PM2.5 - {current.pm2_5 ?? "-"} + + PM2.5 + + + {current.pm2_5 ?? "-"} + - PM10 - {current.pm10 ?? "-"} + + PM10 + + + {current.pm10 ?? "-"} + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/An Empty Widget/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/An Empty Widget/main.jsx index 0c385bb1..4352d471 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/An Empty Widget/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/An Empty Widget/main.jsx @@ -1,19 +1,37 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Empty Template -// +// // Description: Empty script for starter -// +// +// The smallest useful starting point: one $render call with an icon and two texts. +// Try changing the texts, the icon name and the background color. +// +// The size being drawn: "small", "medium", "large", … It is shown in the badge. const size = $getenv("widget-size"); +// $render draws the JSX it is given. stacks its children from top to bottom and +// from left to right. frame="max" fills the whole widget; padding (the distance +// to the edges) and spacing (the gap between children) are in points. $render( - + + {/* systemName is the name of a system icon (an SF Symbol). */} + + + + + {/* frame="max,bottomLeading" takes the remaining space and puts the text bottom left. */} - Your next idea - Start editing this template to make it yours. + {/* The small widget gets a smaller title font. */} + + Your next idea + + + Start editing this template to make it yours. + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Aquarium/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Aquarium/main.jsx index f5a637e3..2c8eb676 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Aquarium/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Aquarium/main.jsx @@ -1,37 +1,80 @@ // ScriptWidget · https://atomsprout.com/scriptwidget // Aquarium: one creature per bounded cell, with family-specific compositions. // WidgetKit may freeze motion. The scene remains complete at its resting pose. +// Shows how to move elements with $animation and how to build rows from lists of emoji. +// Try changing the emoji in the rows at the bottom, or the `distance` of a motion. +// +// The size being drawn. `compact` and `roomy` choose smaller or larger cells and rows. const family = $getenv("widget-size"); const compact = family === "small"; const roomy = ["large", "extraLarge", "extraLargePortrait"].includes(family); +// The side of one creature's cell, and its font size, in points. const cell = roomy ? 36 : 28; const font = roomy ? "26" : "20"; -const fishHorizontal = $animation({ type: "swing", duration: 20, direction: "horizontal", distance: compact ? 6 : 10 }); -const fishVertical = $animation({ type: "swing", duration: 30, direction: "vertical", distance: 5 }); -const bubbleVertical = $animation({ type: "swing", duration: 15, direction: "vertical", distance: 6 }); +// $animation describes a motion to give to an element's `animation` property. A "swing" +// slides the element back and forth by up to `distance` points; a full cycle takes twice +// `duration` (in seconds). +const fishHorizontal = $animation({ + type: "swing", + duration: 20, + direction: "horizontal", + distance: compact ? 6 : 10, +}); +const fishVertical = $animation({ + type: "swing", + duration: 30, + direction: "vertical", + distance: 5, +}); +const bubbleVertical = $animation({ + type: "swing", + duration: 15, + direction: "vertical", + distance: 6, +}); +// $gradient builds a color gradient that can be used as a background. const water = $gradient({ type: "linear", colors: ["#013A63", "#1E81B0", "#E0FBFC"], startPoint: "top", endPoint: "bottom", }); -const motion = symbol => symbol === "🐡" ? fishHorizontal : symbol === "🐠" ? fishVertical : symbol === "🫧" ? bubbleVertical : undefined; +// Which motion each emoji gets. All others stay still. +const motion = (symbol) => + symbol === "🐡" + ? fishHorizontal + : symbol === "🐠" + ? fishVertical + : symbol === "🫧" + ? bubbleVertical + : undefined; +// One row of the scene: each emoji sits in the middle of an equal share of the width. const Row = ({ symbols }) => ( - {symbols.map(symbol => ( + {symbols.map((symbol) => ( - {symbol} + + {symbol} + ))} ); +// Lock Screen sizes (the "accessory" ones) get a small picture without motion. if (family === "accessoryInline") { $render(Aquarium 🐠); } else if (family === "accessoryCircular") { $render(🐠); } else if (family === "accessoryRectangular") { - $render(🐠Aquarium🪸); + $render( + + 🐠 + Aquarium + 🪸 + , + ); } else { + // Home Screen sizes: rows of sea life above the seabed, with spacers between them. $render( @@ -39,10 +82,13 @@ if (family === "accessoryInline") { + {/* One more row, only on the large sizes. */} {roomy && } {roomy && } - - + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Clock/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Clock/main.jsx index f2a85b0f..4dfe21ef 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Clock/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Clock/main.jsx @@ -1,36 +1,71 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // +// Animation Clock +// An analog clock whose hands are turned by the built-in clock animations. +// Try changing the colors and the lengths of the hands. +// The hands move on iPhone and iPad; a Mac shows them still, at the current time. // - +// Both layouts draw the same clock face. +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the clock face with the time under it. $render( + {/* The face. draws its children on top of each other, centered. */} - - - - - + + {/* A hand is a colored bar above a clear bar of the same size, so the pair turns around */} + {/* the middle of the face. "clockSecond" makes one turn a minute, "clockMinute" one an */} + {/* hour and "clockHour" one every 12 hours. */} + + + + + + + + + + + + + {/* The cap over the center. */} + - - + {/* shows the current time. */} + + , ); } else { + // Medium and larger: the clock face on the left, the time and date on the right. $render( - - - - - + + + + + + + + + + + + + + - ANALOG CLOCK - + + + ANALOG CLOCK + + + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Golden Bloom/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Golden Bloom/main.jsx index 16974fd7..9765cd1a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Golden Bloom/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Golden Bloom/main.jsx @@ -1,7 +1,17 @@ +// Animation Golden Bloom +// A flower whose petals are each turned by the golden angle, in two rings that rotate in +// opposite directions. Try changing the number of petals or the colors. +// +// The golden angle in degrees. Turning each petal by it spreads the petals around the +// circle without two of them landing on the same spot. const goldenAngle = 137.507764; +// The numbers 0 to 12 and 0 to 7: one for each petal and each seed. const petals = Array.from({ length: 13 }, (_, index) => index); const seeds = Array.from({ length: 8 }, (_, index) => index); +// One petal: an ellipse at the top of a tall box with nothing else in it. Rotating the box +// around its center carries the ellipse around the middle of the flower. `rotation` is in +// degrees. const petal = (index) => ( @@ -9,6 +19,7 @@ const petal = (index) => ( ); +// A seed is built the same way with a shorter box, so it sits closer to the middle. const seed = (index) => ( @@ -17,6 +28,8 @@ const seed = (index) => ( ); // Fermat phyllotaxis: consecutive elements differ by the golden angle. +// animation="clockCustom,34" turns a stack half a turn every 34 seconds; a negative +// number turns it the other way. $render( @@ -25,12 +38,18 @@ $render( {seeds.map(seed)} + {/* The center of the flower. */} + {/* The labels: a full-size stack over the picture, with a between the texts. */} - GOLDEN BLOOM + + GOLDEN BLOOM + - φ · 137.507764° + + φ · 137.507764° + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Lissajous/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Lissajous/main.jsx index 88a294a4..5815a443 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Lissajous/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Lissajous/main.jsx @@ -1,22 +1,35 @@ +// Animation Lissajous +// A dot that swings left-right and up-down at the same time, at two different speeds. +// Try changing the two `duration` values; the path depends on their ratio. +// +// Two "swing" motions. Each slides an element back and forth by up to `distance` points; +// a full cycle takes twice `duration` (in seconds). const horizontal = { type: "swing", duration: 7, direction: "horizontal", distance: 88 }; const vertical = { type: "swing", duration: 11, direction: "vertical", distance: 58 }; // Orthogonal oscillators with coprime periods trace a slowly repeating path. $render( + {/* Two crossed outlines as a backdrop. `stroke` draws a 1-point outline with no fill. */} + {/* Nesting applies both motions: the outer stack moves sideways, the inner up and down. */} + {/* The fixed center point. */} - LISSAJOUS 7×11 + + {"LISSAJOUS 7×11"} + - orthogonal phase space + + orthogonal phase space + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Orbital Resonance/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Orbital Resonance/main.jsx index 6e269965..c7ee2e4a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Orbital Resonance/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Orbital Resonance/main.jsx @@ -1,7 +1,15 @@ // Three coupled orbits whose periods form a 2:3:5 resonance. +// Each orbit is a ring with a moon on it, turned by a "clockCustom" animation. +// Try changing the periods in the three orbit(...) calls. +// +// orbit(size, period, color, moonSize, rotation): `size` is the ring's diameter in points, +// `period` the seconds for half a turn (a negative number turns the other way) and +// `rotation` the starting angle in degrees. const orbit = (size, period, color, moonSize, rotation) => ( + {/* The thin ring: `stroke` draws a 1-point outline with no fill. */} + {/* The moon sits at the top of a box as large as the ring, so it travels along the ring. */} @@ -12,14 +20,18 @@ const orbit = (size, period, color, moonSize, rotation) => ( $render( + {/* Half-turn times of 30, 18 and 12 seconds: the ratio 5:3:2. */} {orbit(126, 30, "#67e8f9", 10, 18)} {orbit(98, -18, "#c084fc", 13, 138)} {orbit(70, 12, "#fbbf24", 9, 258)} + {/* The sun in the middle. */} - ORBITAL 2:3:5 + + {"ORBITAL 2:3:5"} + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Phase Wave/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Phase Wave/main.jsx index e99850e1..b740dbd1 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Phase Wave/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Phase Wave/main.jsx @@ -1,6 +1,25 @@ +// Animation Phase Wave +// Nine dots that turn at slightly different speeds, so they drift in and out of step. +// Try changing the step between the phases, or the 0.17 that sets the speed difference. +// +// The starting angle of each dot in degrees: nine equal steps of 40. const phases = [0, 40, 80, 120, 160, 200, 240, 280, 320]; -const colors = ["#38bdf8", "#22d3ee", "#2dd4bf", "#a3e635", "#fde047", "#fb923c", "#fb7185", "#c084fc", "#818cf8"]; +// One color for each dot. +const colors = [ + "#38bdf8", + "#22d3ee", + "#2dd4bf", + "#a3e635", + "#fde047", + "#fb923c", + "#fb7185", + "#c084fc", + "#818cf8", +]; +// One dot at the top of a tall box, with a small gray dot at the bottom. The box starts +// turned by `phase` degrees. "clockCustom,n" turns it half a turn every n seconds; each +// box takes 0.17 seconds longer than the one before. const oscillator = (phase, index) => ( @@ -15,13 +34,16 @@ const oscillator = (phase, index) => ( $render( + {/* Negative spacing makes the nine boxes overlap. */} {phases.map((phase, index) => oscillator(phase, index))} - PHASE WAVE Δφ=40° + + {"PHASE WAVE Δφ=40°"} + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Spirograph/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Spirograph/main.jsx index 32469e5d..b823f090 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Spirograph/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Animation Spirograph/main.jsx @@ -1,3 +1,10 @@ +// Animation Spirograph +// Three dots on circles that turn inside a larger turning circle, some one way and some +// the other. Try changing the periods or adding a fourth satellite. +// +// satellite(radius, period, color, size, phase): a dot at the top of a box `radius` points +// wide. "clockCustom" turns the box half a turn every `period` seconds (a negative number +// turns the other way). `phase` is the starting angle in degrees. const satellite = (radius, period, color, size, phase) => ( @@ -10,18 +17,25 @@ const satellite = (radius, period, color, size, phase) => ( // Counter-rotating epicycles approximate a hypotrochoid mechanism. $render( + {/* Two guide circles. `stroke` draws a 1-point outline with no fill. */} + {/* The outer stack turns as well, so each dot's own turn is added to this one. */} {satellite(112, -9, "#5eead4", 11, 0)} {satellite(82, 15, "#f472b6", 9, 120)} {satellite(54, -6, "#facc15", 7, 240)} + {/* The fixed center. */} - HYPOTROCHOID + + HYPOTROCHOID + - 24 : −9 : 15 : −6 + + 24 : −9 : 15 : −6 + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Battery & Brightness/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Battery & Brightness/main.jsx index b258e4ec..6e2d6d48 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Battery & Brightness/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Battery & Brightness/main.jsx @@ -4,37 +4,75 @@ // // Battery & Brightness // +// Shows two device readings. Try changing the colors or adding a third reading. +// +// Read the data. $device.battery() returns { level, state }: level goes from 0 to 1 and +// state is a word such as "unplugged". $system.brightness() is the screen brightness, +// also from 0 to 1. const battery = $device.battery(); const brightness = $system.brightness(); +// The level as a whole-number percentage, as text: for example "80". const percent = (battery.level * 100).toFixed(0); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the battery level, with the brightness as one line under it. $render( - BATTERY - {percent}% - - {brightness >= 0 ? Math.round(brightness * 100) + "% display" : "Display —"} - + + + + BATTERY + + + + + {percent}% + + + {/* A Mac reports a brightness of -1 (unknown), so a dash is shown for a negative value. */} + + + + {brightness >= 0 ? Math.round(brightness * 100) + "% display" : "Display —"} + + + , ); } else { + // Medium and larger: battery on the left, brightness on the right, a line between. $render( - BATTERY - {percent}% - + + + + BATTERY + + + + {percent}% + + - - - + + + - DISPLAY - {brightness >= 0 ? Math.round(brightness * 100) + "%" : "—"} - Brightness + + + + DISPLAY + + + + {brightness >= 0 ? Math.round(brightness * 100) + "%" : "—"} + + + Brightness + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Birthday Countdown/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Birthday Countdown/main.jsx index b565a359..c98c4172 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Birthday Countdown/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Birthday Countdown/main.jsx @@ -1,3 +1,35 @@ // widget-param: name,MM-DD (optional), e.g. Alex,12-18 -const p = ($getenv("widget-param") || "Alex,12-18").split(","); const name=p[0].trim(); const md=(p[1]||"12-18").split("-").map(Number); const now=new Date(); let next=new Date(now.getFullYear(),md[0]-1,md[1]); if(next{name}{days}days until the celebration); +// Counts the days to the next birthday. Try changing the default name and date below. +// +// $getenv("widget-param") is the parameter set for this widget; the default is used when +// it is empty. +const p = ($getenv("widget-param") || "Alex,12-18").split(","); +const name = p[0].trim(); +// [month, day] as numbers, for example [12, 18]. +const md = (p[1] || "12-18").split("-").map(Number); +const now = new Date(); +// This year's birthday at midnight or, if that has passed, next year's. +let next = new Date(now.getFullYear(), md[0] - 1, md[1]); +if (next < now) next = new Date(now.getFullYear() + 1, md[0] - 1, md[1]); +// 86400000 is the number of milliseconds in a day. Math.ceil rounds a part of a day up. +const days = Math.ceil((next - now) / 86400000); +// frame="max" fills the widget; padding keeps the content 14 points from the edges. +$render( + + + + + + {name} + + + + + {days} + + + days until the celebration + + + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Calendar Agenda/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Calendar Agenda/main.jsx index e2cc7a83..a93decc1 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Calendar Agenda/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Calendar Agenda/main.jsx @@ -2,55 +2,157 @@ // Declare calendar in widget.json. Run in the app to grant access. // Optional widget parameter: comma-separated calendar IDs from $calendar.calendars(). // Browser previews use editable samples; native templates never seed fake events. +// $calendar runs on iPhone and iPad, Mac and Android (for calendars selected in the app); +// not on Windows or Linux. +// Shows today's events, with a layout for each size and a message for each way the read +// can fail. Try changing `limit` or the colors. +// +// The size being drawn. The "accessory" sizes are Lock Screen widgets: for them the colors +// are "primary" and "secondary" instead of fixed values, and the background is clear. const size = $getenv("widget-size"); const accessory = size.startsWith("accessory"); const dark = $device.isdarkmode(); -const foreground = accessory ? "primary" : (dark ? "#f3f4f6" : "#172033"); -const secondary = accessory ? "secondary" : (dark ? "#9ca3af" : "#68758b"); -const background = accessory ? "clear" : (dark ? "#131b2a" : "#f4f7fc"); +const foreground = accessory ? "primary" : dark ? "#f3f4f6" : "#172033"; +const secondary = accessory ? "secondary" : dark ? "#9ca3af" : "#68758b"; +const background = accessory ? "clear" : dark ? "#131b2a" : "#f4f7fc"; const accent = accessory ? "primary" : "#5274d9"; const small = size === "small" || size === "systemSmall"; -const limit = accessory || small ? 2 : (size === "medium" || size === "systemMedium" ? 3 : 6); -let events = [], message = "", authorized = false, stale = false, failed = false; - +// How many events to ask for: 2 on small and Lock Screen sizes, 3 on medium, 6 on larger. +const limit = accessory || small ? 2 : size === "medium" || size === "systemMedium" ? 3 : 6; +// What the read below finds. `message` is shown under, or instead of, the event list. +let events = [], + message = "", + authorized = false, + stale = false, + failed = false; +// Read the data. Each way it can go wrong sets a message instead of stopping the script. try { + // isAvailable() is false on a system without $calendar. authorizationStatus() tells + // whether calendar access has been allowed in the ScriptWidget app. if (!$calendar.isAvailable()) message = "Calendar is unavailable on this device."; - else if ($calendar.authorizationStatus() !== "authorized") message = small ? "Settings → Calendar in ScriptWidget." : "Connect Calendar in ScriptWidget Settings."; + else if ($calendar.authorizationStatus() !== "authorized") + message = small + ? "Settings → Calendar in ScriptWidget." + : "Connect Calendar in ScriptWidget Settings."; else { authorized = true; const parameter = $getenv("widget-param").trim(); + // Ask for today's events, at most `limit`. A saved answer up to 60 seconds old may be used. const options = { limit, maxAgeSeconds: 60 }; - if (parameter) options.calendarIDs = parameter.split(",").map(id => id.trim()).filter(Boolean); + // The optional parameter narrows the read to the listed calendar IDs. + if (parameter) + options.calendarIDs = parameter + .split(",") + .map((id) => id.trim()) + .filter(Boolean); const result = await $calendar.events(options); + // result.items is the list of events. result.stale is true for an older saved answer. events = Array.isArray(result.items) ? result.items : []; stale = result.stale; if (!events.length) message = "Your day is clear."; } } catch (error) { + // The read was rejected. Choose a short message for small sizes, a longer one otherwise. failed = true; - message = String(error).includes("No Calendar sources") ? (small || accessory ? "Choose calendars in Settings." : "Choose Calendar sources in ScriptWidget Settings.") - : String(error).includes("invalid_options") ? (small || accessory ? "Review Calendar selection." : "Review your Calendar selection and widget parameter.") - : (small || accessory ? "Open ScriptWidget to check access." : "Calendar could not load. Open ScriptWidget to check access."); + message = String(error).includes("No Calendar sources") + ? small || accessory + ? "Choose calendars in Settings." + : "Choose Calendar sources in ScriptWidget Settings." + : String(error).includes("invalid_options") + ? small || accessory + ? "Review Calendar selection." + : "Review your Calendar selection and widget parameter." + : small || accessory + ? "Open ScriptWidget to check access." + : "Calendar could not load. Open ScriptWidget to check access."; } +// "All day", or the start time in the device's own format. event.start is an ISO-8601 +// date string. function eventTime(event) { if (event.allDay) return "All day"; return new Date(event.start).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); } +// Choose a layout for the widget size. if (size === "accessoryInline") { - $render({events.length ? `${eventTime(events[0])} ${events[0].title}` : (failed ? "Check Calendar access" : authorized ? "No events today" : "Connect Calendar")}); + // Lock Screen line: the first event, or the reason there is none. + $render( + + {events.length + ? `${eventTime(events[0])} ${events[0].title}` + : failed + ? "Check Calendar access" + : authorized + ? "No events today" + : "Connect Calendar"} + , + ); } else if (size === "accessoryCircular") { - $render({failed ? "Check" : authorized ? `${events.length} events` : "Connect"}); + // Lock Screen circle: an icon and the number of events. + $render( + + + + {failed ? "Check" : authorized ? `${events.length} events` : "Connect"} + + , + ); } else { + // Lock Screen rectangle and all Home Screen sizes: a header, then one row for each event. $render( - - {small ? "AGENDA" : "TODAY'S AGENDA"}{stale && Cached} - {events.map(event => {event.title || "Untitled event"}{eventTime(event)})} - {!!message && {message}} - {(!authorized || failed) && !accessory && {small ? "Settings" : "Open ScriptWidget"}} - {!accessory && } - + + + + + {small ? "AGENDA" : "TODAY'S AGENDA"} + + + {/* "Cached" marks events that come from an older saved answer. */} + {stale && ( + + Cached + + )} + + {events.map((event) => ( + + + + + {event.title || "Untitled event"} + + + {eventTime(event)} + + + + + ))} + {/* The empty or error message, if there is one. */} + {!!message && ( + + {message} + + )} + {/* Without access, a link that opens the calendar access settings of ScriptWidget. */} + {(!authorized || failed) && !accessory && ( + + + + {small ? "Settings" : "Open ScriptWidget"} + + + )} + {/* A spacer at the end pushes the content to the top. */} + {!accessory && } + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Friday Today/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Friday Today/main.jsx index fefc2523..043f4fed 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Friday Today/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Friday Today/main.jsx @@ -1,18 +1,41 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// +// +// Check Is Friday Today +// Shows a different icon and text on Fridays. Try another day number, or other texts. +// var d = new Date(); +// getDay() returns the day of the week: 0 is Sunday, 1 is Monday, … 5 is Friday. var n = d.getDay(); +// console.log writes a line to the log, which helps while testing. console.log(n); +// $render draws the widget. frame="max" fills it; padding (the distance to the edges) +// and spacing (the gap between children) are in points. $render( - FRIDAY CHECK{d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} - - {n == 5 ? "Yes!" : "Not yet"} - {n == 5 ? "The weekend starts here." : `${(5-n+7)%7} days to go.`} - + + + FRIDAY CHECK + + + + {d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} + + + + {/* Values in braces are JavaScript: here the icon and the text depend on the day. */} + + + + {n == 5 ? "Yes!" : "Not yet"} + + + {/* (5 - n + 7) % 7 is the number of days until the next Friday. */} + + {n == 5 ? "The weekend starts here." : `${(5 - n + 7) % 7} days to go.`} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Working Day Today/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Working Day Today/main.jsx index 7803e078..dcc0462c 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Working Day Today/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Check Is Working Day Today/main.jsx @@ -1,18 +1,51 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// Check Is Working Day Today +// Changes its colors, icon and text between working days and days off. +// Try changing which days count as working days. +// var d = new Date(); +// getDay() returns the day of the week: 0 is Sunday, 1 is Monday, … 6 is Saturday. var n = d.getDay(); +// console.log writes a line to the log, which helps while testing. console.log(n); +// Monday to Friday. const working = n >= 1 && n <= 5; +// Every color, icon and text below is chosen with `working ? … : …`. +// frame="max" fills the widget; padding and spacing are in points. $render( - - DAY STATUS{d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} - - {working ? "Work day" : "Day off"} - {working ? "Choose one meaningful priority." : "Rest, reset, and enjoy."} - + + + + DAY STATUS + + + + {d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} + + + + + + + {working ? "Work day" : "Day off"} + + + + {working ? "Choose one meaningful priority." : "Rest, reset, and enjoy."} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Condition Content/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Condition Content/main.jsx index 39f034ba..b7fe5235 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Condition Content/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Condition Content/main.jsx @@ -1,21 +1,65 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Content Select Template -// +// // Description: Choose content at runtime -// +// +// Shows that JSX can be kept in a variable and chosen with ordinary JavaScript. +// Try changing the hour, or adding a third case. +// +// The size being drawn ("small", "medium", "large", …); it is shown in the badge. const widget_size = $getenv("widget-size"); +// true before noon. const morning = new Date().getHours() < 12; -const content = morning - ? Good morningStart with what matters. - : Good eveningMake space to unwind.; +// Two blocks of JSX. Only the chosen one is put into the widget below. +const content = morning ? ( + + + + + Good morning + + + Start with what matters. + + + +) : ( + + + + + Good evening + + + Make space to unwind. + + + +); +// $render draws the widget. frame="max" fills it; padding and spacing are in points. $render( - - CONDITION - {content} - + + + + CONDITION + + + + + + {/* The chosen block goes here. The spacers above and below center it vertically. */} + {content} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Control Switch/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Control Switch/main.jsx index fb0e5fcc..2a1def60 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Control Switch/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Control Switch/main.jsx @@ -1,26 +1,96 @@ // A local flag, not a system Focus/home/device setting. No network or credentials. -const stateKey="switch.enabled",size=$getenv("widget-size"); -function readFlag(){const raw=$storage.getString(stateKey);if(!["","true","false"].includes(raw))throw new Error("The saved local switch is invalid.");return raw==="true";} -function writeFlag(desired){ - for(let attempt=0;attempt<8;attempt++){ - const raw=$storage.getString(stateKey);if(!["","true","false"].includes(raw))throw new Error("The saved local switch is invalid."); - const next=desired===undefined?raw!=="true":desired; - if($storage.compareAndSetString(stateKey,raw,String(next))){$render({next?"Local switch on":"Local switch off"});return;} +// A switch whose state is saved with $storage, so the widget, the control and Shortcuts +// all show and change the same value. Try changing the texts and the icon. +// widget.json declares the "storage" permission (a toggle with a stateKey requires it), +// the three actions (setFlag, enableFlag, disableFlag) and the control. The functions +// below carry the names listed there. +// Control Widgets are on iPhone and iPad; Android shows a Quick Settings tile. +// +// The $storage key that holds the state, and the size being drawn. +const stateKey = "switch.enabled", + size = $getenv("widget-size"); +// Read the saved state. $storage.getString returns "" for a key that was never set, +// which counts as off. +function readFlag() { + const raw = $storage.getString(stateKey); + if (!["", "true", "false"].includes(raw)) throw new Error("The saved local switch is invalid."); + return raw === "true"; +} +// Save a new state. `desired` is true, false, or undefined to flip the current state. +function writeFlag(desired) { + // compareAndSetString saves only if the value is still the one just read. If something + // else changed it in between, read again and retry, at most 8 times. + for (let attempt = 0; attempt < 8; attempt++) { + const raw = $storage.getString(stateKey); + if (!["", "true", "false"].includes(raw)) throw new Error("The saved local switch is invalid."); + const next = desired === undefined ? raw !== "true" : desired; + if ($storage.compareAndSetString(stateKey, raw, String(next))) { + $render({next ? "Local switch on" : "Local switch off"}); + return; + } } throw new Error("The local switch changed. Refresh and try again."); } -function setFlag(){const value=$getenv("action-value");if(value!==""&&value!=="true"&&value!=="false")throw new Error("Invalid switch value.");writeFlag(value===""?undefined:value==="true");} -function enableFlag(){writeFlag(true);} -function disableFlag(){writeFlag(false);} -const enabled=readFlag(),dark=$device.isdarkmode(),background=dark?"#111827":"#eff6ff",ink=dark?"#f8fafc":"#1e3a8a",muted=dark?"#cbd5e1":"#475569"; -if(size==="function"||size==="action"){ +// The actions named in widget.json. A toggle passes the wanted state in +// $getenv("action-value") as "true" or "false"; without a value the switch is flipped. +function setFlag() { + const value = $getenv("action-value"); + if (value !== "" && value !== "true" && value !== "false") + throw new Error("Invalid switch value."); + writeFlag(value === "" ? undefined : value === "true"); +} +function enableFlag() { + writeFlag(true); +} +function disableFlag() { + writeFlag(false); +} +// Read the data, and choose colors for dark or light mode. +const enabled = readFlag(), + dark = $device.isdarkmode(), + background = dark ? "#111827" : "#eff6ff", + ink = dark ? "#f8fafc" : "#1e3a8a", + muted = dark ? "#cbd5e1" : "#475569"; +// Choose what to draw. While an action runs, the size is "function" or "action". +if (size === "function" || size === "action") { // App Intents call the same declared handler after source evaluation. -}else if(size==="accessoryInline"){ - $render({enabled?"Local switch on":"Local switch off"}); -}else if(size==="accessoryCircular"){ - $render({enabled?"On":"Off"}); -}else if(size==="accessoryRectangular"){ - $render(Local switch); -}else{ - $render(Local switch{enabled?"On":"Off"}Shared with this widget’s control and Shortcuts); +} else if (size === "accessoryInline") { + // Lock Screen line: text only. + $render({enabled ? "Local switch on" : "Local switch off"}); +} else if (size === "accessoryCircular") { + // Lock Screen circle: an icon with On or Off. + $render( + + + {enabled ? "On" : "Off"} + , + ); +} else if (size === "accessoryRectangular") { + // Lock Screen rectangle: a working toggle. actionID names the action in widget.json to + // run on a tap, and stateKey is the $storage key that holds the state. + $render( + + Local switch + , + ); +} else { + // Home Screen sizes: a title, the toggle and a note. + $render( + + + + + Local switch + + + + + {enabled ? "On" : "Off"} + + + + Shared with this widget’s control and Shortcuts + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/lib/countdown.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/lib/countdown.js index 73852e27..fdc05cc8 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/lib/countdown.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/lib/countdown.js @@ -1,81 +1,186 @@ // Calendar days use Gregorian ordinals, never elapsed 24-hour periods. +// This file is imported by main.jsx. It defines one global, CountdownCalendar, +// with two functions: configuration() reads the settings and describe() turns them into +// the texts the widget shows. It draws nothing itself. var CountdownCalendar = (() => { - const defaults = {title: "Your next moment", targetDate: "", repeatYearly: false, accent: "blue"}; + // The settings used when nothing has been saved. + const defaults = { + title: "Your next moment", + targetDate: "", + repeatYearly: false, + accent: "blue", + }; + // Split "YYYY-MM-DD" into [year, month, day]. Returns null for anything that is not a + // real calendar date, such as 2027-02-30. function parts(text) { if (typeof text !== "string" || !/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/.test(text)) return null; const [year, month, day] = text.split("-").map(Number); if (year < 1970 || year > 9999) return null; const date = new Date(Date.UTC(year, month - 1, day)); - return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day ? [year, month, day] : null; + return date.getUTCFullYear() === year && + date.getUTCMonth() === month - 1 && + date.getUTCDate() === day + ? [year, month, day] + : null; } + // true if `value` holds exactly the four settings, each with a valid value. function validate(value) { - return value && typeof value === "object" && !Array.isArray(value) && + return ( + value && + typeof value === "object" && + !Array.isArray(value) && Object.keys(value).sort().join(",") === "accent,repeatYearly,targetDate,title" && - typeof value.title === "string" && value.title.trim().length > 0 && value.title.length <= 40 && - (value.targetDate === "" || !!parts(value.targetDate)) && typeof value.repeatYearly === "boolean" && - ["blue", "rose", "green"].includes(value.accent); + typeof value.title === "string" && + value.title.trim().length > 0 && + value.title.length <= 40 && + (value.targetDate === "" || !!parts(value.targetDate)) && + typeof value.repeatYearly === "boolean" && + ["blue", "rose", "green"].includes(value.accent) + ); } + // Build the settings. `raw` is the saved JSON text from storage ("" if nothing was + // saved) and `parameter` is the widget's parameter. Returns { value, time }: the settings + // and, if the parameter gave a time of day, [hour, minute, second]. function configuration(raw, parameter) { - let value = {...defaults}; + let value = { ...defaults }; + // The saved text must be { kind: "countdown", version: 1, values: {…} } and at most + // 4096 bytes; unescape(encodeURIComponent(raw)).length is its size in UTF-8 bytes. if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved countdown configuration is invalid. Open Records & Configuration to repair it."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || !state || - Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== "countdown" || !validate(state.values)) { - throw new Error("Saved countdown configuration is invalid. Open Records & Configuration to repair it."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved countdown configuration is invalid. Open Records & Configuration to repair it.", + ); + } + if ( + typeof raw !== "string" || + unescape(encodeURIComponent(raw)).length > 4096 || + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== "countdown" || + !validate(state.values) + ) { + throw new Error( + "Saved countdown configuration is invalid. Open Records & Configuration to repair it.", + ); } value = state.values; } parameter = (parameter || "").trim(); - if (!parameter) return {value, time: null}; + // No parameter: use the saved settings as they are. + if (!parameter) return { value, time: null }; + // A parameter that starts with "{" is JSON; its keys replace single settings. if (parameter[0] === "{") { let custom; - try { custom = JSON.parse(parameter); } catch (_) { throw new Error("Use valid JSON for countdown settings."); } - if (!custom || Array.isArray(custom) || Object.keys(custom).some(key => !Object.prototype.hasOwnProperty.call(defaults, key))) throw new Error("Unknown countdown setting."); - value = {...value, ...custom}; - if (!validate(value)) throw new Error("Use a valid event name, calendar date, repeat setting and accent."); - return {value, time: null}; + try { + custom = JSON.parse(parameter); + } catch (_) { + throw new Error("Use valid JSON for countdown settings."); + } + if ( + !custom || + Array.isArray(custom) || + Object.keys(custom).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error("Unknown countdown setting."); + value = { ...value, ...custom }; + if (!validate(value)) + throw new Error("Use a valid event name, calendar date, repeat setting and accent."); + return { value, time: null }; } + // Otherwise the parameter is "YYYY-MM-DD Title" or "YYYY-MM-DDTHH:mm:ss Title". + // The title is optional. const match = /^(\d{4}-\d{2}-\d{2})(?:T(\d{2}):(\d{2}):(\d{2}))?(?:\s+(.+))?$/.exec(parameter); - if (!match || !parts(match[1])) throw new Error("Use YYYY-MM-DD Event or YYYY-MM-DDTHH:mm:ss Event."); + if (!match || !parts(match[1])) + throw new Error("Use YYYY-MM-DD Event or YYYY-MM-DDTHH:mm:ss Event."); const time = match[2] === undefined ? null : match.slice(2, 5).map(Number); - if (time && (time[0] > 23 || time[1] > 59 || time[2] > 59)) throw new Error("Use a valid local time."); - value = {...value, title: match[5] || value.title, targetDate: match[1], repeatYearly: false}; + if (time && (time[0] > 23 || time[1] > 59 || time[2] > 59)) + throw new Error("Use a valid local time."); + value = { ...value, title: match[5] || value.title, targetDate: match[1], repeatYearly: false }; if (!validate(value)) throw new Error("Keep the event name to 40 characters."); - return {value, time}; + return { value, time }; } + // The number of days from 1970-01-01 to a date. The difference of two of these is a count + // of calendar days that daylight-saving changes cannot disturb. const ordinal = ([year, month, day]) => Date.UTC(year, month - 1, day) / 86400000; + // Turn the settings into the texts to show at the time `now`. function describe(settings, now) { const value = settings.value; if (!Number.isFinite(now.getTime())) throw new Error("The preview date is invalid."); - if (!value.targetDate) return {configured: false, title: value.title, number: "—", unit: "Choose a date", summary: "Set up your countdown", date: "Records & Configuration", accent: value.accent}; + // No date chosen yet: show a hint instead of a number. + if (!value.targetDate) + return { + configured: false, + title: value.title, + number: "—", + unit: "Choose a date", + summary: "Set up your countdown", + date: "Records & Configuration", + accent: value.accent, + }; let target = parts(value.targetDate); const today = [now.getFullYear(), now.getMonth() + 1, now.getDate()]; if (value.repeatYearly) { + // A yearly event: find its next occurrence, today included. Looking up to 8 years ahead + // covers February 29, which most years lack. let next = null; for (let year = today[0]; year <= Math.min(9999, today[0] + 8); year++) { - const text = `${year}-${String(target[1]).padStart(2,"0")}-${String(target[2]).padStart(2,"0")}`; + const text = `${year}-${String(target[1]).padStart(2, "0")}-${String(target[2]).padStart(2, "0")}`; const candidate = parts(text); - if (candidate && ordinal(candidate) >= ordinal(today)) { next = candidate; break; } + if (candidate && ordinal(candidate) >= ordinal(today)) { + next = candidate; + break; + } } if (!next) throw new Error("No upcoming occurrence in the supported date range."); target = next; } + // Days until the target: positive in the future, negative in the past, 0 today. const days = ordinal(target) - ordinal(today); const dayWord = Math.abs(days) === 1 ? "day" : "days"; - let number = String(Math.abs(days)), unit = days === 0 ? "Today" : `${dayWord} ${days > 0 ? "to go" : "since"}`; + let number = String(Math.abs(days)), + unit = days === 0 ? "Today" : `${dayWord} ${days > 0 ? "to go" : "since"}`; let summary = days === 0 ? "Today" : `${Math.abs(days)} ${unit}`; + // With a time of day, count minutes instead of days. if (settings.time) { const [hour, minute, second] = settings.time; const date = new Date(target[0], target[1] - 1, target[2], hour, minute, second); - if (date.getFullYear() !== target[0] || date.getMonth() !== target[1] - 1 || date.getDate() !== target[2] || date.getHours() !== hour || date.getMinutes() !== minute || date.getSeconds() !== second) throw new Error("That local time does not exist in this time zone."); + // A local time skipped by a daylight-saving change comes back changed; reject it. + if ( + date.getFullYear() !== target[0] || + date.getMonth() !== target[1] - 1 || + date.getDate() !== target[2] || + date.getHours() !== hour || + date.getMinutes() !== minute || + date.getSeconds() !== second + ) + throw new Error("That local time does not exist in this time zone."); const remaining = date.getTime() - now.getTime(); + // Round up to whole minutes, then show days, or hours and minutes, or minutes. const minutes = Math.ceil(Math.abs(remaining) / 60000); - number = minutes >= 1440 ? String(Math.floor(minutes / 1440)) : minutes >= 60 ? `${Math.floor(minutes / 60)}h ${minutes % 60}m` : `${minutes}m`; + number = + minutes >= 1440 + ? String(Math.floor(minutes / 1440)) + : minutes >= 60 + ? `${Math.floor(minutes / 60)}h ${minutes % 60}m` + : `${minutes}m`; unit = remaining === 0 ? "Now" : remaining > 0 ? "until the moment" : "since the moment"; summary = `${number} ${unit}`; } - return {configured: true, title: value.title, number, unit, summary, date: target.map((p,i) => i ? String(p).padStart(2,"0") : String(p)).join("-"), accent: value.accent, repeatYearly: value.repeatYearly}; + return { + configured: true, + title: value.title, + number, + unit, + summary, + // The target date as YYYY-MM-DD. + date: target.map((p, i) => (i ? String(p).padStart(2, "0") : String(p))).join("-"), + accent: value.accent, + repeatYearly: value.repeatYearly, + }; } - return {configuration, describe}; + return { configuration, describe }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/main.jsx index 8e5ec987..bc371fca 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Countdown/main.jsx @@ -2,48 +2,148 @@ // them: 2027-01-01 New Year, 2027-01-01T12:30:00 Flight, or JSON settings. // Calendar dates follow the device's local Gregorian date. WidgetKit schedules // updates; this is not a continuously ticking timer. -if (!$import("lib/countdown.js")) throw new Error("Install the complete Countdown template, including lib/countdown.js."); -const settings = CountdownCalendar.configuration($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); -const moment = CountdownCalendar.describe(settings, new Date($getenv("timeline-date") || Date.now())); +// widget.json declares the "storage" permission, and a timeline with dailyTimes +// ["00:00"] so the day count changes at midnight. +// Try changing the colors in `palette` or the layouts below. +// +// $import runs another file of this package; the check fails if it could not be loaded. +// lib/countdown.js defines the global CountdownCalendar used below. +if (!$import("lib/countdown.js")) + throw new Error("Install the complete Countdown template, including lib/countdown.js."); +// Read the settings: the saved defaults from $storage, then the widget's parameter. +const settings = CountdownCalendar.configuration( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Work out the texts to show. "timeline-date" is the date this entry is drawn for; +// the current time is used when it is not set. +const moment = CountdownCalendar.describe( + settings, + new Date($getenv("timeline-date") || Date.now()), +); +// Three color sets. The `accent` setting chooses one. const palette = { - blue: {background: "#eff6ff", ink: "#1e3a8a", soft: "#3b82f6"}, - rose: {background: "#fff1f2", ink: "#881337", soft: "#e11d48"}, - green: {background: "#ecfdf5", ink: "#064e3b", soft: "#059669"}, + blue: { background: "#eff6ff", ink: "#1e3a8a", soft: "#3b82f6" }, + rose: { background: "#fff1f2", ink: "#881337", soft: "#e11d48" }, + green: { background: "#ecfdf5", ink: "#064e3b", soft: "#059669" }, }[moment.accent]; +// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets. const size = $getenv("widget-size"); if (size === "accessoryInline") { + // Lock Screen line: the title and the summary as text. $render({moment.title + ": " + moment.summary}); } else if (size === "accessoryCircular") { - $render({moment.number}); + // Lock Screen circle: an icon and the number. + $render( + + + + {moment.number} + + , + ); } else if (size === "accessoryRectangular") { - $render({moment.title}{moment.summary}); + // Lock Screen rectangle: the title above the summary. + $render( + + {moment.title} + {moment.summary} + , + ); } else if (size === "medium") { - $render( - - COUNTDOWN - {moment.title} - {moment.date} - - - {moment.number}{moment.unit} - ); + // Medium: the title and date on the left, the number on the right. + // frame="max" fills the widget; padding and spacing are in points. + $render( + + + + COUNTDOWN + + + {moment.title} + + + {moment.date} + + + + + + {moment.number} + + + {moment.unit} + + + , + ); } else if (size === "small") { - const shortTitle = Array.from(moment.title).slice(0, 14).join("") + (Array.from(moment.title).length > 14 ? "…" : ""); - $render( - COUNTDOWN - {moment.number} - {moment.unit} - {shortTitle} - {moment.date} - ); + // Small: cut the title to 14 characters. Array.from counts whole characters, so an emoji + // is not cut in half. + const shortTitle = + Array.from(moment.title).slice(0, 14).join("") + + (Array.from(moment.title).length > 14 ? "…" : ""); + $render( + + + COUNTDOWN + + + {moment.number} + + + {moment.unit} + + + {shortTitle} + + + {moment.date} + + , + ); } else { - $render( - COUNTDOWN - - {moment.number} - {moment.unit} - - {moment.title} - {moment.date} - ); + // Large and extra-large: the number in the middle, the title and date at the bottom. + $render( + + + + COUNTDOWN + + + {/* A repeat icon for a yearly event, a calendar icon otherwise. */} + + + + + {moment.number} + + + {moment.unit} + + + + {moment.title} + + + {moment.date} + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Crypto Price Ticker/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Crypto Price Ticker/main.jsx index 76853899..b16f33ef 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Crypto Price Ticker/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Crypto Price Ticker/main.jsx @@ -5,23 +5,44 @@ // Crypto Price Ticker (CoinGecko) // widget-param: coin id, e.g. "bitcoin", "ethereum" // +// Shows the price of one coin in US dollars and its 24-hour change, read from a web API. +// Try another coin id as the default, or another currency in the URL. +// +// $getenv("widget-param") is the parameter set for this widget; "bitcoin" is used when it is +// empty. const coin = ($getenv("widget-param") || "bitcoin").trim().toLowerCase(); +// Read the data from CoinGecko. +// Here fetch returns the response body as text, so it is parsed with JSON.parse. +// This template has no widget.json. In a package that has one, fetch only works when +// widget.json declares the "network" permission and lists this host in "networkDomains". const url = `https://api.coingecko.com/api/v3/simple/price?ids=${coin}&vs_currencies=usd&include_24hr_change=true`; const result = await fetch(url); const data = JSON.parse(result); +// The answer looks like { bitcoin: { usd: 64000, usd_24h_change: -1.2 } }. +// An unknown coin id has no entry, so zeros are shown. const info = data[coin] || { usd: 0, usd_24h_change: 0 }; const price = info.usd || 0; const change = info.usd_24h_change || 0; +// Green for a rise and red for a fall; a rise also gets a "+" sign. const changeColor = change >= 0 ? "#22c55e" : "#ef4444"; const changeLabel = change >= 0 ? "+" + change.toFixed(2) : change.toFixed(2); +// frame="max" makes the stack fill the whole widget. $render( - Crypto Ticker - {coin.toUpperCase()} - ${price.toFixed(2)} - {changeLabel}% 24h - + + Crypto Ticker + + + {coin.toUpperCase()} + + + ${price.toFixed(2)} + + + {changeLabel}% 24h + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Currency Pulse/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Currency Pulse/main.jsx index 2e636aa7..25045f49 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Currency Pulse/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Currency Pulse/main.jsx @@ -5,21 +5,52 @@ // Currency Pulse (open.er-api.com) // widget-param: base currency (optional) // +// Shows what one unit of the base currency is worth in three others, read from a web API. +// Try changing the three currency codes in the elements. +// +// $getenv("widget-param") is the parameter set for this widget; "USD" is used when it is empty. const base = ($getenv("widget-param") || "USD").trim().toUpperCase(); +// Read the data from open.er-api.com. +// Here fetch returns the response body as text, so it is parsed with JSON.parse. +// This template has no widget.json. In a package that has one, fetch only works when +// widget.json declares the "network" permission and lists this host in "networkDomains". const url = `https://open.er-api.com/v6/latest/${base}`; const result = await fetch(url); const data = JSON.parse(result); +// `rates` maps a currency code to its rate, for example { EUR: 0.92, … }. const rates = data.rates || {}; +// frame="max" makes the stack fill the whole widget. $render( - Currency Pulse - Base: {base} + + Currency Pulse + + + Base: {base} + - - - + {/* is a block with a title, a value and a subtitle. */} + {/* "-" is shown for a currency that the answer does not contain. */} + + + - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Affirmation/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Affirmation/main.jsx index d9063535..49115c0f 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Affirmation/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Affirmation/main.jsx @@ -1,3 +1,20 @@ // widget-param: your affirmation (optional) -const words=($getenv("widget-param")||"I have everything I need for today.").trim(); -$render({words}DAILY AFFIRMATION); +// Shows one sentence in bold type. Try changing the default sentence or the colors. +// +// $getenv("widget-param") is the parameter set for this widget; the default text is used +// when it is empty. +const words = ($getenv("widget-param") || "I have everything I need for today.").trim(); +// frame="max" fills the widget and alignment="leading" lines the children up on the +// left. padding and spacing are in points. +$render( + + + {/* frame="max,leading" gives the text the remaining space, aligned to the left. */} + + {words} + + + DAILY AFFIRMATION + + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Agenda/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Agenda/main.jsx index 9f29eec1..e1c76e9a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Agenda/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Agenda/main.jsx @@ -1,3 +1,31 @@ // widget-param: Plan,Deep work,Walk (optional) -const items = ($getenv("widget-param") || "Plan the day,Deep work,Take a walk").split(",").slice(0, 3); -$render(Today{items.map((item, i) => {item.trim()})}); +// Shows up to three items as a numbered list. Try changing the default items. +// +// Split the parameter (or the default, when it is empty) at the commas and keep the first +// three items. +const items = ($getenv("widget-param") || "Plan the day,Deep work,Take a walk") + .split(",") + .slice(0, 3); +// frame="max" fills the widget; padding and spacing are in points. +$render( + + + + Today + + + {/* shows today's date. */} + + + {/* One row for each item: map turns the list of texts into a list of elements. */} + {items.map((item, i) => ( + + + + {item.trim()} + + + + ))} + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Command Center/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Command Center/main.jsx index 76bdefc1..5f79e024 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Command Center/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Command Center/main.jsx @@ -1,66 +1,172 @@ -// Designed for the large widget; the small and medium sizes show the essentials. widget-param: Focus task|09:00 Stand-up,11:30 Deep work,15:00 Review|Email Alex,Book dentist,Walk 20 min -const parts = ($getenv("widget-param") || "Ship the weekly update|09:00 Stand-up,11:30 Deep work,15:00 Review|Reply to Sam,Book dentist,Walk 20 min").split("|"); +// Designed for the large widget; the small and medium sizes show the essentials. +// widget-param: Focus task|09:00 Stand-up,11:30 Deep work,15:00 Review|Email Alex,Book dentist,Walk 20 min +// The parameter has three parts separated by "|": the focus, the schedule and the tasks. +// Try changing the default text below, or the colors. +// +// $getenv("widget-param") is the parameter set for this widget; the default is used when +// it is empty. +const parts = ( + $getenv("widget-param") || + "Ship the weekly update|09:00 Stand-up,11:30 Deep work,15:00 Review|Reply to Sam,Book dentist,Walk 20 min" +).split("|"); +// Take the three parts. filter(Boolean) drops empty entries; slice(0, 3) keeps three. const focus = (parts[0] || "Choose one meaningful outcome").trim(); const schedule = (parts[1] || "").split(",").filter(Boolean).slice(0, 3); const tasks = (parts[2] || "").split(",").filter(Boolean).slice(0, 3); const now = new Date(); +// The share of the day that has passed, from 0 to 1. A day has 1440 minutes. const progress = (now.getHours() * 60 + now.getMinutes()) / 1440; +// One line of a list. The first entry gets a brighter dot and text. const Row = ({ text, index }) => ( - - {text.trim()} + + + {text.trim()} + ); +// Choose a layout for the widget size. const size = $getenv("widget-size"); if (size === "small") { // Small: the primary outcome, the day's progress and the next entry of the schedule. $render( - PRIMARY OUTCOME - {focus} - - {schedule.length ? {schedule[0].trim()} : null} - + + + PRIMARY OUTCOME + + + + + {focus} + + {/* The bar shows how much of the day has passed. */} + + {schedule.length ? ( + + + + {schedule[0].trim()} + + + ) : null} + , ); } else if (size === "medium") { // Medium: the primary outcome beside the schedule. $render( - - PRIMARY OUTCOME - {focus} - + {/* A card: its own background with rounded corners (`corner`, in points). */} + {/* frame="max,142,topLeading" is full width, 142 points high, content at the top left. */} + + + PRIMARY OUTCOME + + + {focus} + + - - SCHEDULE - {schedule.map((item, i) => )} + + + + SCHEDULE + + + + + {schedule.map((item, i) => ( + + ))} - + , ); } else { + // Large and bigger: a header, the outcome card, then schedule and tasks side by side. $render( - Today - + + + Today + + + + + - - PRIMARY OUTCOME - {focus} - + + + PRIMARY OUTCOME + + + {focus} + + - - SCHEDULE - {schedule.map((item, i) => )} + + + + SCHEDULE + + + + + {schedule.map((item, i) => ( + + ))} - - QUICK TASKS - {tasks.map((item, i) => )} + + + + QUICK TASKS + + + + + {tasks.map((item, i) => ( + + ))} - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Quote/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Quote/main.jsx index 7327b183..8227329d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Quote/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Daily Quote/main.jsx @@ -4,16 +4,31 @@ // // Daily Quote (zenquotes.io) // +// Shows the quote of the day, read from a web API. Try changing the colors or fonts. +// +// Read the data. +// Here fetch returns the response body as text, so it is parsed with JSON.parse. +// This template has no widget.json. In a package that has one, fetch only works when +// widget.json declares the "network" permission and lists this host in "networkDomains". const url = "https://zenquotes.io/api/today"; const result = await fetch(url); const data = JSON.parse(result); +// The answer is a list with one quote: `q` is the text and `a` the author. +// The fallback is used when the list is empty. const quote = data && data.length ? data[0] : { q: "Stay inspired", a: "ScriptWidget" }; +// frame="max" makes the stack fill the whole widget. $render( - Daily Quote - "{quote.q}" - - {quote.a} - + + Daily Quote + + + "{quote.q}" + + + - {quote.a} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Current/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Current/main.jsx index e49372f3..8c03ba04 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Current/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Current/main.jsx @@ -1,28 +1,53 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Clock Template -// +// // Description: Display Clock Time -// +// +// Shows the time and date with . Try another style or font. +// +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the time, with a short date that fits the narrow widget. $render( - CURRENT TIME + + + CURRENT TIME + + + + - - {new Date().toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} + {/* shows the current time. */} + + + {new Date().toLocaleDateString("en-US", { + weekday: "short", + month: "short", + day: "numeric", + })} + - + , ); } else { + // Medium and larger: the time and date on the left, a large icon on the right. $render( - CURRENT TIME - - + + + CURRENT TIME + + + {/* style="date" shows the date instead of the time. */} + + + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Timezone/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Timezone/main.jsx index e1b2795f..8fb1526d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Timezone/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Datetime Timezone/main.jsx @@ -1,31 +1,87 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // +// Datetime Timezone +// Shows the time in three cities. Try changing the cities and their time zone names. // +// The size being drawn, and the widget's parameter (read here, but not used below). const widget_size = $getenv("widget-size"); const widget_param = $getenv("widget-param"); -const time = zone => new Date().toLocaleTimeString([], { timeZone: zone, hour: "2-digit", minute: "2-digit" }); +// The time in a zone such as "Asia/Shanghai", as hours and minutes in the device's own +// format. The text is worked out when the script runs. +const time = (zone) => + new Date().toLocaleTimeString([], { timeZone: zone, hour: "2-digit", minute: "2-digit" }); if (widget_size === "small") { // Small: one city on each line. - const City = ({ name, zone }) => {name}{time(zone)}; + // A component for one line: the city on the left, its time on the right. + const City = ({ name, zone }) => ( + + + {name} + + + + {time(zone)} + + + ); $render( - World Clock - - - - + + + World Clock + + + + + + + + , ); } else { + // Medium and larger: the three cities side by side. $render( - World Clock - BEIJING{time("Asia/Shanghai")}SAN JOSE{time("America/Los_Angeles")}NEW YORK{time("America/New_York")} - + + + World Clock + + + + + + + + BEIJING + + + {time("Asia/Shanghai")} + + + + + + SAN JOSE + + + {time("America/Los_Angeles")} + + + + + + NEW YORK + + + {time("America/New_York")} + + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Day Rhythm/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Day Rhythm/main.jsx index 2da4b395..cf8032a1 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Day Rhythm/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Day Rhythm/main.jsx @@ -1,35 +1,113 @@ // Day Rhythm — local scheduled themes, without network or personal data. // Change dailyTimes/timeZone in widget.json. Optional widget-param: {"name":"Alex"}. +// Shows one of four themes, chosen by the time of day. widget.json lists four times in +// timeline.dailyTimes (06:00, 12:00, 18:00, 22:00) and the theme changes at each of them. +// Try changing the texts and colors in `phases`. +// +// One theme for each time in dailyTimes, in the same order. `symbol` names a system icon. const phases = [ - { title: "Morning focus", hint: "Make room for one good thing.", symbol: "sunrise.fill", background: "#fff7ed", accent: "#9a3412", label: "MORNING" }, - { title: "Afternoon flow", hint: "A little progress goes a long way.", symbol: "sun.max.fill", background: "#eff6ff", accent: "#1e40af", label: "AFTERNOON" }, - { title: "Evening reset", hint: "Slow down and recharge.", symbol: "sunset.fill", background: "#f5f3ff", accent: "#6b21a8", label: "EVENING" }, - { title: "Quiet hours", hint: "Rest is part of the rhythm.", symbol: "moon.stars.fill", background: "#eef2f6", accent: "#334155", label: "NIGHT" }, + { + title: "Morning focus", + hint: "Make room for one good thing.", + symbol: "sunrise.fill", + background: "#fff7ed", + accent: "#9a3412", + label: "MORNING", + }, + { + title: "Afternoon flow", + hint: "A little progress goes a long way.", + symbol: "sun.max.fill", + background: "#eff6ff", + accent: "#1e40af", + label: "AFTERNOON", + }, + { + title: "Evening reset", + hint: "Slow down and recharge.", + symbol: "sunset.fill", + background: "#f5f3ff", + accent: "#6b21a8", + label: "EVENING", + }, + { + title: "Quiet hours", + hint: "Rest is part of the rhythm.", + symbol: "moon.stars.fill", + background: "#eef2f6", + accent: "#334155", + label: "NIGHT", + }, ]; +// "timeline-slot" is the index of the dailyTimes entry now in effect: 0 to 3 here. let slot = Number($getenv("timeline-slot")); +// Fallback when the slot is missing or out of range: choose by the hour instead. if (!$getenv("timeline-slot") || !Number.isInteger(slot) || slot < 0 || slot >= phases.length) { + // "timeline-date" is the date this entry is drawn for; without it, use the time now. const date = new Date($getenv("timeline-date") || Date.now()); const hour = date.getHours(); slot = hour >= 22 || hour < 6 ? 3 : hour >= 18 ? 2 : hour >= 12 ? 1 : 0; } const phase = phases[slot]; +// The optional name from the parameter, such as {"name":"Alex"}, cut to 24 characters. +// A parameter that is not valid JSON is ignored. let name = ""; -try { const value = JSON.parse($getenv("widget-param") || "{}"); if (typeof value.name === "string") name = value.name.slice(0, 24); } catch {} +try { + const value = JSON.parse($getenv("widget-param") || "{}"); + if (typeof value.name === "string") name = value.name.slice(0, 24); +} catch {} +// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets. const family = $getenv("widget-size"); if (family === "accessoryInline") { + // Lock Screen line: the title only. $render({phase.title}); } else if (family === "accessoryCircular") { - $render({String(slot + 1) + "/4"}); + // Lock Screen circle: the icon and the position, such as "2/4". + $render( + + + {String(slot + 1) + "/4"} + , + ); } else if (family === "accessoryRectangular") { - $render({phase.title}{name || "Find your daily rhythm"}); + // Lock Screen rectangle: the icon beside the title and the name. + $render( + + + + {phase.title} + {name || "Find your daily rhythm"} + + , + ); } else { + // Home Screen sizes share one layout; the small one uses less padding and smaller type. + // frame="max" fills the widget; padding and spacing are in points. const compact = family === "small"; $render( - - {phase.label}{String(slot + 1) + "/4"} - - {phase.title} - {name ? name + ", " : ""}{phase.hint} - + + + + {phase.label} + + + + {String(slot + 1) + "/4"} + + + + + {phase.title} + + + {name ? name + ", " : ""} + {phase.hint} + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Device Battery Percent/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Device Battery Percent/main.jsx index a2c48572..0a20decb 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Device Battery Percent/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Device Battery Percent/main.jsx @@ -1,27 +1,64 @@ // -// ScriptWidget +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Battery Percent Template -// - +// +// Shows the battery level as a number and a ring. Try changing the colors or the +// thickness of the ring. +// +// $device.battery().level goes from 0 to 1. Turn it into a whole-number percentage; +// toFixed returns text, for example "80". var percent = $device.battery().level * 100; percent = percent.toFixed(0); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the percentage inside the ring. $render( - DEVICE BATTERY - {percent}% - + + DEVICE BATTERY + + + {/* takes a value from 0 to 1. The draws the text on top of it. */} + + + {percent}% + + + , ); } else { + // Medium and larger: the number on the left, the ring on the right. $render( - DEVICE BATTERY{percent}%Power at a glance - - + + + DEVICE BATTERY + + + {percent}% + + + Power at a glance + + + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Family Command Board/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Family Command Board/main.jsx index cf720c3d..6ddd5474 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Family Command Board/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Family Command Board/main.jsx @@ -1,63 +1,230 @@ -// Designed for the large widget; the small and medium sizes show the essentials. widget-param: Family name|events comma-separated|chores comma-separated|dinner -const parts = ($getenv("widget-param") || "The Parkers|08:15 School drop-off,17:30 Soccer practice,19:00 Call Grandma|Mia · Feed Mochi,Noah · Recycling,All · Tidy kitchen|Taco bowls · 18:30").split("|"); +// Designed for the large widget; the small and medium sizes show the essentials. +// widget-param: Family name|events comma-separated|chores comma-separated|dinner +// Try changing the default text below, or the colors. +// +// $getenv("widget-param") is the parameter set for this widget; the default is used when +// it is empty. +const parts = ( + $getenv("widget-param") || + "The Parkers|08:15 School drop-off,17:30 Soccer practice,19:00 Call Grandma|Mia · Feed Mochi,Noah · Recycling,All · Tidy kitchen|Taco bowls · 18:30" +).split("|"); +// Take the four parts. filter(Boolean) drops empty entries; slice(0, 3) keeps three. const family = (parts[0] || "Our Family").trim(); const events = (parts[1] || "").split(",").filter(Boolean).slice(0, 3); const chores = (parts[2] || "").split(",").filter(Boolean).slice(0, 3); const dinner = (parts[3] || "Plan dinner together").trim(); +// One bar color for each of the three events. const colors = ["#fb7185", "#fbbf24", "#60a5fa"]; // "08:15 School drop-off" is drawn as the time above the title, so both fit the half-width card. const Event = ({ text, index }) => { + // The first word is the time, when the text has more than one word. const words = text.trim().split(" "); const time = words.length > 1 ? words[0] : ""; return ( - {time ? {time} : null}{words.slice(time ? 1 : 0).join(" ")} + + + + {time ? ( + + {time} + + ) : null} + + {words.slice(time ? 1 : 0).join(" ")} + + + ); }; +// Choose a layout for the widget size. `today` is a short date such as "Nov 18". const size = $getenv("widget-size"); const today = new Date().toLocaleDateString("en-US", { month: "short", day: "numeric" }); if (size === "small") { // Small: the next event and dinner. $render( - TODAY{today} - {events.length ? : null} - DINNER PLAN{dinner} - + + + + TODAY + + + + {today} + + + {events.length ? : null} + {/* A card: its own background with rounded corners (`corner`, in points). */} + {/* frame="max,52,leading" is full width, 52 points high, content on the left. */} + + + + DINNER PLAN + + + + + {dinner} + + + , ); } else if (size === "medium") { // Medium: today's events beside the first chore and dinner. $render( - - TODAY{today} - {events.map((item, i) => )} + + + + TODAY + + + + {today} + + + {events.map((item, i) => ( + + ))} - - CHORES - {chores.length ? {chores[0].trim()} : null} + + + + CHORES + + + {/* The badge counts all chores; this size lists only the first one. */} + + + {chores.length ? ( + + + + {chores[0].trim()} + + + ) : null} + + + + + DINNER PLAN + + + + + {dinner} + - DINNER PLAN{dinner} - + , ); } else { + // Large and bigger: a header, events and chores side by side, dinner at the bottom. $render( - {family}Home at a glance + + + + {family} + + + Home at a glance + + + + + - - TODAY{new Date().toLocaleDateString("en-US", { month: "short", day: "numeric" })} - {events.map((item, i) => )} + + + + TODAY + + + + {new Date().toLocaleDateString("en-US", { month: "short", day: "numeric" })} + + + {events.map((item, i) => ( + + ))} - - CHORES - {chores.map(item => {item.trim()})} + + + + CHORES + + + + + {chores.map((item) => ( + + + + {item.trim()} + + + ))} + + + + + + + DINNER PLAN + + + {dinner} + + - DINNER PLAN{dinner} - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Focus Countdown/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Focus Countdown/main.jsx index 5d1086d8..1c15adb1 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Focus Countdown/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Focus Countdown/main.jsx @@ -4,24 +4,37 @@ // // Focus Countdown (25-minute cycle) // +// Shows the time left in a 25-minute block, taken from the clock, with a gauge. +// Try changing cycleMinutes. +// const cycleMinutes = 25; const now = new Date(); +// Minutes into the current block. Blocks are counted from the start of each hour. const minutesInto = now.getMinutes() % cycleMinutes; const secondsInto = now.getSeconds(); +// Seconds passed and seconds left in the block, and the share that has passed (0 to 1). const elapsed = minutesInto * 60 + secondsInto; const total = cycleMinutes * 60; const remaining = total - elapsed; const progress = elapsed / total; +// The time left as "MM:SS", for example "04:09". const mm = Math.floor(remaining / 60); const ss = Math.floor(remaining % 60); const timeText = `${mm.toString().padStart(2, "0")}:${ss.toString().padStart(2, "0")}`; +// These numbers are worked out when the script runs. +// frame="max" makes the stack fill the whole widget. $render( - Focus Timer - {timeText} + + Focus Timer + + + {timeText} + + {/* draws an arc and fills it up to `value`, from 0 to 1. */} - Cycle: {cycleMinutes} min - + + Cycle: {cycleMinutes} min + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Gauge Battery/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Gauge Battery/main.jsx index 55a84284..61746814 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Gauge Battery/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Gauge Battery/main.jsx @@ -1,31 +1,40 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Battery Gauge -// +// +// Shows the battery charge on a round gauge. +// Try changing the colors of the sections, the angle or the thickness. +// $device.battery().level is the charge from 0 to 1. Make it a whole percentage; +// toFixed(0) rounds and returns text, such as "87". var percent = $device.battery().level * 100; percent = percent.toFixed(0); +// The colored parts of the gauge, in order. `value` is the share of the scale that a +// part covers, so the values add up to 1. let gaugeSections = [ - {color: "yellow", value: 0.1}, - {color: "blue", value: 0.2}, - {color: "orange", value: 0.3}, - {color: "green", value: 0.4}, + { color: "yellow", value: 0.1 }, + { color: "blue", value: 0.2 }, + { color: "orange", value: 0.3 }, + { color: "green", value: 0.4 }, ]; - +// $render draws the widget. frame="max" lets the stack fill the whole widget. +// `value` is the needle position from 0 to 1. `sections` takes JSON text, which +// $json(…) makes from the array. $render( - - - + > + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Profile/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Profile/main.jsx index a8f7d2b2..bdcb09e4 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Profile/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Profile/main.jsx @@ -1,46 +1,155 @@ // Real authenticated profile. Connect GitHub in Settings > Service Accounts, // then allow this installed widget. Web Studio supplies editable samples only. -const family = $getenv("widget-size"), accessory = family.startsWith("accessory"); -const dark = $device.isdarkmode(), compact = family === "small"; +// Shows your GitHub name and repository counts. Try changing the colors, or which +// numbers the layouts show. +// $services runs on iPhone, iPad and Mac, and on Android with a fine-grained token (no +// OAuth sign-in); not on Windows or Linux. widget.json must declare the permissions +// "services" and "network", and the host api.github.com. + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". +const family = $getenv("widget-size"), + accessory = family.startsWith("accessory"); +// $device.isdarkmode() is true when the system uses the dark appearance. +const dark = $device.isdarkmode(), + compact = family === "small"; +// Lock Screen sizes get a clear background and the system's own text colors. const background = accessory ? "clear" : dark ? "#192822" : "#f1f8f3"; const primary = accessory ? "primary" : dark ? "#e7f5eb" : "#224432"; const secondary = accessory ? "secondary" : dark ? "#a4bead" : "#60776a"; -let profile = null, state = "notConnected"; +// Read the data. When there is no profile, `state` says why. +let profile = null, + state = "notConnected"; try { + // status() only looks at the connection saved on this device; profile() asks GitHub. state = await $services.status("github"); if (state === "connected") profile = await $services.profile("github"); } catch (error) { + // A failed call throws an error whose text contains a code such as service_rate_limit. const message = String(error); - state = message.includes("service_rate_limit") ? "rateLimited" : message.includes("service_expired") || message.includes("service_credential") ? "expired" - : message.includes("service_permission") ? "notGranted" : message.includes("service_not_connected") ? "notConnected" : "offline"; + state = message.includes("service_rate_limit") + ? "rateLimited" + : message.includes("service_expired") || message.includes("service_credential") + ? "expired" + : message.includes("service_permission") + ? "notGranted" + : message.includes("service_not_connected") + ? "notConnected" + : "offline"; } +// What to show for each state: [title, explanation]. const messages = { notConnected: ["Connect GitHub", "Open Service Accounts in ScriptWidget Settings."], notGranted: ["Allow this widget", "Choose this widget in Service Accounts."], unavailable: ["Account unavailable", "Review Service Accounts in ScriptWidget."], expired: ["Reconnect GitHub", "Update your token in Service Accounts."], rateLimited: ["Try again later", "GitHub is rate limiting requests."], - offline: ["Unable to refresh", "Try again when your connection is available."] + offline: ["Unable to refresh", "Try again when your connection is available."], }; const notice = messages[state] || messages.offline; -const number = value => value === null ? "—" : String(value); -const Metric = ({label,value}) => {number(value)}{label}; +// A count that GitHub did not share is null; show a dash for it. +const number = (value) => (value === null ? "—" : String(value)); +// A reusable piece of layout, used below as : a number with a label under it. +const Metric = ({ label, value }) => ( + + + {number(value)} + + + {label} + + +); +// No profile: show the notice in a form that fits the size. if (!profile) { if (family === "accessoryInline") $render({notice[0]}); - else if (family === "accessoryCircular") $render({state === "notConnected" ? "Setup" : state === "notGranted" ? "Allow" : state === "expired" ? "Login" : state === "rateLimited" ? "Later" : "Retry"}); - else $render({notice[0]}{notice[1]}); + else if (family === "accessoryCircular") + $render( + + + + {state === "notConnected" + ? "Setup" + : state === "notGranted" + ? "Allow" + : state === "expired" + ? "Login" + : state === "rateLimited" + ? "Later" + : "Retry"} + + , + ); + else + $render( + + + {notice[0]} + + + {notice[1]} + + , + ); } else if (family === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({`@${profile.username} · ${profile.publicRepositories} repos`}); } else if (family === "accessoryCircular") { - $render({number(profile.publicRepositories)}repos); + // Lock Screen, circular: only the number of public repositories. + $render( + + {number(profile.publicRepositories)} + repos + , + ); } else if (family === "accessoryRectangular") { - $render({`@${profile.username}`}{`${profile.publicRepositories} repos · ${number(profile.followers)} followers`}); + // Lock Screen, rectangular: two short lines. + $render( + + {`@${profile.username}`} + {`${profile.publicRepositories} repos · ${number(profile.followers)} followers`} + , + ); } else { - $render( - {profile.displayName || profile.username}{`@${profile.username}`} - - {!compact && } - {!compact && {profile.privateRepositories === null ? "Private repository count not shared" : `${profile.privateRepositories} private repositories`}} - {family !== "medium" && !compact && } - ); + // Home Screen sizes. The small widget (`compact`) leaves out the third number and the + // last line. frame="max" fills the widget; padding is the space in points around the content. + $render( + + + + + + {profile.displayName || profile.username} + + {`@${profile.username}`} + + + + + + + {!compact && } + + {!compact && ( + + {profile.privateRepositories === null + ? "Private repository count not shared" + : `${profile.privateRepositories} private repositories`} + + )} + {family !== "medium" && !compact && } + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/lib/repository.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/lib/repository.js index d3ff3fcf..bfbb8f3e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/lib/repository.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/lib/repository.js @@ -1,104 +1,372 @@ +// Loads the public counts of one GitHub repository and keeps a copy in $storage, so the +// widget still has numbers when it is offline or when GitHub limits requests. +// main.jsx imports this file ("lib/repository.js") and uses `repositoryStats`. var repositoryStats = (() => { - const key="github.stats.v1",hour=3600000,day=24*hour; - const defaults={repository:"everettjf/ScriptWidget",accent:"blue"}; - const closed=(value,keys)=>value && typeof value==="object" && !Array.isArray(value) && Object.keys(value).sort().join(",")===keys.split(",").sort().join(","); - const count=value=>Number.isSafeInteger(value)&&value>=0&&value<=1000000000; + // The storage key of the saved copy, and two time spans in milliseconds. + const key = "github.stats.v1", + hour = 3600000, + day = 24 * hour; + const defaults = { repository: "everettjf/ScriptWidget", accent: "blue" }; + // True when `value` is a plain object with exactly the keys listed in `keys` ("a,b,c"). + const closed = (value, keys) => + value && + typeof value === "object" && + !Array.isArray(value) && + Object.keys(value).sort().join(",") === keys.split(",").sort().join(","); + // A whole number from 0 to one billion. + const count = (value) => Number.isSafeInteger(value) && value >= 0 && value <= 1000000000; + // True for "owner/name" written the way GitHub allows. function validRepository(value) { - if(typeof value!=="string"||value.length>140)return false; - const parts=value.split("/");return parts.length===2&&/^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(parts[0])&&/^[A-Za-z0-9_.-]{1,100}$/.test(parts[1])&&![".",".."].includes(parts[1]); + if (typeof value !== "string" || value.length > 140) return false; + const parts = value.split("/"); + return ( + parts.length === 2 && + /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/.test(parts[0]) && + /^[A-Za-z0-9_.-]{1,100}$/.test(parts[1]) && + ![".", ".."].includes(parts[1]) + ); } - function validate(value){if(!closed(value,"repository,accent")||!validRepository(value.repository)||!["blue","green","rose"].includes(value.accent))throw new Error("Choose a public owner/repository and an accent in Records & Configuration.");return value;} - function options(raw,parameter){ - let result={...defaults}; - if(raw!==null&&raw!==undefined&&raw!==""){ - if(typeof raw!=="string"||raw.length>4096)throw new Error("Invalid repository configuration."); - const saved=JSON.parse(raw);if(!closed(saved,"version,kind,values")||saved.version!==1||saved.kind!=="repoStats")throw new Error("Invalid repository configuration.");result={...validate(saved.values)}; + // Check the settings { repository, accent }, or throw a message the app can show. + function validate(value) { + if ( + !closed(value, "repository,accent") || + !validRepository(value.repository) || + !["blue", "green", "rose"].includes(value.accent) + ) + throw new Error("Choose a public owner/repository and an accent in Records & Configuration."); + return value; + } + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter. The parameter is owner/name, or JSON + // such as {"repository":"owner/name","accent":"green"}. + function options(raw, parameter) { + let result = { ...defaults }; + if (raw !== null && raw !== undefined && raw !== "") { + if (typeof raw !== "string" || raw.length > 4096) + throw new Error("Invalid repository configuration."); + const saved = JSON.parse(raw); + if ( + !closed(saved, "version,kind,values") || + saved.version !== 1 || + saved.kind !== "repoStats" + ) + throw new Error("Invalid repository configuration."); + result = { ...validate(saved.values) }; } - if(parameter){ - if(typeof parameter!=="string"||parameter.length>4096)throw new Error("Invalid repository parameter."); - if(parameter.trim().startsWith("{")){ - const override=JSON.parse(parameter);if(!override||typeof override!=="object"||Array.isArray(override)||Object.keys(override).some(key=>!Object.hasOwn(defaults,key)))throw new Error("Unknown repository setting.");result={...result,...override}; - }else result.repository=parameter.trim(); + if (parameter) { + if (typeof parameter !== "string" || parameter.length > 4096) + throw new Error("Invalid repository parameter."); + if (parameter.trim().startsWith("{")) { + const override = JSON.parse(parameter); + if ( + !override || + typeof override !== "object" || + Array.isArray(override) || + Object.keys(override).some((key) => !Object.hasOwn(defaults, key)) + ) + throw new Error("Unknown repository setting."); + result = { ...result, ...override }; + } else result.repository = parameter.trim(); } return validate(result); } - const validDate=value=>typeof value==="string"&&value.length<=128&&/^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value)&&Number.isFinite(Date.parse(value)); - const validValues=value=>closed(value,"stars,forks,issues")&&count(value.stars)&&count(value.forks)&&count(value.issues); - function packets(raw,now){ - try{ - if(typeof raw!=="string"||raw.length>32768)return []; - const data=JSON.parse(raw);if(!closed(data,"version,entries")||data.version!==1||!Array.isArray(data.entries)||data.entries.length>4)return []; - const seen=new Set(); - for(const entry of data.entries){ - if(!closed(entry,"repository,checkedAt,nextRequestAt,observedAt,lastModified,reason,values,history")||!validRepository(entry.repository)||entry.repository!==entry.repository.toLowerCase()||seen.has(entry.repository)|| - !Number.isSafeInteger(entry.checkedAt)||entry.checkedAt<0||entry.checkedAt>now+60000||!Number.isSafeInteger(entry.nextRequestAt)||entry.nextRequestAtentry.checkedAt+7*day|| - !Number.isSafeInteger(entry.observedAt)||entry.observedAt<0||entry.observedAt>entry.checkedAt||!["","offline","rate","missing","invalid"].includes(entry.reason)|| - (entry.lastModified!==""&&!validDate(entry.lastModified))||(entry.values!==null&&!validValues(entry.values))|| - (entry.values===null?entry.observedAt!==0:entry.observedAt===0)||!Array.isArray(entry.history)||entry.history.length>14|| - entry.history.some((point,index)=>!closed(point,"time,stars")||!count(point.stars)||!Number.isSafeInteger(point.time)||point.time<0||point.time>entry.observedAt||(index>0&&Math.floor(point.time/day)<=Math.floor(entry.history[index-1].time/day)))|| - (entry.values===null&&entry.history.length>0))return []; + // An HTTP date such as "Sun, 08 Mar 2026 12:00:00 GMT", as in the Last-Modified header. + const validDate = (value) => + typeof value === "string" && + value.length <= 128 && + /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(value) && + Number.isFinite(Date.parse(value)); + // The three counts and nothing else. + const validValues = (value) => + closed(value, "stars,forks,issues") && + count(value.stars) && + count(value.forks) && + count(value.issues); + // Read the saved copy: up to 4 repositories, each with its counts, when it was checked + // (`checkedAt`), when to ask again (`nextRequestAt`) and up to 14 daily star counts. + // Times are milliseconds since 1970. Anything unexpected gives an empty list, so a + // damaged copy is simply loaded again. + function packets(raw, now) { + try { + if (typeof raw !== "string" || raw.length > 32768) return []; + const data = JSON.parse(raw); + if ( + !closed(data, "version,entries") || + data.version !== 1 || + !Array.isArray(data.entries) || + data.entries.length > 4 + ) + return []; + const seen = new Set(); + for (const entry of data.entries) { + if ( + !closed( + entry, + "repository,checkedAt,nextRequestAt,observedAt,lastModified,reason,values,history", + ) || + !validRepository(entry.repository) || + entry.repository !== entry.repository.toLowerCase() || + seen.has(entry.repository) || + !Number.isSafeInteger(entry.checkedAt) || + entry.checkedAt < 0 || + entry.checkedAt > now + 60000 || + !Number.isSafeInteger(entry.nextRequestAt) || + entry.nextRequestAt < entry.checkedAt || + entry.nextRequestAt > entry.checkedAt + 7 * day || + !Number.isSafeInteger(entry.observedAt) || + entry.observedAt < 0 || + entry.observedAt > entry.checkedAt || + !["", "offline", "rate", "missing", "invalid"].includes(entry.reason) || + (entry.lastModified !== "" && !validDate(entry.lastModified)) || + (entry.values !== null && !validValues(entry.values)) || + (entry.values === null ? entry.observedAt !== 0 : entry.observedAt === 0) || + !Array.isArray(entry.history) || + entry.history.length > 14 || + entry.history.some( + (point, index) => + !closed(point, "time,stars") || + !count(point.stars) || + !Number.isSafeInteger(point.time) || + point.time < 0 || + point.time > entry.observedAt || + (index > 0 && + Math.floor(point.time / day) <= Math.floor(entry.history[index - 1].time / day)), + ) || + (entry.values === null && entry.history.length > 0) + ) + return []; seen.add(entry.repository); } return data.entries; - }catch{return [];} + } catch { + return []; + } } - function publish(packet,now){ - for(let attempt=0;attempt<4;attempt++){ - const raw=$storage.getString(key),entries=packets(raw,now),previous=entries.find(entry=>entry.repository===packet.repository); - if(previous&&(previous.checkedAt>packet.checkedAt))return true; + // Save one repository's entry next to the others. compareAndSetString writes only if the + // stored text is still `raw`; if something else saved in between, read again and retry. + function publish(packet, now) { + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(key), + entries = packets(raw, now), + previous = entries.find((entry) => entry.repository === packet.repository); + if (previous && previous.checkedAt > packet.checkedAt) return true; // Keep newer successful data if an older failed request completes at the same timestamp. - const candidate=previous?.values && previous.observedAt>packet.observedAt && packet.reason!=="missing" ? {...packet,values:previous.values,observedAt:previous.observedAt,lastModified:previous.lastModified,history:previous.history,nextRequestAt:Math.max(packet.nextRequestAt,previous.nextRequestAt)} : packet; - const history=[...(previous?.history||[]),...candidate.history].sort((a,b)=>a.time-b.time),daily=[]; - for(const point of history){if(daily.length&&Math.floor(daily[daily.length-1].time/day)===Math.floor(point.time/day))daily[daily.length-1]=point;else daily.push(point);} - const merged={...candidate,history:candidate.values===null?[]:daily.slice(-14)}; - const next=[merged,...entries.filter(entry=>entry.repository!==packet.repository)].sort((a,b)=>b.checkedAt-a.checkedAt).slice(0,4); - if($storage.compareAndSetString(key,raw,JSON.stringify({version:1,entries:next})))return true; + const candidate = + previous?.values && previous.observedAt > packet.observedAt && packet.reason !== "missing" + ? { + ...packet, + values: previous.values, + observedAt: previous.observedAt, + lastModified: previous.lastModified, + history: previous.history, + nextRequestAt: Math.max(packet.nextRequestAt, previous.nextRequestAt), + } + : packet; + const history = [...(previous?.history || []), ...candidate.history].sort( + (a, b) => a.time - b.time, + ), + daily = []; + // Keep one history point per day (UTC); a later point replaces an earlier one of that day. + for (const point of history) { + if ( + daily.length && + Math.floor(daily[daily.length - 1].time / day) === Math.floor(point.time / day) + ) + daily[daily.length - 1] = point; + else daily.push(point); + } + const merged = { ...candidate, history: candidate.values === null ? [] : daily.slice(-14) }; + // Newest first, and never more than 4 repositories. + const next = [merged, ...entries.filter((entry) => entry.repository !== packet.repository)] + .sort((a, b) => b.checkedAt - a.checkedAt) + .slice(0, 4); + if ($storage.compareAndSetString(key, raw, JSON.stringify({ version: 1, entries: next }))) + return true; } return false; } - function nextRequest(headers,now){ - const expiry=Date.parse(headers.expires||""),maxAge=/(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"]||""); - const until=maxAge?now+Number(maxAge[1])*1000:expiry; - return Math.round(Math.max(now+hour,Number.isFinite(until)&&until<=now+7*day?until:now+hour)); + // When to ask GitHub again after an answer: when the response says it expires + // (Cache-Control max-age, else Expires), but not sooner than one hour. A missing time, + // or one more than 7 days away, also gives one hour. + function nextRequest(headers, now) { + const expiry = Date.parse(headers.expires || ""), + maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"] || ""); + const until = maxAge ? now + Number(maxAge[1]) * 1000 : expiry; + return Math.round( + Math.max(now + hour, Number.isFinite(until) && until <= now + 7 * day ? until : now + hour), + ); } - function retry(headers,now){ - const raw=headers["retry-after"]||"",seconds=/^\d+$/.test(raw)?Number(raw):NaN; - const until=Number.isFinite(seconds)?now+seconds*1000:Date.parse(raw); - return Math.round(Number.isFinite(until)&&until>now&&until<=now+7*day?Math.max(now+hour,until):now+hour); + // When to ask again after a failure: at the Retry-After time (seconds or a date) if it + // is within 7 days, but not sooner than one hour; otherwise in one hour. + function retry(headers, now) { + const raw = headers["retry-after"] || "", + seconds = /^\d+$/.test(raw) ? Number(raw) : NaN; + const until = Number.isFinite(seconds) ? now + seconds * 1000 : Date.parse(raw); + return Math.round( + Number.isFinite(until) && until > now && until <= now + 7 * day + ? Math.max(now + hour, until) + : now + hour, + ); } - function values(body,repository){ - if(typeof body!=="string"||body.length>2097152)throw new Error("Invalid repository response"); - const data=JSON.parse(body); - if(!data||typeof data.full_name!=="string"||data.full_name.toLowerCase()!==repository||data.private!==false||!count(data.stargazers_count)||!count(data.forks_count)||!count(data.open_issues_count))throw new Error("Invalid public repository response"); - return {stars:data.stargazers_count,forks:data.forks_count,issues:data.open_issues_count}; + // Take the three counts out of GitHub's answer, after checking that it describes the + // public repository that was asked for. + function values(body, repository) { + if (typeof body !== "string" || body.length > 2097152) + throw new Error("Invalid repository response"); + const data = JSON.parse(body); + if ( + !data || + typeof data.full_name !== "string" || + data.full_name.toLowerCase() !== repository || + data.private !== false || + !count(data.stargazers_count) || + !count(data.forks_count) || + !count(data.open_issues_count) + ) + throw new Error("Invalid public repository response"); + return { + stars: data.stargazers_count, + forks: data.forks_count, + issues: data.open_issues_count, + }; } - async function load(config,now,projection){ - validate(config);const repository=config.repository.toLowerCase(); - let packet=packets($storage.getString(key),now).find(entry=>entry.repository===repository),saved=true,fromCache=!!packet; - if(!projection&&(!packet||now>=packet.nextRequestAt)){ - const previous=packet; - const headers={"Accept":"application/vnd.github+json","X-GitHub-Api-Version":"2022-11-28","User-Agent":"ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)"}; - if(packet?.lastModified)headers["If-Modified-Since"]=packet.lastModified; - let responseHeaders={},reason="offline",missing=false; - try{ - const response=await $http.getResponse(`https://api.github.com/repos/${repository.split("/").map(encodeURIComponent).join("/")}`,{headers}); - if(!response||!Number.isInteger(response.status))throw new Error("Invalid response"); - responseHeaders=response.headers||{}; - if(response.status===304&&packet?.values){packet={...packet,checkedAt:now,observedAt:now,nextRequestAt:nextRequest(responseHeaders,now),reason:""};} - else if(response.status===200){ - reason="invalid";const result=values(response.body,repository),history=[...(packet?.history||[])].filter(point=>Math.floor(point.time/day)!==Math.floor(now/day));history.push({time:now,stars:result.stars}); - packet={repository,checkedAt:now,observedAt:now,nextRequestAt:nextRequest(responseHeaders,now),lastModified:validDate(responseHeaders["last-modified"])&&Date.parse(responseHeaders["last-modified"])<=now+60000?responseHeaders["last-modified"]:"",reason:"",values:result,history:history.slice(-14)}; - }else{reason=response.status===403||response.status===429?"rate":response.status===404?"missing":"offline";missing=response.status===404;throw new Error("Service unavailable");} - fromCache=response.status===304; - }catch{ - packet={repository,checkedAt:now,nextRequestAt:retry(responseHeaders,now),observedAt:missing?0:previous?.observedAt||0,lastModified:missing?"":previous?.lastModified||"",reason,values:missing?null:previous?.values||null,history:missing?[]:previous?.history||[]}; + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which must not use the network. + async function load(config, now, projection) { + validate(config); + const repository = config.repository.toLowerCase(); + let packet = packets($storage.getString(key), now).find( + (entry) => entry.repository === repository, + ), + saved = true, + fromCache = !!packet; + // Ask GitHub only when there is no saved copy or it is due for a refresh. + if (!projection && (!packet || now >= packet.nextRequestAt)) { + const previous = packet; + const headers = { + Accept: "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)", + }; + // With If-Modified-Since, GitHub can answer 304 "not changed" instead of the counts. + if (packet?.lastModified) headers["If-Modified-Since"] = packet.lastModified; + let responseHeaders = {}, + reason = "offline", + missing = false; + try { + // $http.getResponse resolves to { status, body, headers }, also for statuses such as + // 404; it throws only when the request itself fails. + const response = await $http.getResponse( + `https://api.github.com/repos/${repository.split("/").map(encodeURIComponent).join("/")}`, + { headers }, + ); + if (!response || !Number.isInteger(response.status)) throw new Error("Invalid response"); + responseHeaders = response.headers || {}; + // 304: nothing changed, the saved counts are still right. + if (response.status === 304 && packet?.values) { + packet = { + ...packet, + checkedAt: now, + observedAt: now, + nextRequestAt: nextRequest(responseHeaders, now), + reason: "", + }; + } else if (response.status === 200) { + // 200: new counts. Add today's stars to the history, one point per day. + reason = "invalid"; + const result = values(response.body, repository), + history = [...(packet?.history || [])].filter( + (point) => Math.floor(point.time / day) !== Math.floor(now / day), + ); + history.push({ time: now, stars: result.stars }); + packet = { + repository, + checkedAt: now, + observedAt: now, + nextRequestAt: nextRequest(responseHeaders, now), + lastModified: + validDate(responseHeaders["last-modified"]) && + Date.parse(responseHeaders["last-modified"]) <= now + 60000 + ? responseHeaders["last-modified"] + : "", + reason: "", + values: result, + history: history.slice(-14), + }; + } else { + // 403 and 429 mean a rate limit, 404 an unknown or private repository. + reason = + response.status === 403 || response.status === 429 + ? "rate" + : response.status === 404 + ? "missing" + : "offline"; + missing = response.status === 404; + throw new Error("Service unavailable"); + } + fromCache = response.status === 304; + } catch { + // No usable answer: keep the earlier counts (unless the repository is gone) and note why. + packet = { + repository, + checkedAt: now, + nextRequestAt: retry(responseHeaders, now), + observedAt: missing ? 0 : previous?.observedAt || 0, + lastModified: missing ? "" : previous?.lastModified || "", + reason, + values: missing ? null : previous?.values || null, + history: missing ? [] : previous?.history || [], + }; } - saved=publish(packet,now); + saved = publish(packet, now); } - const message=packet?.reason==="rate"?"GitHub rate limit":packet?.reason==="missing"?"Repository unavailable":packet?.reason==="invalid"?"Invalid service response":"Refresh unavailable"; - if(!packet?.values||now-packet.observedAt>7*day)return {available:false,repository:config.repository,heading:projection?"Refresh in current entry":message,detail:packet?.reason==="missing"?"Check the public owner/repository. Private or deleted repositories cannot be read.":"Check your connection and try again later.",saved}; - const minutes=Math.max(0,Math.floor((now-packet.observedAt)/60000)),age=minutes<1?"Checked just now":minutes<60?`Checked ${minutes}m ago`:minutes<1440?`Checked ${Math.floor(minutes/60)}h ago`:`Checked ${Math.floor(minutes/1440)}d ago`; - return {available:true,repository:config.repository,...packet.values,history:packet.history,age,saved,status:!saved?"Cache unavailable":packet.reason?`Saved counts · ${message.toLowerCase()}`:projection||fromCache?"Saved counts":"GitHub · Public repository"}; + // A short text for the reason of the last failure. + const message = + packet?.reason === "rate" + ? "GitHub rate limit" + : packet?.reason === "missing" + ? "Repository unavailable" + : packet?.reason === "invalid" + ? "Invalid service response" + : "Refresh unavailable"; + // No counts, or counts older than 7 days: return a message to show instead. + if (!packet?.values || now - packet.observedAt > 7 * day) + return { + available: false, + repository: config.repository, + heading: projection ? "Refresh in current entry" : message, + detail: + packet?.reason === "missing" + ? "Check the public owner/repository. Private or deleted repositories cannot be read." + : "Check your connection and try again later.", + saved, + }; + // How long ago the counts were read, as text. + const minutes = Math.max(0, Math.floor((now - packet.observedAt) / 60000)), + age = + minutes < 1 + ? "Checked just now" + : minutes < 60 + ? `Checked ${minutes}m ago` + : minutes < 1440 + ? `Checked ${Math.floor(minutes / 60)}h ago` + : `Checked ${Math.floor(minutes / 1440)}d ago`; + // The counts, plus the texts for the last two lines of the widget. + return { + available: true, + repository: config.repository, + ...packet.values, + history: packet.history, + age, + saved, + status: !saved + ? "Cache unavailable" + : packet.reason + ? `Saved counts · ${message.toLowerCase()}` + : projection || fromCache + ? "Saved counts" + : "GitHub · Public repository", + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/main.jsx index 7006e494..ffc33438 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/GitHub Repo Stats/main.jsx @@ -1,25 +1,196 @@ // Public counts only. Configure owner/repository and accent in Records & Configuration. -if (!$import("lib/repository.js")) throw new Error("Install the complete GitHub Repo Stats template."); -const config=repositoryStats.options($storage.getString("recordTemplate.config.v1"),$getenv("widget-param")); -const stats=await repositoryStats.load(config,Date.now(),$getenv("timeline-is-projection")==="true"); -const size=$getenv("widget-size"),small=size==="small",dark=$device.isdarkmode(); -const nameLimit=small?24:40; -const displayRepository=stats.repository.length<=nameLimit?stats.repository:stats.repository.slice(0,Math.floor(nameLimit/2)-1)+"…"+stats.repository.slice(-Math.floor(nameLimit/2)); -const background=dark?"#111827":"#eff6ff",text=dark?"#f8fafc":"#1e3a8a",secondary=dark?"#cbd5e1":"#475569",accent={blue:"#2563eb",green:"#15803d",rose:"#be185d"}[config.accent]; -const NumberCard=({title,value,icon})=>{String(value)}{title}; -const Trend=()=>stats.history.length>=2?Stars · saved daily checks({label:new Date(point.time).toISOString().slice(0,10),value:point.stars})))}/>{`${stats.history.length} recorded days · ${new Date(stats.history[0].time).toISOString().slice(0,10)} onward`}:Daily star history appears after two recorded days.; -if(size==="accessoryInline"){ - $render({stats.available?`${displayRepository} · ${stats.stars} stars`:stats.heading}); -}else if(size==="accessoryCircular"){ - $render({stats.available?String(stats.stars):"—"}{stats.available?"stars":"Open app"}); -}else if(size==="accessoryRectangular"){ - $render({displayRepository}{stats.available?`${stats.stars} stars · ${stats.forks} forks`:stats.heading}{stats.available?stats.age:"Check public repository"}); -}else if(!stats.available){ - $render({stats.heading}{stats.detail}); -}else if(small){ - $render({displayRepository}{String(stats.stars)}{stats.age}{stats.status}); -}else if(size==="medium"){ - $render({displayRepository}{stats.age}{stats.status}); -}else{ - $render({displayRepository}{stats.age}{stats.status}); +// Shows the stars, forks and open issues of a public GitHub repository, and a star trend +// in the large size. Try another repository: write owner/name in the widget parameter. +// widget.json must declare the permission "network" with the host api.github.com, and +// "storage" for the saved copy of the counts. + +// $import runs another file of this package; lib/repository.js defines `repositoryStats`. +// It returns false when the file is missing. +if (!$import("lib/repository.js")) + throw new Error("Install the complete GitHub Repo Stats template."); +// The settings: defaults, then what the app saved in $storage, then the widget parameter +// ($getenv("widget-param"), a text you set on each widget you place). +const config = repositoryStats.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Read the counts: from GitHub when the saved copy is due for a refresh, else from $storage. +// "timeline-is-projection" is "true" when the script runs for a future timeline entry; +// no request is made then. +const stats = await repositoryStats.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +const size = $getenv("widget-size"), + small = size === "small", + dark = $device.isdarkmode(); +// A long owner/name gets its middle replaced by "…". +const nameLimit = small ? 24 : 40; +const displayRepository = + stats.repository.length <= nameLimit + ? stats.repository + : stats.repository.slice(0, Math.floor(nameLimit / 2) - 1) + + "…" + + stats.repository.slice(-Math.floor(nameLimit / 2)); +const background = dark ? "#111827" : "#eff6ff", + text = dark ? "#f8fafc" : "#1e3a8a", + secondary = dark ? "#cbd5e1" : "#475569", + accent = { blue: "#2563eb", green: "#15803d", rose: "#be185d" }[config.accent]; +// A reusable piece of layout: an icon, a number and a title under it. +const NumberCard = ({ title, value, icon }) => ( + + + + {String(value)} + + + {title} + + +); +// A line chart of the saved daily star counts; it needs two days of history. +// takes its points as JSON text: [{ label, value }, …]. +const Trend = () => + stats.history.length >= 2 ? ( + + + Stars · saved daily checks + + ({ + label: new Date(point.time).toISOString().slice(0, 10), + value: point.stars, + })), + )} + /> + {`${stats.history.length} recorded days · ${new Date(stats.history[0].time).toISOString().slice(0, 10)} onward`} + + ) : ( + + Daily star history appears after two recorded days. + + ); +// Choose a layout for the widget size. +if (size === "accessoryInline") { + // Lock Screen, inline: one line of text. + $render( + {stats.available ? `${displayRepository} · ${stats.stars} stars` : stats.heading}, + ); +} else if (size === "accessoryCircular") { + // Lock Screen, circular: the star count. + $render( + + + + {stats.available ? String(stats.stars) : "—"} + + {stats.available ? "stars" : "Open app"} + , + ); +} else if (size === "accessoryRectangular") { + // Lock Screen, rectangular: three short lines. + $render( + + + {displayRepository} + + + {stats.available ? `${stats.stars} stars · ${stats.forks} forks` : stats.heading} + + {stats.available ? stats.age : "Check public repository"} + , + ); +} else if (!stats.available) { + // No counts to show: say why (offline, rate limit, unknown repository). + $render( + + + + {stats.heading} + + + {stats.detail} + + , + ); +} else if (small) { + // Small widget: only the star count. + $render( + + + {displayRepository} + + + + + + {String(stats.stars)} + + + + {stats.age} + + + {stats.status} + + , + ); +} else if (size === "medium") { + // Medium widget: the three numbers in a row. + $render( + + + {displayRepository} + + + + + + + + + {stats.age} + + + + {stats.status} + + + , + ); +} else { + // Large and extra large widgets: the three numbers and the trend chart. + $render( + + + {displayRepository} + + + + + + + + + + + + {stats.age} + + + {stats.status} + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/main.jsx index 59076497..4ab69c1e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Heatmap/main.jsx @@ -7,44 +7,91 @@ // renaming a habit's display name preserves its stable id and history. // Keep up to ten years of local calendar dates per habit. No network required. // Duplicate copies have separate history; this is not iCloud sync. +// Shows a grid of the days on which each of three habits was done, like a GitHub +// contribution graph. Try changing the colors in `habits`, or the weeks and cell size +// passed to . +// $storage needs the permission "storage" in widget.json; the buttons need its "actions". -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// The habit names set in Records & Configuration, or the defaults Read, Run, Meditate. const savedNames = localRecords.configuration("habitHeatmap"); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); +// `action` names the function that a tap calls. `color` holds five shades from empty +// to full; a day is either done or not, so only the first and the last are used. const habits = [ - { id: "read", name: savedNames.readName, action: "checkInRead", color: ["#1B2A1E", "#0E4429", "#006D32", "#26A641", "#39D353"] }, - { id: "run", name: savedNames.runName, action: "checkInRun", color: ["#1E1B2A", "#2E2266", "#4434A5", "#6B5BE0", "#9D8CFF"] }, - { id: "meditate", name: savedNames.meditateName, action: "checkInMeditate", color: ["#2A1E1B", "#5C2A10", "#9A4A12", "#D9741C", "#FFA94D"] }, + { + id: "read", + name: savedNames.readName, + action: "checkInRead", + color: ["#1B2A1E", "#0E4429", "#006D32", "#26A641", "#39D353"], + }, + { + id: "run", + name: savedNames.runName, + action: "checkInRun", + color: ["#1E1B2A", "#2E2266", "#4434A5", "#6B5BE0", "#9D8CFF"], + }, + { + id: "meditate", + name: savedNames.meditateName, + action: "checkInMeditate", + color: ["#2A1E1B", "#5C2A10", "#9A4A12", "#D9741C", "#FFA94D"], + }, ]; -const dateKey = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; +// Day key in local time, for example "2026-03-08". +const dateKey = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; // Calendar arithmetic at noon handles DST without assuming 24-hour days. -const dayOffset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); +const dayOffset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); const today = dayOffset(new Date(), 0); const todayKey = dateKey(today); +// Days older than about ten years (3660 days) are dropped when saving. const oldestKey = dateKey(dayOffset(today, -3659)); +// Each habit's days are saved under its own key, as a JSON list of day keys. const storageKey = (habit) => `habitHeatmap.v1.${habit.id}`; +// Turn the saved text into a sorted list of day keys, or throw if it is not such a list. const parseDays = (raw) => { if (!raw) return []; let days; - try { days = JSON.parse(raw); } catch (error) { throw new Error("Habit history is unreadable. Restore it before checking in."); } - if (!Array.isArray(days) || days.length > 3660 || days.some((day) => { - if (typeof day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(day)) return true; - const parts = day.split("-").map(Number); - return dateKey(new Date(parts[0], parts[1] - 1, parts[2], 12)) !== day; - })) throw new Error("Invalid habit history. Restore it before checking in."); + try { + days = JSON.parse(raw); + } catch (error) { + throw new Error("Habit history is unreadable. Restore it before checking in."); + } + if ( + !Array.isArray(days) || + days.length > 3660 || + days.some((day) => { + if (typeof day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(day)) return true; + const parts = day.split("-").map(Number); + return dateKey(new Date(parts[0], parts[1] - 1, parts[2], 12)) !== day; + }) + ) + throw new Error("Invalid habit history. Restore it before checking in."); return Array.from(new Set(days)).sort(); }; +// $storage.getString returns "" when nothing was saved under the key. const readDays = (habit) => parseDays($storage.getString(storageKey(habit))); +// Mark today as done for one habit. This runs when a Check in button is tapped. function checkIn(habit) { // A conflict rereads and revalidates history rather than replacing another // process's new day. Rendering and rejected attempts never create records. for (let attempt = 0; attempt < 4; attempt++) { const raw = $storage.getString(storageKey(habit)); const days = parseDays(raw); - if (days.includes(todayKey)) { $render(Already checked in); return; } + if (days.includes(todayKey)) { + $render(Already checked in); + return; + } const updated = days.filter((day) => day >= oldestKey); updated.push(todayKey); updated.sort(); + // compareAndSetString writes only if the stored text is still `raw`. if (updated.length > 3660 || typeof $storage.compareAndSetString !== "function") break; if ($storage.compareAndSetString(storageKey(habit), raw, JSON.stringify(updated))) { $render(Checked in); @@ -53,19 +100,33 @@ function checkIn(habit) { } throw new Error("Could not save check-in. Storage may be busy; please try again."); } -function checkInRead() { return checkIn(habits[0]); } -function checkInRun() { return checkIn(habits[1]); } -function checkInMeditate() { return checkIn(habits[2]); } +// The functions named by the "actions" in widget.json, one per habit. +function checkInRead() { + return checkIn(habits[0]); +} +function checkInRun() { + return checkIn(habits[1]); +} +function checkInMeditate() { + return checkIn(habits[2]); +} +// Read the data: one list of days per habit. const records = habits.map(readDays); +// Days in a row that are done, ending today, or yesterday if today is not done yet. const streak = (days) => { const completed = new Set(days); let offset = completed.has(todayKey) ? 0 : -1; let count = 0; - while (count < 3660 && completed.has(dateKey(dayOffset(today, offset)))) { count++; offset--; } + while (count < 3660 && completed.has(dateKey(dayOffset(today, offset)))) { + count++; + offset--; + } return count; }; // Monday-first columns; future days in the current week stay blank. -const weekEnd = dayOffset(today, 6 - (today.getDay() + 6) % 7); +// getDay() is 0 on Sunday; (getDay() + 6) % 7 is 0 on Monday. weekEnd is this week's Sunday. +const weekEnd = dayOffset(today, 6 - ((today.getDay() + 6) % 7)); +// Per habit, 26 weeks of cells: 4 = done, 0 = not done, -1 = a day still to come. const logs = records.map((days) => { const completed = new Set(days); return Array.from({ length: 26 * 7 }, (_, index) => { @@ -74,6 +135,7 @@ const logs = records.map((days) => { }); }); +// Draws the last `weeks` weeks of a log: squares of `cell` points, `gap` points apart. const Grid = ({ log, colors, weeks, cell, gap }) => { const days = log.slice(-weeks * 7); // Columns are weeks, rows are weekdays, as in a contribution graph. @@ -81,90 +143,155 @@ const Grid = ({ log, colors, weeks, cell, gap }) => { {Array.from({ length: weeks }, (_, week) => ( - {days.slice(week * 7, week * 7 + 7).map((level) => )} + {days.slice(week * 7, week * 7 + 7).map((level) => ( + + ))} ))} ); }; +// The saved days of a habit. const daysFor = (habit) => records[habits.findIndex((item) => item.id === habit.id)]; const streakLabel = (habit) => { const count = streak(daysFor(habit)); return `${count} ${count === 1 ? "day" : "days"}`; }; +// The habit name on the left; the streak with a flame on the right. const Header = ({ habit, font }) => ( - {habit.name} + + {habit.name} + - {streakLabel(habit)} + + {streakLabel(habit)} + ); +// A label to tap. actionID names an action in widget.json, which names the function +// to call. Needs iOS 17 or macOS 14. const CheckIn = ({ habit }) => ( ); // The flame counts consecutive days and returns to 0 after a missed day; this // count is every recorded check-in and never goes down. -const Total = ({ habit }) => {`${daysFor(habit).length} total`}; +const Total = ({ habit }) => ( + {`${daysFor(habit).length} total`} +); +// Choose a layout for the widget size. A tap runs this script with the size "action". // App Intent calls the named function after evaluating this source. if (size === "action") { // Do not render a widget while handling a tap. } else if (size === "accessoryCircular") { - $render({streak(records[0])}); + // Lock Screen, circular: the streak of the first habit. + $render( + + + + {streak(records[0])} + + , + ); } else if (size === "accessoryRectangular") { + // Lock Screen, rectangular: the first habit as a gray grid of 20 weeks. $render( - {habits[0].name} · {streak(records[0])}-day streak - (level < 0 ? -1 : level > 0 ? 4 : 1))} colors={["#444444", "#666666", "#888888", "#AAAAAA", "#FFFFFF"]} weeks={20} cell={5} gap={1.5} /> - + + {habits[0].name} · {streak(records[0])}-day streak + + (level < 0 ? -1 : level > 0 ? 4 : 1))} + colors={["#444444", "#666666", "#888888", "#AAAAAA", "#FFFFFF"]} + weeks={20} + cell={5} + gap={1.5} + /> + , ); } else if (size === "accessoryInline") { - $render({habits[0].name} · {streak(records[0])}-day streak); + // Lock Screen, inline: one line of text. + $render( + + {habits[0].name} · {streak(records[0])}-day streak + , + ); } else if (size === "small") { + // Small widget: the first habit, 8 weeks. $render(
- - + + + + + + , ); } else if (size === "medium") { + // Medium widget: the first habit, 22 weeks. $render(
- - + + + + + + , ); } else if (size === "extraLarge") { + // Extra large widget: the three habits side by side. $render( {habits.map((habit, index) => (
- + + + + + ))} - + , ); } else { + // Large widget: the three habits one below the other, 26 weeks each. $render( {habits.map((habit, index) => ( -
+ +
+ + + ))} - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/main.jsx index 06171965..ff75485a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Habit Streak Tracker/main.jsx @@ -1,40 +1,143 @@ // Explicit check-ins only. Optional widget-param: your habit name (up to 40 characters). // The earlier template recorded automatically on refresh. Its original keys stay // untouched; they are not reliable evidence of completed days and are never imported. -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); -const size = $getenv("widget-size"), title = ($getenv("widget-param") || localRecords.configuration("habitStreak").title).trim(); +// Shows how many days in a row you checked in, with Check in, Undo and Reset buttons. +// Try changing the colors below, or the habit name in Records & Configuration. +// $storage needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. +const size = $getenv("widget-size"), + title = ($getenv("widget-param") || localRecords.configuration("habitStreak").title).trim(); if (!title || title.length > 40) throw new Error("Use a habit name of 1–40 characters."); +// One record per day under the key "habitStreak.v2": 1 means done; no record reads as 0. const log = localRecords.create("habitStreak.v2", (value) => value === 1, 0); -function checkIn() { const changed = log.edit(() => 1); $render({changed ? "Checked in" : "Already checked in"}); } -function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); } -function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); } -const state = log.read(), done = log.value(state) === 1; +// The three functions below are named by the "actions" in widget.json. A tap on a +// {size !== "small" && } - {!["small", "medium"].includes(size) && Last 7 days{log.recent(state).map((day) => {day.date.slice(5)}{day.recorded ? "✓" : "—"})}} - {hasLegacy && {size === "small" ? "Earlier counter kept" : legacyLabel}} - ); + // Home Screen sizes. frame="max" fills the widget; padding is the space in points + // around the content. + $render( + + + + + {title} + + + + {streakLabel} + + + + + {/* The small widget has no room for a third button. */} + {size !== "small" && ( + + )} + + {/* Large sizes: the last 7 days, oldest first. day.date.slice(5) is the MM-DD part. */} + {!["small", "medium"].includes(size) && ( + + + Last 7 days + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? "✓" : "—"} + + + ))} + + )} + {/* Shown only when the earlier version left a counter behind. */} + {hasLegacy && ( + + {size === "small" ? "Earlier counter kept" : legacyLabel} + + )} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Overview/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Overview/main.jsx index 8c8f10f2..04873628 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Overview/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Overview/main.jsx @@ -1,56 +1,410 @@ // Real read-only HealthKit summaries. Declare health; review access in app Settings. // Parameter: overview (default), sleep, activity or workouts. Nothing is saved. // Web Studio supplies editable samples; native widgets never seed Health data. -const family = $getenv("widget-size"), small = family === "small"; -const accessory = family.startsWith("accessory"), dark = $device.isdarkmode(); +// Shows the sleep of the last 24 hours, today's activity rings and recent workouts. +// Try the widget parameter (sleep, activity or workouts), or change `colors`. +// $health runs on iPhone and iPad, and on Android through Health Connect (no ring goals +// or stand time); not on Mac, Windows or Linux. +// widget.json must declare the permission "health". + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". +const family = $getenv("widget-size"), + small = family === "small"; +const accessory = family.startsWith("accessory"), + dark = $device.isdarkmode(); +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const mode = $getenv("widget-param").trim() || "overview"; +// Lock Screen sizes get a clear background and the system's own text colors. const background = accessory ? "clear" : dark ? "#17242b" : "#f2f8f8"; const foreground = accessory ? "primary" : dark ? "#eaf4f4" : "#23444b"; const secondary = accessory ? "secondary" : dark ? "#a6bec4" : "#58737c"; +// The ring colors: move, exercise, stand. const colors = ["#e67f92", "#70b58b", "#6aadd3"]; -let sleep = null, activity = null, workouts = null, errors = 0; +// Read the data. A part stays null when it is not asked for or cannot be read. +let sleep = null, + activity = null, + workouts = null, + errors = 0; +// isAvailable() is false on a system without Health data; the calls below would fail there. const supported = $health.isAvailable(); -if (!["overview", "sleep", "activity", "workouts"].includes(mode)) throw new Error("Use overview, sleep, activity or workouts as the widget parameter."); +if (!["overview", "sleep", "activity", "workouts"].includes(mode)) + throw new Error("Use overview, sleep, activity or workouts as the widget parameter."); if (supported) { - if (mode === "overview" || mode === "sleep") { try { sleep = await $health.sleepSummary(); } catch { errors++; } } - if (mode === "overview" || mode === "activity") { try { activity = await $health.activitySummary(); } catch { errors++; } } - if (mode === "overview" || mode === "workouts") { try { workouts = await $health.workouts(); } catch { errors++; } } + // `await` waits for the answer. A failed read is counted and the rest still shows. + if (mode === "overview" || mode === "sleep") { + try { + sleep = await $health.sleepSummary(); + } catch { + errors++; + } + } + if (mode === "overview" || mode === "activity") { + try { + activity = await $health.activitySummary(); + } catch { + errors++; + } + } + if (mode === "overview" || mode === "workouts") { + try { + workouts = await $health.workouts(); + } catch { + errors++; + } + } } -function duration(seconds) { const minutes = Math.round(seconds/60); return `${Math.floor(minutes/60)}h ${String(minutes%60).padStart(2,"0")}m`; } +// Seconds as text: 27000 becomes "7h 30m". +function duration(seconds) { + const minutes = Math.round(seconds / 60); + return `${Math.floor(minutes / 60)}h ${String(minutes % 60).padStart(2, "0")}m`; +} +// The text for each value, or a dash. hasSamples is false when Health returned nothing, +// which can also mean that the data was not shared with ScriptWidget. const sleeping = sleep?.hasSamples && sleep.totalSleepSeconds > 0; const sleepValue = sleeping ? duration(sleep.totalSleepSeconds) : "—"; const move = activity?.hasSamples ? activity.move : null; const moveValue = move ? `${Math.round(move.value)} ${move.unit}` : "—"; const recent = workouts?.items?.[0]; const workoutValue = workouts?.hasSamples ? String(workouts.items.length) : "—"; -const title = mode === "sleep" ? "Sleep summary" : mode === "activity" ? "Activity today" : mode === "workouts" ? "Recent workouts" : "Health overview"; -const rings = activity?.hasSamples ? [activity.move,activity.exercise,activity.stand] : []; -const progress = index => rings[index]?.goal > 0 ? Math.min(1,Math.max(0,rings[index].value/rings[index].goal)) : 0; -const Rings = ({side}) => ; -const Metric = ({label,value}) => {label}{value}; +const title = + mode === "sleep" + ? "Sleep summary" + : mode === "activity" + ? "Activity today" + : mode === "workouts" + ? "Recent workouts" + : "Health overview"; +// The three activity rings. progress(index) is value / goal, kept between 0 and 1. +const rings = activity?.hasSamples ? [activity.move, activity.exercise, activity.stand] : []; +const progress = (index) => + rings[index]?.goal > 0 ? Math.min(1, Math.max(0, rings[index].value / rings[index].goal)) : 0; +// Three rings inside each other; `side` is the outer size in points. +// puts its children on top of each other. +const Rings = ({ side }) => ( + + + + + +); +// A reusable piece of layout: a small label with its value under it. +const Metric = ({ label, value }) => ( + + + {label} + + + {value} + + +); +// Nothing to show: there is no Health data on this system, or nothing could be read. if (!supported || (!sleep && !activity && !workouts)) { const message = !supported ? "Use a Health-capable device." : "Review access in app Settings."; - $render(accessory ? Health · Open app : Health setup{small ? (!supported ? "Health unavailable\non this device." : "Review Health in\napp Settings.") : message}{small ? "Read-only" : "Read-only · Apple Health"}); + $render( + accessory ? ( + Health · Open app + ) : ( + + + + Health setup + + + {small + ? !supported + ? "Health unavailable\non this device." + : "Review Health in\napp Settings." + : message} + + + + {small ? "Read-only" : "Read-only · Apple Health"} + + + ), + ); } else if (family === "accessoryInline") { - $render({mode === "activity" ? `Move ${moveValue}` : mode === "workouts" ? `${workoutValue} workouts · 7d` : `Sleep ${sleepValue}`}); + // Lock Screen, inline: one line of text. + $render( + + {mode === "activity" + ? `Move ${moveValue}` + : mode === "workouts" + ? `${workoutValue} workouts · 7d` + : `Sleep ${sleepValue}`} + , + ); } else if (family === "accessoryCircular") { - $render({mode === "activity" ? moveValue : mode === "workouts" ? workoutValue : sleeping ? `${(sleep.totalSleepSeconds/3600).toFixed(1)}h` : "—"}); + // Lock Screen, circular: an icon and one value. + $render( + + + + {mode === "activity" + ? moveValue + : mode === "workouts" + ? workoutValue + : sleeping + ? `${(sleep.totalSleepSeconds / 3600).toFixed(1)}h` + : "—"} + + , + ); } else if (accessory) { - $render({title}{mode === "activity" ? moveValue : mode === "workouts" ? `${workoutValue} · last 7d` : sleepValue}); + // Lock Screen, rectangular: a title and one value. + $render( + + {title} + + {mode === "activity" + ? moveValue + : mode === "workouts" + ? `${workoutValue} · last 7d` + : sleepValue} + + , + ); } else if (mode === "sleep" && family === "medium") { - $render(SLEEP · LAST 24H{sleepValue}{sleep?.truncated ? "Partial window" : sleep?.conflictSeconds > 0 ? "Stage overlap" : sleeping ? "Known sleep intervals" : "No shared stages"}{["core","deep","rem"].map(stage=>)}); + // Sleep, medium widget: the total on the left, the sleep stages on the right. + $render( + + + + SLEEP · LAST 24H + + + {sleepValue} + + + {sleep?.truncated + ? "Partial window" + : sleep?.conflictSeconds > 0 + ? "Stage overlap" + : sleeping + ? "Known sleep intervals" + : "No shared stages"} + + + + + {["core", "deep", "rem"].map((stage) => ( + + ))} + + , + ); } else if (mode === "sleep") { - $render(SLEEP · LAST 24H{sleepValue}{sleep?.truncated ? "Partial sample window" : sleep?.conflictSeconds > 0 ? "Stage overlap" : sleeping ? "Known sleep intervals" : "No shared sleep stages"}{!small && sleeping && {["core","deep","rem"].map(stage=>)}}{small ? "Read-only" : "Apple Health · Read-only"}); + // Sleep, other sizes. + $render( + + + SLEEP · LAST 24H + + + + {sleepValue} + + + {sleep?.truncated + ? "Partial sample window" + : sleep?.conflictSeconds > 0 + ? "Stage overlap" + : sleeping + ? "Known sleep intervals" + : "No shared sleep stages"} + + {/* Larger sizes also list the stages. Each one is a number of seconds. */} + {!small && sleeping && ( + + {["core", "deep", "rem"].map((stage) => ( + + ))} + + )} + + + {small ? "Read-only" : "Apple Health · Read-only"} + + , + ); } else if (mode === "activity" && family === "medium") { - $render(ACTIVITY · TODAY{moveValue}{activity?.hasSamples ? `Exercise ${Math.round(activity.exercise.value)} min` : "No shared activity"}{activity?.hasSamples ? `Stand ${Math.round(activity.stand.value)} hrs` : "Goals unavailable"}); + // Activity, medium widget: the rings on the left, the numbers on the right. + $render( + + + + + ACTIVITY · TODAY + + + {moveValue} + + + {activity?.hasSamples + ? `Exercise ${Math.round(activity.exercise.value)} min` + : "No shared activity"} + + + {activity?.hasSamples + ? `Stand ${Math.round(activity.stand.value)} hrs` + : "Goals unavailable"} + + + + , + ); } else if (mode === "activity") { - $render(ACTIVITY · TODAY{moveValue}{!small && }); + // Activity, other sizes. + $render( + + + ACTIVITY · TODAY + + + + {moveValue} + + {!small && ( + + + + + )} + , + ); } else if (mode === "workouts") { - $render(WORKOUTS · LAST 7D{recent ? recent.activity : "—"}{recent ? `${Math.round(recent.duration/60)} min` : "None shared"}{!small && recent && {[recent.distanceMeters === null ? null : `${(recent.distanceMeters/1000).toFixed(1)} km`,recent.energyKcal === null ? null : `${Math.round(recent.energyKcal)} kcal`].filter(Boolean).join(" · ")}}{workouts?.truncated ? (small ? "More available" : "More results not shown") : small ? "Read-only" : "Apple Health · Read-only"}); + // Workouts: the first one in the list. Its duration is in seconds. + $render( + + + WORKOUTS · LAST 7D + + + + {recent ? recent.activity : "—"} + + + {recent ? `${Math.round(recent.duration / 60)} min` : "None shared"} + + {/* Distance and energy are null when a workout has none; filter(Boolean) drops them. */} + {!small && recent && ( + + {[ + recent.distanceMeters === null + ? null + : `${(recent.distanceMeters / 1000).toFixed(1)} km`, + recent.energyKcal === null ? null : `${Math.round(recent.energyKcal)} kcal`, + ] + .filter(Boolean) + .join(" · ")} + + )} + + + {workouts?.truncated + ? small + ? "More available" + : "More results not shown" + : small + ? "Read-only" + : "Apple Health · Read-only"} + + , + ); } else if (small) { - $render(HEALTH SNAPSHOT{sleepValue}Sleep · last 24h{move ? `Move ${moveValue}` : "No shared activity"}{errors ? "Some data unavailable" : "Apple Health"}); + // Overview, small widget: sleep and move only. + $render( + + + HEALTH SNAPSHOT + + + + {sleepValue} + + + Sleep · last 24h + + + + {move ? `Move ${moveValue}` : "No shared activity"} + + + {errors ? "Some data unavailable" : "Apple Health"} + + , + ); } else if (family === "medium") { - $render(HEALTH SNAPSHOT); + // Overview, medium widget: the rings and three values. + $render( + + + HEALTH SNAPSHOT + + + + + + + + + + + , + ); } else { - $render(Health overview{recent ? `${recent.activity} · ${Math.round(recent.duration/60)} min` : "No shared workouts in 7d"}{errors ? "Some data unavailable" : "Apple Health · Read-only"}); + // Overview, large and extra large widgets. + $render( + + + Health overview + + + + + + + + {recent + ? `${recent.activity} · ${Math.round(recent.duration / 60)} min` + : "No shared workouts in 7d"} + + + + {errors ? "Some data unavailable" : "Apple Health · Read-only"} + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/lib/health.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/lib/health.js index 1e6ae9dd..eb0074c9 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/lib/health.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/lib/health.js @@ -1,60 +1,173 @@ // Query only the selected metric. Never persist HealthKit readings or authorization. +// main.jsx imports this file ("lib/health.js") and then uses `healthCard`. var healthCard = (() => { - const defaults = {metric:"steps",stepsGoal:8000,energyGoal:500}; + // metric is "steps", "energy" or "heart". The goals are steps and kcal per day. + const defaults = { metric: "steps", stepsGoal: 8000, energyGoal: 500 }; + // Check the settings, or throw a message the app can show. function validate(value) { - if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "energyGoal,metric,stepsGoal" || - !["steps","energy","heart"].includes(value.metric) || !Number.isInteger(value.stepsGoal) || value.stepsGoal < 1 || value.stepsGoal > 100000 || - !Number.isInteger(value.energyGoal) || value.energyGoal < 1 || value.energyGoal > 10000) throw new Error("Choose a metric and valid goals in Records & Configuration."); + if ( + !value || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).sort().join(",") !== "energyGoal,metric,stepsGoal" || + !["steps", "energy", "heart"].includes(value.metric) || + !Number.isInteger(value.stepsGoal) || + value.stepsGoal < 1 || + value.stepsGoal > 100000 || + !Number.isInteger(value.energyGoal) || + value.energyGoal < 1 || + value.energyGoal > 10000 + ) + throw new Error("Choose a metric and valid goals in Records & Configuration."); return value; } - function options(raw,parameter) { - let result = {...defaults}; + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter, which is JSON such as + // {"metric":"heart"}. + function options(raw, parameter) { + let result = { ...defaults }; if (raw !== null && raw !== undefined && raw !== "") { - if (typeof raw !== "string" || raw.length > 4096) throw new Error("Invalid saved health configuration."); + if (typeof raw !== "string" || raw.length > 4096) + throw new Error("Invalid saved health configuration."); const saved = JSON.parse(raw); - if (!saved || Object.keys(saved).sort().join(",") !== "kind,values,version" || saved.kind !== "healthCard" || saved.version !== 1) throw new Error("Invalid saved health configuration."); - result = {...validate(saved.values)}; + if ( + !saved || + Object.keys(saved).sort().join(",") !== "kind,values,version" || + saved.kind !== "healthCard" || + saved.version !== 1 + ) + throw new Error("Invalid saved health configuration."); + result = { ...validate(saved.values) }; } if (parameter) { - if (typeof parameter !== "string" || parameter.length > 4096) throw new Error("Invalid health parameter."); + if (typeof parameter !== "string" || parameter.length > 4096) + throw new Error("Invalid health parameter."); const overrides = JSON.parse(parameter); - if (!overrides || typeof overrides !== "object" || Array.isArray(overrides) || Object.keys(overrides).some(key => !Object.hasOwn(defaults,key))) throw new Error("Unknown health setting."); - result = {...result,...overrides}; + if ( + !overrides || + typeof overrides !== "object" || + Array.isArray(overrides) || + Object.keys(overrides).some((key) => !Object.hasOwn(defaults, key)) + ) + throw new Error("Unknown health setting."); + result = { ...result, ...overrides }; } return validate(result); } - async function load(config,now,projection) { + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which gets no reading. + async function load(config, now, projection) { validate(config); const metric = config.metric; - const title = metric === "steps" ? "Steps today" : metric === "energy" ? "Active energy" : "Latest heart rate"; - const icon = metric === "steps" ? "figure.walk" : metric === "energy" ? "flame.fill" : "heart.fill"; + // Title, icon and color of the chosen metric. + const title = + metric === "steps" + ? "Steps today" + : metric === "energy" + ? "Active energy" + : "Latest heart rate"; + const icon = + metric === "steps" ? "figure.walk" : metric === "energy" ? "flame.fill" : "heart.fill"; const color = metric === "steps" ? "#2563eb" : metric === "energy" ? "#c2410c" : "#be185d"; - const empty = (heading,detail) => ({available:false,title,icon,color,heading,detail}); - if (projection) return empty("Refresh in current entry","Health readings are queried only for the current entry."); - if (!$health.isAvailable()) return empty("Health on iPhone","Install on iPhone and enable Health in ScriptWidget Settings."); + // The result when there is no number: a heading and one line of explanation. + const empty = (heading, detail) => ({ available: false, title, icon, color, heading, detail }); + if (projection) + return empty( + "Refresh in current entry", + "Health readings are queried only for the current entry.", + ); + // isAvailable() is false on a system without Health data. + if (!$health.isAvailable()) + return empty( + "Health on iPhone", + "Install on iPhone and enable Health in ScriptWidget Settings.", + ); + // Health does not tell an app whether reading was allowed, so this only stops when + // Health is not available or not set up. const authorization = $health.authorizationStatus(); - if (["unavailable","undeclared","denied","notDetermined"].includes(authorization)) return empty("Connect Health","Enable Health in ScriptWidget Settings on iPhone."); + if (["unavailable", "undeclared", "denied", "notDetermined"].includes(authorization)) + return empty("Connect Health", "Enable Health in ScriptWidget Settings on iPhone."); let reading; - try { reading = await (metric === "steps" ? $health.stepCountToday() : metric === "energy" ? $health.activeEnergyToday() : $health.heartRateLatest()); } - catch { return empty("Health unavailable","Open ScriptWidget to check access; locked devices may delay readings."); } - if (!reading || typeof reading !== "object" || reading.hasSamples === false || (reading.hasSamples !== true && reading.value === 0)) - return empty("No readable data","Check Health access and recorded samples. Read permission is not disclosed."); - if (reading.hasSamples !== undefined && typeof reading.hasSamples !== "boolean") return empty("Reading unavailable","Invalid sample metadata. Refresh later."); + // Ask Health for the chosen metric only. `await` waits for the answer. + try { + reading = await (metric === "steps" + ? $health.stepCountToday() + : metric === "energy" + ? $health.activeEnergyToday() + : $health.heartRateLatest()); + } catch { + return empty( + "Health unavailable", + "Open ScriptWidget to check access; locked devices may delay readings.", + ); + } + // No samples. A value of 0 without the hasSamples flag is treated the same way. + if ( + !reading || + typeof reading !== "object" || + reading.hasSamples === false || + (reading.hasSamples !== true && reading.value === 0) + ) + return empty( + "No readable data", + "Check Health access and recorded samples. Read permission is not disclosed.", + ); + if (reading.hasSamples !== undefined && typeof reading.hasSamples !== "boolean") + return empty("Reading unavailable", "Invalid sample metadata. Refresh later."); + // Accept the reading only with the expected unit, a believable value and a recent end: + // within 15 minutes for today's totals, 24 hours for the heart rate. const unit = metric === "steps" ? "count" : metric === "energy" ? "kcal" : "bpm"; - const start = Date.parse(reading.start),end = Date.parse(reading.end),limit = metric === "heart" ? 24*3600000 : 15*60000; - if (reading.unit !== unit || typeof reading.value !== "number" || !Number.isFinite(reading.value) || reading.value < (metric === "heart" ? 1 : 0) || - reading.value > (metric === "steps" ? 1000000 : metric === "energy" ? 100000 : 300) || - !Number.isFinite(start) || !Number.isFinite(end) || start > end || end > now+60000 || now-end > limit) - return empty("Reading unavailable","No recent valid sample. Open Health and refresh later."); + const start = Date.parse(reading.start), + end = Date.parse(reading.end), + limit = metric === "heart" ? 24 * 3600000 : 15 * 60000; + if ( + reading.unit !== unit || + typeof reading.value !== "number" || + !Number.isFinite(reading.value) || + reading.value < (metric === "heart" ? 1 : 0) || + reading.value > (metric === "steps" ? 1000000 : metric === "energy" ? 100000 : 300) || + !Number.isFinite(start) || + !Number.isFinite(end) || + start > end || + end > now + 60000 || + now - end > limit + ) + return empty("Reading unavailable", "No recent valid sample. Open Health and refresh later."); + // A total that began on another day is not today's total. if (metric !== "heart") { - const today = new Date(now),begin = new Date(start); today.setHours(0,0,0,0);begin.setHours(0,0,0,0); - if (today.getTime() !== begin.getTime()) return empty("Refresh for today","Yesterday’s total is not shown as today’s activity."); + const today = new Date(now), + begin = new Date(start); + today.setHours(0, 0, 0, 0); + begin.setHours(0, 0, 0, 0); + if (today.getTime() !== begin.getTime()) + return empty("Refresh for today", "Yesterday’s total is not shown as today’s activity."); } - const goal = metric === "steps" ? config.stepsGoal : metric === "energy" ? config.energyGoal : null; - const minutes = Math.max(0,Math.floor((now-end)/60000)); - return {available:true,title,icon,color,value:Math.round(reading.value),unit:metric === "steps" ? "steps" : unit, - goal,progress:goal === null ? null : Math.min(1,reading.value/goal),age:minutes < 1 ? "Updated just now" : minutes < 60 ? `Updated ${minutes}m ago` : `Sample ${Math.floor(minutes/60)}h ago`, - detail:metric === "heart" ? "Latest sample · not live" : `Goal ${goal} ${metric === "steps" ? "steps" : "kcal"}`}; + // Heart rate has no goal. + const goal = + metric === "steps" ? config.stepsGoal : metric === "energy" ? config.energyGoal : null; + // Whole minutes since the end of the reading. + const minutes = Math.max(0, Math.floor((now - end) / 60000)); + // The result for main.jsx. `progress` is value / goal, at most 1. + return { + available: true, + title, + icon, + color, + value: Math.round(reading.value), + unit: metric === "steps" ? "steps" : unit, + goal, + progress: goal === null ? null : Math.min(1, reading.value / goal), + age: + minutes < 1 + ? "Updated just now" + : minutes < 60 + ? `Updated ${minutes}m ago` + : `Sample ${Math.floor(minutes / 60)}h ago`, + detail: + metric === "heart" + ? "Latest sample · not live" + : `Goal ${goal} ${metric === "steps" ? "steps" : "kcal"}`, + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/main.jsx index cd5d2674..7f58667a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Health Steps Ring/main.jsx @@ -1,23 +1,182 @@ // Read-only HealthKit card. Configure goals in Records & Configuration. // Empty results never prove that read permission was granted or denied. +// Shows one Health number (steps, active energy or heart rate) and a ring for its goal. +// Try another metric or goal in Records & Configuration, or with a widget parameter such +// as {"metric":"energy","energyGoal":400}. +// The Health API runs on iPhone and iPad, and on Android through Health Connect (no ring goals +// or stand time); not on Mac, Windows or Linux. +// widget.json must declare the permissions "health", and "storage" for the saved settings. + +// $import runs another file of this package; lib/health.js defines `healthCard`. +// It returns false when the file is missing. if (!$import("lib/health.js")) throw new Error("Install the complete Health Steps Ring template."); -const config = healthCard.options($storage.getString("recordTemplate.config.v1"),$getenv("widget-param")); -const health = await healthCard.load(config,Date.now(),$getenv("timeline-is-projection") === "true"); -const size = $getenv("widget-size"),small = size === "small"; -const dark = $device.isdarkmode(),background = dark ? "#111827" : "#eff6ff",text = dark ? "#f8fafc" : "#1e3a8a",secondary = dark ? "#cbd5e1" : "#475569"; -const Ring = ({side}) => ; +// The settings: defaults, then what the app saved in $storage, then the widget parameter +// ($getenv("widget-param"), a text you set on each widget you place). +const config = healthCard.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Read the number. "timeline-is-projection" is "true" when the script runs for a future +// timeline entry; Health is not asked then. +const health = await healthCard.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +const size = $getenv("widget-size"), + small = size === "small"; +const dark = $device.isdarkmode(), + background = dark ? "#111827" : "#eff6ff", + text = dark ? "#f8fafc" : "#1e3a8a", + secondary = dark ? "#cbd5e1" : "#475569"; +// A progress ring with the icon of the metric in the middle. `value` goes from 0 to 1. +// puts its children on top of each other. +const Ring = ({ side }) => ( + + + + +); +// Choose a layout for the widget size. if (size === "accessoryInline") { - $render({health.available ? `${health.title}: ${health.value} ${health.unit}` : health.heading}); + // Lock Screen, inline: one line of text. + $render( + + {health.available ? `${health.title}: ${health.value} ${health.unit}` : health.heading} + , + ); } else if (size === "accessoryCircular") { - $render({health.available ? String(health.value) : "—"}{health.available ? health.unit : "Open app"}); + // Lock Screen, circular: an icon, the number and its unit. + $render( + + + + {health.available ? String(health.value) : "—"} + + {health.available ? health.unit : "Open app"} + , + ); } else if (size === "accessoryRectangular") { - $render({health.title}{health.available ? `${health.value} ${health.unit}` : health.heading}{health.available ? health.age : "Open ScriptWidget"}); + // Lock Screen, rectangular: three short lines. + $render( + + + {health.title} + + + {health.available ? `${health.value} ${health.unit}` : health.heading} + + {health.available ? health.age : "Open ScriptWidget"} + , + ); } else if (!health.available) { - $render({health.heading}{health.detail}); + // No number to show: say why. + $render( + + + + {health.heading} + + + {health.detail} + + , + ); } else if (small) { - $render({health.title}{String(health.value)}{health.unit}{health.detail}{health.age}); + // Small widget: the number, without a ring. + $render( + + + + + {health.title} + + + + + + {String(health.value)} + + + {health.unit} + + + + {health.detail} + + + {health.age} + + , + ); } else if (size === "medium") { - $render({health.goal === null ? : }{health.title}{String(health.value)}{health.unit}{health.detail}{health.age}); + // Medium widget: the ring on the left. Heart rate has no goal, so it gets an icon. + $render( + + {health.goal === null ? ( + + ) : ( + + )} + + + {health.title} + + + + {String(health.value)} + + + {health.unit} + + + + {health.detail} + + + {health.age} + + + , + ); } else { - $render({health.title}{health.goal === null ? : }{String(health.value)}{health.unit}{health.detail}{health.age}Apple Health · Read-only); + // Large and extra large widgets: the ring above the number. + $render( + + + {health.title} + + + {health.goal === null ? ( + + ) : ( + + )} + + + {String(health.value)} + + + {health.unit} + + + + {health.detail} + + + + {health.age} + + + Apple Health · Read-only + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/lib/cloud-hydration.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/lib/cloud-hydration.js index e4362a70..70bc66c4 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/lib/cloud-hydration.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/lib/cloud-hydration.js @@ -1,68 +1,121 @@ // Add-only cloud log. Keeping each tap as a uniquely identified event makes // two offline devices' additions safe to union when iCloud exposes a fork. +// main.jsx imports this file ("lib/cloud-hydration.js") and then uses +// `cloudHydration`. The log is one JSON document: +// { version: 1, events: [{ id, at, day, ml }] }. var cloudHydration = (() => { + // The name of the document in the connected iCloud Data store, and its limits. const documentName = "hydration.json"; const maximumEvents = 512; const maximumJSONLength = 60 * 1024; - const empty = () => ({version: 1, events: []}); + const empty = () => ({ version: 1, events: [] }); const keys = (value) => Object.keys(value).sort().join(","); - const dayKey = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // Day key in local time, for example "2026-03-08". + const dayKey = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // True for a real calendar date written as YYYY-MM-DD. const validDay = (day) => { if (typeof day !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(day)) return false; const parts = day.split("-").map(Number); const date = new Date(Date.UTC(parts[0], parts[1] - 1, parts[2], 12)); return parts[0] >= 1970 && date.toISOString().slice(0, 10) === day; }; + // True for a UTC time written like 2026-03-08T12:00:00.000Z. const validTime = (time) => { - if (typeof time !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(time)) return false; + if (typeof time !== "string" || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(time)) + return false; const date = new Date(time); return !Number.isNaN(date.getTime()) && date.toISOString() === time; }; - const fail = () => { throw new Error("Cloud hydration history is invalid. Keep the existing revisions and repair them before recording more water."); }; + const fail = () => { + throw new Error( + "Cloud hydration history is invalid. Keep the existing revisions and repair them before recording more water.", + ); + }; + // Check a document and return a copy of it. No document yet gives an empty log. function parse(value) { if (value === null || value === undefined) return empty(); - if (!value || Array.isArray(value) || keys(value) !== "events,version" || value.version !== 1 || - !Array.isArray(value.events) || value.events.length > maximumEvents) return fail(); + if ( + !value || + Array.isArray(value) || + keys(value) !== "events,version" || + value.version !== 1 || + !Array.isArray(value.events) || + value.events.length > maximumEvents + ) + return fail(); const ids = new Set(); + // Every event needs a unique 32-digit hex id, a time, a day and 25 to 2000 mL. for (const event of value.events) { - if (!event || Array.isArray(event) || keys(event) !== "at,day,id,ml" || - typeof event.id !== "string" || !/^[0-9a-f]{32}$/.test(event.id) || ids.has(event.id) || - !validTime(event.at) || !validDay(event.day) || - !Number.isInteger(event.ml) || event.ml < 25 || event.ml > 2000) return fail(); + if ( + !event || + Array.isArray(event) || + keys(event) !== "at,day,id,ml" || + typeof event.id !== "string" || + !/^[0-9a-f]{32}$/.test(event.id) || + ids.has(event.id) || + !validTime(event.at) || + !validDay(event.day) || + !Number.isInteger(event.ml) || + event.ml < 25 || + event.ml > 2000 + ) + return fail(); ids.add(event.id); } - return {version: 1, events: value.events.slice()}; + return { version: 1, events: value.events.slice() }; } + // Combine several versions of the log: every event once, sorted by time. + // The same id with different content is an error. function merge(values) { const byID = new Map(); for (const value of values) { for (const event of parse(value).events) { const previous = byID.get(event.id); - if (previous && (previous.at !== event.at || previous.day !== event.day || previous.ml !== event.ml)) return fail(); + if ( + previous && + (previous.at !== event.at || previous.day !== event.day || previous.ml !== event.ml) + ) + return fail(); byID.set(event.id, event); } } - const events = Array.from(byID.values()).sort((a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id)); - const result = {version: 1, events}; + const events = Array.from(byID.values()).sort( + (a, b) => a.at.localeCompare(b.at) || a.id.localeCompare(b.id), + ); + const result = { version: 1, events }; + // The result must stay within the limits: 64000 mL a day, 512 events, 60 KiB of JSON. const totals = new Map(); for (const event of events) { const total = (totals.get(event.day) ?? 0) + event.ml; - if (total > 64000) throw new Error("Conflicting additions exceed the daily record limit. The original revisions are preserved."); + if (total > 64000) + throw new Error( + "Conflicting additions exceed the daily record limit. The original revisions are preserved.", + ); totals.set(event.day, total); } if (events.length > maximumEvents || JSON.stringify(result).length > maximumJSONLength) { - throw new Error("Cloud hydration history is full. Copy its JSON revisions from iCloud Drive before starting a new data store."); + throw new Error( + "Cloud hydration history is full. Copy its JSON revisions from iCloud Drive before starting a new data store.", + ); } return result; } + // Turn what $icloud.readJSON returned into one log. The state is "cached" or "pending" + // with the document in `value`, or "conflict" with the diverging versions in + // `conflicts`; those are merged. function fromSnapshot(snapshot) { if (!snapshot || typeof snapshot.revision !== "string") return fail(); if (snapshot.state === "conflict") { - if (!Array.isArray(snapshot.conflicts) || snapshot.conflicts.length < 2 || - snapshot.conflicts.some((head) => !head || typeof head.id !== "string" || !head.value)) return fail(); + if ( + !Array.isArray(snapshot.conflicts) || + snapshot.conflicts.length < 2 || + snapshot.conflicts.some((head) => !head || typeof head.id !== "string" || !head.value) + ) + return fail(); return merge(snapshot.conflicts.map((head) => head.value)); } if (snapshot.state !== "cached" && snapshot.state !== "pending") return fail(); @@ -70,41 +123,55 @@ var cloudHydration = (() => { return merge([snapshot.value]); } + // A new event id: the time in hex (12 digits) followed by 20 random hex digits. function idFor(date) { const time = date.getTime().toString(16).padStart(12, "0"); - return time + Array.from({length: 20}, () => Math.floor(Math.random() * 16).toString(16)).join(""); + return ( + time + Array.from({ length: 20 }, () => Math.floor(Math.random() * 16).toString(16)).join("") + ); } + // readJSON returns the copy cached on this device: { value, revision, state, conflicts }. async function read() { const snapshot = await $icloud.readJSON(documentName); - return {snapshot, data: fromSnapshot(snapshot)}; + return { snapshot, data: fromSnapshot(snapshot) }; } + // Add one glass of `ml` millilitres: read, append, write. If the document changed in + // the meantime, read again and retry. async function add(ml) { if (!Number.isInteger(ml) || ml < 25 || ml > 2000) throw new Error("Set glassML to 25–2000."); const at = new Date(); - const event = {id: idFor(at), at: at.toISOString(), day: dayKey(at), ml}; + const event = { id: idFor(at), at: at.toISOString(), day: dayKey(at), ml }; for (let attempt = 0; attempt < 3; attempt++) { - const {snapshot, data} = await read(); + const { snapshot, data } = await read(); if (data.events.some((item) => item.id === event.id)) return; - const total = data.events.filter((item) => item.day === event.day).reduce((sum, item) => sum + item.ml, 0); - if (total > 64000 - ml) throw new Error("Today's record limit would be exceeded. Nothing was saved."); - const next = merge([data, {version: 1, events: [event]}]); + const total = data.events + .filter((item) => item.day === event.day) + .reduce((sum, item) => sum + item.ml, 0); + if (total > 64000 - ml) + throw new Error("Today's record limit would be exceeded. Nothing was saved."); + const next = merge([data, { version: 1, events: [event] }]); try { - if (snapshot.state === "conflict") await $icloud.resolveJSON(documentName, next, snapshot.revision); + // A write names the revision it was based on. A conflict has to be settled with + // resolveJSON; writeJSON is rejected while there is one. + if (snapshot.state === "conflict") + await $icloud.resolveJSON(documentName, next, snapshot.revision); else await $icloud.writeJSON(documentName, next, snapshot.revision); return; } catch (error) { + // A stale revision or a new conflict: try again. Any other error ends here. if (!/staleRevision|\[icloud:conflict\]/.test(String(error))) throw error; } } throw new Error("Cloud records changed while saving. Please tap again."); } + // Ask iCloud to exchange data now, then settle a conflict if there is one. async function sync() { await $icloud.sync(); for (let attempt = 0; attempt < 2; attempt++) { - const {snapshot, data} = await read(); + const { snapshot, data } = await read(); if (snapshot.state !== "conflict") return; try { await $icloud.resolveJSON(documentName, data, snapshot.revision); @@ -116,14 +183,24 @@ var cloudHydration = (() => { throw new Error("Cloud records changed while merging. Please sync again."); } + // The last `count` days, oldest first: { day, total, recorded }, with `total` in mL. function recent(data, count = 7, now = new Date()) { - return Array.from({length: count}, (_, index) => { - const date = new Date(now.getFullYear(), now.getMonth(), now.getDate() + index - count + 1, 12); + return Array.from({ length: count }, (_, index) => { + const date = new Date( + now.getFullYear(), + now.getMonth(), + now.getDate() + index - count + 1, + 12, + ); const day = dayKey(date); const events = data.events.filter((event) => event.day === day); - return {day, total: events.reduce((sum, event) => sum + event.ml, 0), recorded: events.length > 0}; + return { + day, + total: events.reduce((sum, event) => sum + event.ml, 0), + recorded: events.length > 0, + }; }); } - return {read, add, sync, recent, dayKey, fromSnapshot}; + return { read, add, sync, recent, dayKey, fromSnapshot }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/main.jsx index 946fa82c..0b825d7f 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal iCloud/main.jsx @@ -1,26 +1,63 @@ // Separate iCloud example. It does not migrate or change Hydration Goal's local records. // Connect this installation to the same iCloud Data store ID on each device. -if (!$import("lib/cloud-hydration.js")) throw new Error("Install the complete template, including lib/cloud-hydration.js."); +// Shows today's water like Hydration Goal, but keeps the log in iCloud so that several +// devices can share it. Try another goal or glass size with the widget parameter. +// The iCloud API runs on iPhone, iPad and Mac, and on Android with a sync folder the user picks +// (it cannot exchange data with an iPhone); not on Windows or Linux. +// widget.json must declare the permission "icloud"; the buttons need its "actions". + +// $import runs another file of this package; lib/cloud-hydration.js defines `cloudHydration`. +// It returns false when the file is missing. +if (!$import("lib/cloud-hydration.js")) + throw new Error("Install the complete template, including lib/cloud-hydration.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); +// The optional widget parameter, JSON such as {"goal":8,"glassML":250}. const parameter = ($getenv("widget-param") || "").trim(); -let options = {goal: 8, glassML: 250}; +let options = { goal: 8, glassML: 250 }; if (parameter) { - try { options = {...options, ...JSON.parse(parameter)}; } - catch (_) { throw new Error('Use a JSON object such as {"goal":8,"glassML":250}.'); } - if (!options || Array.isArray(options) || Object.keys(options).some((key) => !["goal", "glassML"].includes(key))) { + try { + options = { ...options, ...JSON.parse(parameter) }; + } catch (_) { + throw new Error('Use a JSON object such as {"goal":8,"glassML":250}.'); + } + if ( + !options || + Array.isArray(options) || + Object.keys(options).some((key) => !["goal", "glassML"].includes(key)) + ) { throw new Error("Hydration settings accept goal and glassML only."); } } -const {goal, glassML} = options; -if (!Number.isInteger(goal) || goal < 1 || goal > 32 || !Number.isInteger(glassML) || glassML < 25 || glassML > 2000) { +// `goal` is in glasses, `glassML` in millilitres per glass. +const { goal, glassML } = options; +if ( + !Number.isInteger(goal) || + goal < 1 || + goal > 32 || + !Number.isInteger(glassML) || + glassML < 25 || + glassML > 2000 +) { throw new Error("Set goal to 1–32 glasses and glassML to 25–2000."); } -async function addGlass() { await cloudHydration.add(glassML); $render(Glass saved locally; iCloud delivery may follow later); } -async function syncRecords() { await cloudHydration.sync(); $render(Cloud exchange requested; delivery may follow later); } +// The two functions below are named by the "actions" in widget.json; a tap on a - {hint} - {!(["small", "medium"].includes(size)) && Last 7 days · mL{days.map((day) => {day.day.slice(5)}{day.recorded ? String(day.total) : "—"})}} - ); + else if (size === "accessoryCircular") + $render( + + {`${Math.round(progress * 100)}%`} + , + ); + else if (size === "accessoryRectangular") + $render( + + , + ); + else + $render( + + + + {/* Small widget: a progress bar. Other sizes: a ring next to the text. */} + {size === "small" ? ( + + + {label} + + + + ) : ( + + + + {label} + + + )} + + + + + + {hint} + + {/* Large sizes also list the 7 days. day.day.slice(5) is the MM-DD part. */} + {!["small", "medium"].includes(size) && ( + + + Last 7 days · mL + + {days.map((day) => ( + + + {day.day.slice(5)} + + + + {day.recorded ? String(day.total) : "—"} + + + ))} + + )} + , + ); } catch (error) { + // Reading failed, for example because iCloud Data is not connected: say what to do. console.error(String(error)); - $render(Hydration Goal iCloudConnect iCloud Data in ScriptWidget, then sync.{String(error)}); + $render( + + Hydration Goal iCloud + Connect iCloud Data in ScriptWidget, then sync. + {String(error)} + , + ); } } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/main.jsx index 019baa73..f9dcf6dc 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Hydration Goal/main.jsx @@ -1,49 +1,188 @@ // Local hydration log. Optional widget-param: {"goal":8,"glassML":250}. // Legacy current,goal parameters retain the goal only; sample counts are never saved. // Tap to record a glass. Undo restores the most recent change; Reset clears today only. -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); +// Shows today's water against a goal, with buttons to add a glass, undo and reset. +// Try another goal or glass size with the widget parameter, or change the colors. +// Saving needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const parameter = ($getenv("widget-param") || "").trim(); +// The settings saved by Records & Configuration (or the defaults), then the parameter. let options = localRecords.configuration("hydration"); if (parameter.startsWith("{")) { - try { options = {...options, ...JSON.parse(parameter)}; } catch (_) { throw new Error("Use a JSON object for hydration settings."); } - if (!options || Array.isArray(options) || Object.keys(options).some((key) => !["goal", "glassML"].includes(key))) throw new Error("Hydration settings accept goal and glassML only."); + try { + options = { ...options, ...JSON.parse(parameter) }; + } catch (_) { + throw new Error("Use a JSON object for hydration settings."); + } + if ( + !options || + Array.isArray(options) || + Object.keys(options).some((key) => !["goal", "glassML"].includes(key)) + ) + throw new Error("Hydration settings accept goal and glassML only."); } else if (parameter) { + // The older form of the parameter: a number, or "current,goal" where only the goal counts. options.goal = Number(parameter.includes(",") ? parameter.split(",")[1] : parameter); } +// `goal` is in glasses, `glassML` in millilitres per glass. const goal = options.goal === undefined ? 8 : options.goal; const glassML = options.glassML === undefined ? 250 : options.glassML; -if (!Number.isInteger(goal) || goal < 1 || goal > 32 || !Number.isInteger(glassML) || glassML < 25 || glassML > 2000) throw new Error("Set goal to 1–32 glasses and glassML to 25–2000."); +if ( + !Number.isInteger(goal) || + goal < 1 || + goal > 32 || + !Number.isInteger(glassML) || + glassML < 25 || + glassML > 2000 +) + throw new Error("Set goal to 1–32 glasses and glassML to 25–2000."); +// One record per day under the key "hydration.v1": the total of the day in mL. // Store measured millilitres; changing glass size never reinterprets past records. -const log = localRecords.create("hydration.v1", (value) => Number.isInteger(value) && value >= 0 && value <= 64000, 0); +const log = localRecords.create( + "hydration.v1", + (value) => Number.isInteger(value) && value >= 0 && value <= 64000, + 0, +); +// The three functions below are named by the "actions" in widget.json. A tap on a +// ; +// A text to tap. actionID names the action to run. +const Action = ({ name, title }) => ( + +); +// A tap runs this script with the size "function" or "action": draw no widget then. if (size === "function" || size === "action") { // Named handlers alone mutate records. } else if (size === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({`Water · ${label}`}); } else if (size === "accessoryCircular") { - $render({`${Math.round(progress * 100)}%`}); + // Lock Screen, circular: a gauge with the percentage. + $render( + + {`${Math.round(progress * 100)}%`} + , + ); } else if (size === "accessoryRectangular") { - $render(); + // Lock Screen, rectangular: the total and a progress bar. + $render( + + , + ); } else { + // Home Screen sizes. Large ones (`expanded`) also list the last 7 days. const expanded = !["small", "medium"].includes(size); - $render( - - {size === "small" ? {label}{total === 0 ? "Start with a glass" : progress === 1 ? "Goal reached" : "Every glass counts"} : {label}{total === 0 ? "Start with a glass" : progress === 1 ? "Goal reached" : "Every glass counts"}} - {size !== "small" && } - {expanded && Last 7 days · mL{log.recent(state).map((day) => {day.date.slice(5)}{day.recorded ? String(day.value) : "—"})}} - ); + $render( + + {/* log.today is a day key such as 2026-03-08; slice(5) keeps the 03-08 part. */} + + + {/* Small widget: a progress bar. Other sizes: a ring next to the text. */} + {size === "small" ? ( + + + {label} + + + + {total === 0 + ? "Start with a glass" + : progress === 1 + ? "Goal reached" + : "Every glass counts"} + + + ) : ( + + + + + {label} + + + {total === 0 + ? "Start with a glass" + : progress === 1 + ? "Goal reached" + : "Every glass counts"} + + + + )} + {/* The small widget has no room for Reset. */} + + + + {size !== "small" && } + + {expanded && ( + + + Last 7 days · mL + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? String(day.value) : "—"} + + + ))} + + )} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image Basic Usage/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image Basic Usage/main.jsx index 65a0f342..53a1247e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image Basic Usage/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image Basic Usage/main.jsx @@ -1,9 +1,11 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Usage for component image -// +// +// Shows a picture that fills the widget, with a label on top of it. +// The list below shows other ways to write ; copy one into $render to try it. /* @@ -25,8 +27,17 @@ */ $render( + // puts its children on top of each other: first the picture, then the text. - - Photo spotlight - + {/* mode="fill" scales the picture until it covers its frame; "fit" shows all of it instead. */} + + {/* frame="max,bottomLeading" fills the widget and keeps the content at the bottom left. */} + + + + + Photo spotlight + + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image No Margin/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image No Margin/main.jsx index 829a9e31..ce656b31 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image No Margin/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image No Margin/main.jsx @@ -1,15 +1,32 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // +// Shows three pictures side by side, with no gap between them or around them. +// Try other pictures (image/image0.png to image2.png in this widget's folder) or words. - +// spacing="0" removes the gap between the columns. frame="max" makes a view fill its space. $render( - Explore - Create - Enjoy - + {/* One column: a picture with a word on top of it. */} + + + + Explore + + + + + + Create + + + + + + Enjoy + + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image/main.jsx index cd64491b..85ffc7ba 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Image/main.jsx @@ -1,10 +1,12 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// +// Shows one picture. id="image" is the file image/image.png in this widget's folder. +// Try a picture of your own. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Layout Starter/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Layout Starter/main.jsx index c0e7a93d..4d3714da 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Layout Starter/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Layout Starter/main.jsx @@ -1,13 +1,26 @@ // Open Layout in the editor to select, edit, add and move these layers. // Code remains the source of truth. This template needs no permissions. +// A plain card: an icon and a short line at the top, two lines of text at the bottom. +// Try changing the texts and the colors. + +// $render draws the widget. frame="max" fills the whole widget, alignment="leading" +// lines the children up on the left, and padding is the space in points around them. $render( + {/* places its children side by side, one below the other. */} - - A fresh start + + + A fresh start + - - Make today yours - A little space for your ideas. - + {/* takes all free space, which pushes the two texts to the bottom. */} + + + Make today yours + + + A little space for your ideas. + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Live Activity Demo/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Live Activity Demo/main.jsx index efd63647..be332a7e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Live Activity Demo/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Live Activity Demo/main.jsx @@ -1,25 +1,186 @@ // Local state supplied by ScriptWidget's Live Activities screen. Rendering never polls. // Optional JSON: title, detail, progress+total, endsAt (ISO date). The app updates this state. -const raw=$getenv("live-activity-state")||$getenv("widget-param")||"",now=Date.now(); -let data={},invalid=false; -try{ - if(raw){if(typeof raw!=="string"||raw.length>4096)throw new Error();data=JSON.parse(raw);} - if(!data||typeof data!=="object"||Array.isArray(data)||Object.keys(data).some(key=>!["title","detail","progress","total","endsAt"].includes(key)))throw new Error(); - if(data.title!==undefined&&(typeof data.title!=="string"||data.title.length<1||data.title.length>40))throw new Error(); - if(data.detail!==undefined&&(typeof data.detail!=="string"||data.detail.length>80))throw new Error(); - if(data.progress!==undefined||data.total!==undefined){if(!Number.isInteger(data.progress)||!Number.isInteger(data.total)||data.total<1||data.total>10000||data.progress<0||data.progress>data.total)throw new Error();} - if(data.endsAt!==undefined&&(typeof data.endsAt!=="string"||!/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(data.endsAt)||!Number.isFinite(Date.parse(data.endsAt))))throw new Error(); -}catch{invalid=true;data={};} -const deadline=data.endsAt===undefined?null:Date.parse(data.endsAt),expired=deadline!==null&&deadline<=now,stale=$getenv("live-activity-is-stale")==="true"; -const title=invalid?"Invalid activity state":data.title||(raw?"Live activity":"Ready to start"),detail=invalid?"Update valid JSON in ScriptWidget.":expired?"Time is up":data.detail||(raw?"Updated from the app":"Start or update this activity in ScriptWidget."); -const hasProgress=data.progress!==undefined,summary=invalid?"Check state":hasProgress?`${data.progress} / ${data.total}`:expired?"Finished":stale?"Needs update":raw?"Active":"Ready"; -const Countdown=()=>deadline!==null&&!expired&&!invalid?:{summary}; +// Shows a Live Activity: a title, a detail line, and a countdown or a progress bar. +// Try starting it from the Live Activities screen of the app with a state such as +// {"title":"Tea","detail":"Steeping","endsAt":"2026-03-08T12:05:00Z"}. + +// $getenv("live-activity-state") is the state text the app gave this activity. When it +// is empty, the widget parameter is used instead. +const raw = $getenv("live-activity-state") || $getenv("widget-param") || "", + now = Date.now(); +let data = {}, + invalid = false; +// Check the state: only the five known keys, each of the right type and size. +// Anything else makes the state invalid, and the widget says so. +try { + if (raw) { + if (typeof raw !== "string" || raw.length > 4096) throw new Error(); + data = JSON.parse(raw); + } + if ( + !data || + typeof data !== "object" || + Array.isArray(data) || + Object.keys(data).some( + (key) => !["title", "detail", "progress", "total", "endsAt"].includes(key), + ) + ) + throw new Error(); + if ( + data.title !== undefined && + (typeof data.title !== "string" || data.title.length < 1 || data.title.length > 40) + ) + throw new Error(); + if (data.detail !== undefined && (typeof data.detail !== "string" || data.detail.length > 80)) + throw new Error(); + // progress and total come together: whole numbers with 0 ≤ progress ≤ total. + if (data.progress !== undefined || data.total !== undefined) { + if ( + !Number.isInteger(data.progress) || + !Number.isInteger(data.total) || + data.total < 1 || + data.total > 10000 || + data.progress < 0 || + data.progress > data.total + ) + throw new Error(); + } + // endsAt is an ISO date with a time zone, such as 2026-03-08T12:05:00Z. + if ( + data.endsAt !== undefined && + (typeof data.endsAt !== "string" || + !/^\d{4}-\d{2}-\d{2}T.*(?:Z|[+-]\d{2}:\d{2})$/.test(data.endsAt) || + !Number.isFinite(Date.parse(data.endsAt))) + ) + throw new Error(); +} catch { + invalid = true; + data = {}; +} +// `deadline` is the end time in milliseconds, or null without one. +// "live-activity-is-stale" is "true" when the system marks the activity as stale. +const deadline = data.endsAt === undefined ? null : Date.parse(data.endsAt), + expired = deadline !== null && deadline <= now, + stale = $getenv("live-activity-is-stale") === "true"; +// The texts to show, with a fallback for every case. +const title = invalid + ? "Invalid activity state" + : data.title || (raw ? "Live activity" : "Ready to start"), + detail = invalid + ? "Update valid JSON in ScriptWidget." + : expired + ? "Time is up" + : data.detail || + (raw ? "Updated from the app" : "Start or update this activity in ScriptWidget."); +const hasProgress = data.progress !== undefined, + summary = invalid + ? "Check state" + : hasProgress + ? `${data.progress} / ${data.total}` + : expired + ? "Finished" + : stale + ? "Needs update" + : raw + ? "Active" + : "Ready"; +// A timer while the deadline lies ahead, else the summary text. +// shows the time left and keeps counting on its own. +const Countdown = () => + deadline !== null && !expired && !invalid ? ( + + ) : ( + + {summary} + + ); // Small: the state and the title; the detail needs the width of the medium widget. -if($getenv("widget-size")==="small")$render({deadline!==null&&!expired&&!invalid?:{summary}}{title}{hasProgress&&}); -else $render({title}{detail}{hasProgress&&}{stale&&!expired&&Data needs an update}); +if ($getenv("widget-size") === "small") + $render( + + + + + + {deadline !== null && !expired && !invalid ? ( + + ) : ( + + {summary} + + )} + + {title} + + {hasProgress && } + , + ); +else + // Other sizes, and the Lock Screen view of the Live Activity: icon, texts, countdown. + $render( + + + + + {title} + + + {detail} + + {hasProgress && } + {stale && !expired && ( + + Data needs an update + + )} + + + , + ); +// $dynamic_island gives the views for the Dynamic Island: four regions of the expanded +// form, the two sides of the compact form, and the minimal form. $dynamic_island({ - expanded:{leading:,trailing:deadline!==null&&!expired&&!invalid?:{summary},center:{title},bottom:{detail}}, - compactLeading:, - compactTrailing:deadline!==null&&!expired&&!invalid?:{invalid?"!":hasProgress?`${data.progress}/${data.total}`:expired?"Done":"•"}, - minimal: + expanded: { + leading: ( + + ), + trailing: + deadline !== null && !expired && !invalid ? ( + + ) : ( + + {summary} + + ), + center: ( + + {title} + + ), + bottom: ( + + {detail} + + ), + }, + compactLeading: ( + + ), + compactTrailing: + deadline !== null && !expired && !invalid ? ( + + ) : ( + + {invalid ? "!" : hasProgress ? `${data.progress}/${data.total}` : expired ? "Done" : "•"} + + ), + minimal: , }); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/lib/weather.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/lib/weather.js index 397b0829..bd6e6cdb 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/lib/weather.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/lib/weather.js @@ -1,204 +1,527 @@ // MET Norway Locationforecast 2.0. Forecasts are model data, not observations. // https://api.met.no/doc/TermsOfService · https://api.met.no/doc/License +// main.jsx imports this file ("lib/weather.js") and then uses `localWeather`. +// It chooses the place, asks MET Norway for its forecast and keeps a copy in $storage. var localWeather = (() => { - const cacheKey = "weather.met.v1", hour = 3600000; - const defaults = {city:"",latitude:0,longitude:0,useLocation:true,unit:"c"}; - const numeric = (value,min,max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; - const keys = object => object && typeof object === "object" && !Array.isArray(object) ? Object.keys(object).sort().join(",") : ""; + // The storage key of the saved forecasts, and one hour in milliseconds. + const cacheKey = "weather.met.v1", + hour = 3600000; + // The settings. `unit` is "c" or "f"; `city` with its coordinates is the saved city. + const defaults = { city: "", latitude: 0, longitude: 0, useLocation: true, unit: "c" }; + // True for a real number between min and max. + const numeric = (value, min, max) => + typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; + // The keys of a plain object, sorted and joined ("a,b,c"); "" for anything else. + const keys = (object) => + object && typeof object === "object" && !Array.isArray(object) + ? Object.keys(object).sort().join(",") + : ""; function validOptions(value) { - return keys(value) === "city,latitude,longitude,unit,useLocation" && typeof value.city === "string" && value.city.length <= 60 && - numeric(value.latitude,-90,90) && numeric(value.longitude,-180,180) && typeof value.useLocation === "boolean" && ["c","f"].includes(value.unit); + return ( + keys(value) === "city,latitude,longitude,unit,useLocation" && + typeof value.city === "string" && + value.city.length <= 60 && + numeric(value.latitude, -90, 90) && + numeric(value.longitude, -180, 180) && + typeof value.useLocation === "boolean" && + ["c", "f"].includes(value.unit) + ); } - function options(raw,parameter) { - let value = {...defaults}; + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter: JSON, or latitude,longitude,City. + function options(raw, parameter) { + let value = { ...defaults }; if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || keys(state) !== "kind,values,version" || state.version !== 1 || state.kind !== "weather" || !validOptions(state.values)) throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); + } + if ( + typeof raw !== "string" || + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. + unescape(encodeURIComponent(raw)).length > 4096 || + keys(state) !== "kind,values,version" || + state.version !== 1 || + state.kind !== "weather" || + !validOptions(state.values) + ) + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); value = state.values; } parameter = (parameter || "").trim(); if (parameter) { if (parameter[0] === "{") { let custom; - try { custom = JSON.parse(parameter); } catch (_) { throw new Error("Weather parameters must be valid JSON."); } - if (!custom || Array.isArray(custom) || Object.keys(custom).some(key => !Object.prototype.hasOwnProperty.call(defaults,key))) throw new Error("Weather settings accept city, latitude, longitude, useLocation and unit only."); - value = {...value,...custom}; + try { + custom = JSON.parse(parameter); + } catch (_) { + throw new Error("Weather parameters must be valid JSON."); + } + if ( + !custom || + Array.isArray(custom) || + Object.keys(custom).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error( + "Weather settings accept city, latitude, longitude, useLocation and unit only.", + ); + value = { ...value, ...custom }; } else { - const parts = parameter.split(",").map(value => value.trim()); - if (parts.length < 2 || parts.length > 3 || parts.slice(0,2).some(value => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value))) throw new Error("Use latitude,longitude or JSON weather settings."); - value = {...value,city:parts[2] || "Selected city",latitude:Number(parts[0]),longitude:Number(parts[1]),useLocation:false}; + // latitude,longitude with an optional city name. A fixed place turns location off. + const parts = parameter.split(",").map((value) => value.trim()); + if ( + parts.length < 2 || + parts.length > 3 || + parts.slice(0, 2).some((value) => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) + ) + throw new Error("Use latitude,longitude or JSON weather settings."); + value = { + ...value, + city: parts[2] || "Selected city", + latitude: Number(parts[0]), + longitude: Number(parts[1]), + useLocation: false, + }; } } - if (!validOptions(value)) throw new Error("Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit."); + if (!validOptions(value)) + throw new Error( + "Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit.", + ); return value; } - const rounded = value => Number(value.toFixed(2)); - const placeKey = (source,latitude,longitude) => `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; - const validHTTPDate = value => typeof value === "string" && /^[A-Za-z0-9,: -]{1,128}$/.test(value) && Number.isFinite(Date.parse(value)); + // Coordinates are rounded to 2 decimals, roughly a kilometre, before use. + const rounded = (value) => Number(value.toFixed(2)); + // The name of a place in the saved copy, such as "manual:59.91,10.75". + const placeKey = (source, latitude, longitude) => + `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; + const validHTTPDate = (value) => + typeof value === "string" && + /^[A-Za-z0-9,: -]{1,128}$/.test(value) && + Number.isFinite(Date.parse(value)); + // One forecast point: time (ms), temperature (°C), humidity (%), wind (m/s), symbol code. function validPoint(point) { - return keys(point) === "humidity,symbol,temperature,time,wind" && Number.isSafeInteger(point.time) && point.time > 0 && - numeric(point.temperature,-100,70) && (point.humidity === null || numeric(point.humidity,0,100)) && - (point.wind === null || numeric(point.wind,0,160)) && typeof point.symbol === "string" && /^[a-z_]{1,64}$/.test(point.symbol); + return ( + keys(point) === "humidity,symbol,temperature,time,wind" && + Number.isSafeInteger(point.time) && + point.time > 0 && + numeric(point.temperature, -100, 70) && + (point.humidity === null || numeric(point.humidity, 0, 100)) && + (point.wind === null || numeric(point.wind, 0, 160)) && + typeof point.symbol === "string" && + /^[a-z_]{1,64}$/.test(point.symbol) + ); } - function validPlaceKey(key,source) { + function validPlaceKey(key, source) { if (typeof key !== "string") return false; const match = /^(manual|location):(-?\d{1,3}\.\d{2}),(-?\d{1,3}\.\d{2})$/.exec(key); - return !!match && match[1] === source && numeric(Number(match[2]),-90,90) && numeric(Number(match[3]),-180,180); + return ( + !!match && + match[1] === source && + numeric(Number(match[2]), -90, 90) && + numeric(Number(match[3]), -180, 180) + ); } - function packets(raw,now) { + // Read the saved copy: up to 4 places with up to 24 forecast points each. + // Anything unexpected gives an empty list, so a damaged copy is simply loaded again. + function packets(raw, now) { try { if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 64000) return []; const state = JSON.parse(raw); - if (keys(state) !== "entries,version" || state.version !== 1 || !Array.isArray(state.entries) || state.entries.length > 4) return []; + if ( + keys(state) !== "entries,version" || + state.version !== 1 || + !Array.isArray(state.entries) || + state.entries.length > 4 + ) + return []; const names = new Set(); for (const entry of state.entries) { - if (keys(entry) !== "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || - !["manual","location"].includes(entry.source) || !validPlaceKey(entry.key,entry.source) || names.has(entry.key) || - !Number.isSafeInteger(entry.checkedAt) || entry.checkedAt < 0 || entry.checkedAt > now+300000 || - !Number.isSafeInteger(entry.nextRequestAt) || entry.nextRequestAt < entry.checkedAt || entry.nextRequestAt > entry.checkedAt+7*24*hour || - !Number.isSafeInteger(entry.updatedAt) || entry.updatedAt < 0 || entry.updatedAt > now+300000 || - typeof entry.failed !== "boolean" || typeof entry.deprecated !== "boolean" || - (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || !Array.isArray(entry.points) || entry.points.length > 24 || - !entry.points.every(validPoint) || entry.points.some((point,index) => index > 0 && point.time <= entry.points[index-1].time) || - (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0)) return []; + if ( + keys(entry) !== + "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || + !["manual", "location"].includes(entry.source) || + !validPlaceKey(entry.key, entry.source) || + names.has(entry.key) || + !Number.isSafeInteger(entry.checkedAt) || + entry.checkedAt < 0 || + entry.checkedAt > now + 300000 || + !Number.isSafeInteger(entry.nextRequestAt) || + entry.nextRequestAt < entry.checkedAt || + entry.nextRequestAt > entry.checkedAt + 7 * 24 * hour || + !Number.isSafeInteger(entry.updatedAt) || + entry.updatedAt < 0 || + entry.updatedAt > now + 300000 || + typeof entry.failed !== "boolean" || + typeof entry.deprecated !== "boolean" || + (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || + !Array.isArray(entry.points) || + entry.points.length > 24 || + !entry.points.every(validPoint) || + entry.points.some( + (point, index) => index > 0 && point.time <= entry.points[index - 1].time, + ) || + (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0) + ) + return []; names.add(entry.key); } return state.entries; - } catch (_) { return []; } + } catch (_) { + return []; + } } - function publish(packet,now,projection) { + // Save the forecast of one place next to the others; only one place found by location + // is kept. compareAndSetString writes only if the stored text is still `raw`; if + // something else saved in between, read again and retry. + function publish(packet, now, projection) { if (projection) return false; - for (let attempt=0;attempt<4;attempt++) { - const raw = $storage.getString(cacheKey), entries = packets(raw,now); - const previous = entries.find(entry => entry.key === packet.key); - if (previous && (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt)) return true; - const next = [packet,...entries.filter(entry => entry.key !== packet.key && (packet.source !== "location" || entry.source !== "location"))].sort((a,b) => b.checkedAt-a.checkedAt).slice(0,4); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:next}))) return true; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + entries = packets(raw, now); + const previous = entries.find((entry) => entry.key === packet.key); + if ( + previous && + (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt) + ) + return true; + const next = [ + packet, + ...entries.filter( + (entry) => + entry.key !== packet.key && + (packet.source !== "location" || entry.source !== "location"), + ), + ] + .sort((a, b) => b.checkedAt - a.checkedAt) + .slice(0, 4); + if ( + $storage.compareAndSetString(cacheKey, raw, JSON.stringify({ version: 1, entries: next })) + ) + return true; } return false; } - function expires(headers,now) { + // When to ask again: when the response expires (Expires, else Cache-Control max-age), + // or in one hour without a usable time. Never sooner than 15 minutes, plus up to 5 + // random minutes. + function expires(headers, now) { let until = Date.parse(headers.expires || ""); const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"] || ""); - if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]),604800)*1000; - if (!Number.isFinite(until) || until > now+7*24*hour) until = now+hour; - return Math.round(Math.max(now+900000,until)+Math.random()*300000); + if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]), 604800) * 1000; + if (!Number.isFinite(until) || until > now + 7 * 24 * hour) until = now + hour; + return Math.round(Math.max(now + 900000, until) + Math.random() * 300000); } - function parseResponse(body,place,now,headers,status) { - if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) throw new Error("Invalid forecast"); - const data = JSON.parse(body), meta = data?.properties?.meta, times = data?.properties?.timeseries; + // Check the answer of MET Norway and keep up to 24 points, starting 2 hours ago. + function parseResponse(body, place, now, headers, status) { + if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) + throw new Error("Invalid forecast"); + const data = JSON.parse(body), + meta = data?.properties?.meta, + times = data?.properties?.timeseries; const updatedAt = Date.parse(meta?.updated_at || ""); - if (!Number.isFinite(updatedAt) || updatedAt > now+300000 || now-updatedAt > 24*hour || meta?.units?.air_temperature !== "celsius" || meta?.units?.wind_speed !== "m/s" || !Array.isArray(times) || times.length < 1 || times.length > 250) throw new Error("Invalid forecast"); + if ( + !Number.isFinite(updatedAt) || + updatedAt > now + 300000 || + now - updatedAt > 24 * hour || + meta?.units?.air_temperature !== "celsius" || + meta?.units?.wind_speed !== "m/s" || + !Array.isArray(times) || + times.length < 1 || + times.length > 250 + ) + throw new Error("Invalid forecast"); const points = []; for (const item of times) { const time = Date.parse(item?.time || ""); if (!Number.isFinite(time)) throw new Error("Invalid forecast time"); - if (time < now-2*hour || points.length >= 24) continue; - const details = item?.data?.instant?.details, summary = item?.data?.next_1_hours?.summary || item?.data?.next_6_hours?.summary || item?.data?.next_12_hours?.summary; - const point = {time,temperature:details?.air_temperature,humidity:meta.units.relative_humidity === "%" && numeric(details?.relative_humidity,0,100) ? details.relative_humidity : null, - wind:numeric(details?.wind_speed,0,160) ? details.wind_speed : null,symbol:summary?.symbol_code || "unknown"}; - if (!validPoint(point) || (points.length && time <= points[points.length-1].time)) throw new Error("Invalid forecast point"); + if (time < now - 2 * hour || points.length >= 24) continue; + const details = item?.data?.instant?.details, + summary = + item?.data?.next_1_hours?.summary || + item?.data?.next_6_hours?.summary || + item?.data?.next_12_hours?.summary; + const point = { + time, + temperature: details?.air_temperature, + humidity: + meta.units.relative_humidity === "%" && numeric(details?.relative_humidity, 0, 100) + ? details.relative_humidity + : null, + wind: numeric(details?.wind_speed, 0, 160) ? details.wind_speed : null, + symbol: summary?.symbol_code || "unknown", + }; + if (!validPoint(point) || (points.length && time <= points[points.length - 1].time)) + throw new Error("Invalid forecast point"); points.push(point); } - if (!points.some(point=>Math.abs(point.time-now)<=90*60000)) throw new Error("Forecast is unavailable"); - return {key:place.key,source:place.source,updatedAt,checkedAt:now,nextRequestAt:expires(headers,now), - lastModified:validHTTPDate(headers["last-modified"]) && Date.parse(headers["last-modified"]) <= now+300000 ? headers["last-modified"] : "",points,failed:false,deprecated:status===203}; + // One of the points must lie within 90 minutes of now. + if (!points.some((point) => Math.abs(point.time - now) <= 90 * 60000)) + throw new Error("Forecast is unavailable"); + // Status 203 is how MET Norway announces that this version of the service will end. + return { + key: place.key, + source: place.source, + updatedAt, + checkedAt: now, + nextRequestAt: expires(headers, now), + lastModified: + validHTTPDate(headers["last-modified"]) && + Date.parse(headers["last-modified"]) <= now + 300000 + ? headers["last-modified"] + : "", + points, + failed: false, + deprecated: status === 203, + }; } - function pointAt(packet,now) { - if (!packet || !packet.points.length || now-packet.updatedAt > 24*hour || packet.updatedAt > now+300000) return null; - const earlier = packet.points.filter(point => point.time <= now); - const point = earlier[earlier.length-1] || packet.points[0]; - return Math.abs(point.time-now) <= 90*60000 ? point : null; + // The forecast point for now: the latest one that is not in the future, provided it is + // within 90 minutes of now and the forecast is less than a day old. + function pointAt(packet, now) { + if ( + !packet || + !packet.points.length || + now - packet.updatedAt > 24 * hour || + packet.updatedAt > now + 300000 + ) + return null; + const earlier = packet.points.filter((point) => point.time <= now); + const point = earlier[earlier.length - 1] || packet.points[0]; + return Math.abs(point.time - now) <= 90 * 60000 ? point : null; } + // Turn a symbol code such as "partlycloudy_night" into a title and an SF Symbol name. function condition(symbol) { const night = symbol.endsWith("_night"); - if (symbol.includes("thunder")) return {title:"Thunderstorms",icon:"cloud.bolt.rain.fill"}; - if (symbol.includes("snow") || symbol.includes("sleet")) return {title:"Snow or sleet",icon:"cloud.snow.fill"}; - if (symbol.includes("rain")) return {title:"Rain",icon:"cloud.rain.fill"}; - if (symbol.includes("fog")) return {title:"Fog",icon:"cloud.fog.fill"}; - if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) return {title:"Partly cloudy",icon:night ? "cloud.moon.fill" : "cloud.sun.fill"}; - if (symbol.startsWith("clearsky")) return {title:"Clear",icon:night ? "moon.stars.fill" : "sun.max.fill"}; - if (symbol.startsWith("cloudy")) return {title:"Cloudy",icon:"cloud.fill"}; - return {title:"Forecast",icon:"cloud.fill"}; + if (symbol.includes("thunder")) return { title: "Thunderstorms", icon: "cloud.bolt.rain.fill" }; + if (symbol.includes("snow") || symbol.includes("sleet")) + return { title: "Snow or sleet", icon: "cloud.snow.fill" }; + if (symbol.includes("rain")) return { title: "Rain", icon: "cloud.rain.fill" }; + if (symbol.includes("fog")) return { title: "Fog", icon: "cloud.fog.fill" }; + if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) + return { title: "Partly cloudy", icon: night ? "cloud.moon.fill" : "cloud.sun.fill" }; + if (symbol.startsWith("clearsky")) + return { title: "Clear", icon: night ? "moon.stars.fill" : "sun.max.fill" }; + if (symbol.startsWith("cloudy")) return { title: "Cloudy", icon: "cloud.fill" }; + return { title: "Forecast", icon: "cloud.fill" }; } - const locationAllowed = () => $location.isAvailable() && ["authorizedWhenInUse","authorizedAlways"].includes($location.authorizationStatus()) && $location.isAuthorizedForWidgetUpdates(); - function clearLocationCache(now,projection) { + // True when location exists here, the app may use it and widgets may use it too. + const locationAllowed = () => + $location.isAvailable() && + ["authorizedWhenInUse", "authorizedAlways"].includes($location.authorizationStatus()) && + $location.isAuthorizedForWidgetUpdates(); + // Forget the forecast saved for a location once location is no longer allowed. + function clearLocationCache(now, projection) { if (projection) return; - for (let attempt=0;attempt<4;attempt++) { - const raw=$storage.getString(cacheKey), filtered=packets(raw,now).filter(entry=>entry.source!=="location"); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:filtered}))) return; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + filtered = packets(raw, now).filter((entry) => entry.source !== "location"); + if ( + $storage.compareAndSetString( + cacheKey, + raw, + JSON.stringify({ version: 1, entries: filtered }), + ) + ) + return; } } - async function revoked(config,now,projection) { - clearLocationCache(now,projection); - return config.city.trim() ? await load({...config,useLocation:false},now,projection) : {available:false,title:"Location access changed",hint:"Choose a saved city to continue."}; + // Location was allowed and no longer is: use the saved city, if there is one. + async function revoked(config, now, projection) { + clearLocationCache(now, projection); + return config.city.trim() + ? await load({ ...config, useLocation: false }, now, projection) + : { + available: false, + title: "Location access changed", + hint: "Choose a saved city to continue.", + }; } - async function load(config,now,projection) { - let entries = packets($storage.getString(cacheKey),now); + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which asks neither for the position + // nor for a new forecast. + async function load(config, now, projection) { + let entries = packets($storage.getString(cacheKey), now); const authorized = locationAllowed(); - if (!authorized && entries.some(entry => entry.source === "location")) { - entries = entries.filter(entry => entry.source !== "location"); - clearLocationCache(now,projection); + if (!authorized && entries.some((entry) => entry.source === "location")) { + entries = entries.filter((entry) => entry.source !== "location"); + clearLocationCache(now, projection); } + // Choose the place: the current position, else the last saved one, else the city. let place = null; if (config.useLocation && authorized) { if (!projection) { try { - const location = await $location.current({maxAge:3600}); - const stale = location.isStale === true || (typeof location.age === "number" && location.age > 3600); - if (!stale && numeric(location.latitude,-90,90) && numeric(location.longitude,-180,180)) place = {source:"location",name:location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area",latitude:rounded(location.latitude),longitude:rounded(location.longitude)}; + // maxAge: 3600 accepts a position up to one hour old; `age` is in seconds. + const location = await $location.current({ maxAge: 3600 }); + const stale = + location.isStale === true || (typeof location.age === "number" && location.age > 3600); + if ( + !stale && + numeric(location.latitude, -90, 90) && + numeric(location.longitude, -180, 180) + ) + place = { + source: "location", + name: + location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area", + latitude: rounded(location.latitude), + longitude: rounded(location.longitude), + }; } catch (_) {} } if (!place && (!config.city.trim() || projection)) { - const saved = entries.find(entry => entry.source === "location" && pointAt(entry,now)); - if (saved) place = {source:"location",name:"Last location",key:saved.key,skipNetwork:true}; + const saved = entries.find((entry) => entry.source === "location" && pointAt(entry, now)); + if (saved) + place = { source: "location", name: "Last location", key: saved.key, skipNetwork: true }; } } - if (!place && config.city.trim()) place = {source:"manual",name:config.city,latitude:rounded(config.latitude),longitude:rounded(config.longitude)}; - if (!place) return {available:false,title:"Choose a saved city",hint:"Open Records & Configuration. Location is optional."}; - place.key ??= placeKey(place.source,place.latitude,place.longitude); + if (!place && config.city.trim()) + place = { + source: "manual", + name: config.city, + latitude: rounded(config.latitude), + longitude: rounded(config.longitude), + }; + if (!place) + return { + available: false, + title: "Choose a saved city", + hint: "Open Records & Configuration. Location is optional.", + }; + place.key ??= placeKey(place.source, place.latitude, place.longitude); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } - let packet = entries.find(entry => entry.key === place.key), saved = true, fromCache = true; + let packet = entries.find((entry) => entry.key === place.key), + saved = true, + fromCache = true; + // Ask MET Norway only when there is no saved forecast for the place or it is due. if (!projection && !place.skipNetwork && (!packet || now >= packet.nextRequestAt)) { try { - const headers = {"User-Agent":"ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)","Accept":"application/json"}; + const headers = { + "User-Agent": "ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)", + Accept: "application/json", + }; if (packet?.lastModified) headers["If-Modified-Since"] = packet.lastModified; - const response = await $http.getResponse(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`,{headers,timeoutInterval:4}); + // The call resolves to { status, body, headers }, also for statuses such as 304. + const response = await $http.getResponse( + `https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`, + { headers, timeoutInterval: 4 }, + ); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } const responseHeaders = response.headers || {}; - if (response.status === 304 && pointAt(packet,now)) packet = {...packet,checkedAt:now,nextRequestAt:expires(responseHeaders,now),failed:false}; - else if (response.status === 200 || response.status === 203) { packet = parseResponse(response.body,place,now,responseHeaders,response.status);fromCache=false; } - else { + // 304: not changed since the last request, so the saved points stay. + if (response.status === 304 && pointAt(packet, now)) + packet = { + ...packet, + checkedAt: now, + nextRequestAt: expires(responseHeaders, now), + failed: false, + }; + else if (response.status === 200 || response.status === 203) { + packet = parseResponse(response.body, place, now, responseHeaders, response.status); + fromCache = false; + } else { + // Another status: retry at the Retry-After time, 15 minutes to 24 hours from now. const retry = responseHeaders["retry-after"] || ""; - let until = /^\d+$/.test(retry) ? now+Number(retry)*1000 : Date.parse(retry); - if (!Number.isFinite(until)) until = now+900000; - const error = new Error("Refresh unavailable");error.retryAt=Math.min(now+24*hour,Math.max(now+900000,until));throw error; + let until = /^\d+$/.test(retry) ? now + Number(retry) * 1000 : Date.parse(retry); + if (!Number.isFinite(until)) until = now + 900000; + const error = new Error("Refresh unavailable"); + error.retryAt = Math.min(now + 24 * hour, Math.max(now + 900000, until)); + throw error; } - saved = publish(packet,now,projection); + saved = publish(packet, now, projection); } catch (error) { - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const retryAt = numeric(error?.retryAt,now,now+24*hour) ? error.retryAt : now+900000; - packet = packet || {key:place.key,source:place.source,updatedAt:0,lastModified:"",points:[],deprecated:false}; - packet = {...packet,checkedAt:now,nextRequestAt:Math.round(retryAt),failed:true}; - saved = publish(packet,now,projection); + // No usable answer: keep the saved points and note the failure. + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const retryAt = numeric(error?.retryAt, now, now + 24 * hour) + ? error.retryAt + : now + 900000; + packet = packet || { + key: place.key, + source: place.source, + updatedAt: 0, + lastModified: "", + points: [], + deprecated: false, + }; + packet = { ...packet, checkedAt: now, nextRequestAt: Math.round(retryAt), failed: true }; + saved = publish(packet, now, projection); } } - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const point = pointAt(packet,now); - if (!point) return {available:false,title:"Forecast unavailable",hint:"Check your connection or saved city, then refresh."}; - const celsius = config.unit === "c", temperature = value => Math.round(celsius ? value : value*9/5+32) + (celsius ? "°C" : "°F"); - const age = Math.max(0,Math.floor((now-packet.updatedAt)/60000)); - const statusText = packet.deprecated ? "Service update needed" : !saved ? "Cache unavailable" : packet.failed ? "Saved forecast · refresh unavailable" : place.skipNetwork ? "Saved forecast · last location" : fromCache ? "Saved forecast" : "Forecast"; - const statusShort = packet.deprecated ? "Service update" : !saved ? "No cache" : packet.failed ? "Saved · refresh failed" : place.skipNetwork ? "Last location" : fromCache ? "Saved forecast" : "Forecast"; - return {available:true,statusShort,name:place.name,source:place.source,condition:condition(point.symbol),temperature:temperature(point.temperature), - humidity:point.humidity === null ? "—" : Math.round(point.humidity)+"%",wind:point.wind === null ? "—" : (point.wind*3.6).toFixed(1)+" km/h", - updated:age < 1 ? "Updated just now" : age < 60 ? `Updated ${age}m ago` : `Updated ${Math.floor(age/60)}h ago`,status:statusText, - upcoming:packet.points.filter(value => value.time > point.time).slice(0,4).map(value => ({label:"+"+Math.max(1,Math.round((value.time-now)/hour))+"h",temperature:temperature(value.temperature),condition:condition(value.symbol)}))}; + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const point = pointAt(packet, now); + if (!point) + return { + available: false, + title: "Forecast unavailable", + hint: "Check your connection or saved city, then refresh.", + }; + // Temperatures are saved in °C and converted for display. + const celsius = config.unit === "c", + temperature = (value) => + Math.round(celsius ? value : (value * 9) / 5 + 32) + (celsius ? "°C" : "°F"); + // Minutes since MET Norway updated the forecast. + const age = Math.max(0, Math.floor((now - packet.updatedAt) / 60000)); + const statusText = packet.deprecated + ? "Service update needed" + : !saved + ? "Cache unavailable" + : packet.failed + ? "Saved forecast · refresh unavailable" + : place.skipNetwork + ? "Saved forecast · last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + const statusShort = packet.deprecated + ? "Service update" + : !saved + ? "No cache" + : packet.failed + ? "Saved · refresh failed" + : place.skipNetwork + ? "Last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + // The result for main.jsx. Wind is converted from m/s to km/h (× 3.6). + // `upcoming` holds the next 4 points, with labels such as "+3h". + return { + available: true, + statusShort, + name: place.name, + source: place.source, + condition: condition(point.symbol), + temperature: temperature(point.temperature), + humidity: point.humidity === null ? "—" : Math.round(point.humidity) + "%", + wind: point.wind === null ? "—" : (point.wind * 3.6).toFixed(1) + " km/h", + updated: + age < 1 + ? "Updated just now" + : age < 60 + ? `Updated ${age}m ago` + : `Updated ${Math.floor(age / 60)}h ago`, + status: statusText, + upcoming: packet.points + .filter((value) => value.time > point.time) + .slice(0, 4) + .map((value) => ({ + label: "+" + Math.max(1, Math.round((value.time - now) / hour)) + "h", + temperature: temperature(value.temperature), + condition: condition(value.symbol), + })), + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/main.jsx index eefd33f5..c6f5cff6 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Local Weather (Location)/main.jsx @@ -2,25 +2,189 @@ // Optional instance parameter: latitude,longitude,City or JSON weather settings. // Forecast data: MET Norway (CC BY 4.0). No API key; Expires/conditional requests // and a bounded four-place cache reduce traffic. No exact refresh guarantee. -if (!$import("lib/weather.js")) throw new Error("Install the complete weather template, including lib/weather.js."); -const config = localWeather.options($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); -const weather = await localWeather.load(config,Date.now(),$getenv("timeline-is-projection") === "true"); -const size = $getenv("widget-size"), compact = size === "small"; +// Shows the forecast for where you are, or for a saved city, in every widget size. +// Try the widget parameter: 59.91,10.75,Oslo or {"unit":"f"}. +// The Location API runs on iPhone and iPad, and on Android (widgets see the position +// saved while the app was open); not on Mac, Windows or Linux. There the saved city is +// used. widget.json must declare the permissions "location", "storage" and "network", +// with the host api.met.no. + +// $import runs another file of this package; lib/weather.js defines `localWeather`. +// It returns false when the file is missing. +if (!$import("lib/weather.js")) + throw new Error("Install the complete weather template, including lib/weather.js."); +// The settings: defaults, then what the app saved in $storage, then the widget parameter +// ($getenv("widget-param"), a text you set on each widget you place). +const config = localWeather.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Read the forecast: from MET Norway when the saved copy is due for a refresh, else from +// $storage. "timeline-is-projection" is "true" when the script runs for a future timeline +// entry; no request is made then. +const weather = await localWeather.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +const size = $getenv("widget-size"), + compact = size === "small"; +// No forecast: show the reason in a form that fits the size. if (!weather.available) { if (size === "accessoryInline") $render({weather.title}); - else if (size === "accessoryCircular") $render(); - else if (size === "accessoryRectangular") $render({weather.title}Open ScriptWidget to configure weather.); - else $render({weather.title}{weather.hint}); + else if (size === "accessoryCircular") $render(); + else if (size === "accessoryRectangular") + $render( + + {weather.title} + Open ScriptWidget to configure weather. + , + ); + else + $render( + + + + {weather.title} + + + {weather.hint} + + , + ); } else if (size === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({weather.temperature + " · " + weather.condition.title}); } else if (size === "accessoryCircular") { - $render({weather.temperature}); + // Lock Screen, circular: an icon and the temperature. + $render( + + + + {weather.temperature} + + , + ); } else if (size === "accessoryRectangular") { - $render({weather.name + " · " + weather.temperature}{weather.condition.title}); + // Lock Screen, rectangular: place, temperature and condition. + $render( + + + + {weather.name + " · " + weather.temperature} + {weather.condition.title} + + , + ); } else if (compact) { - $render({Array.from(weather.name).slice(0,12).join("")}{weather.temperature}{weather.condition.title}{weather.statusShort}{weather.updated}MET Norway); + // Small widget. Array.from(name).slice(0, 12) keeps the first 12 characters of the name. + $render( + + + {Array.from(weather.name).slice(0, 12).join("")} + + + + {weather.temperature} + + + + + + {weather.condition.title} + + + {weather.statusShort} + + + {weather.updated} + + + MET Norway + + , + ); } else if (size === "medium") { - $render({weather.name}{weather.condition.title}{weather.temperature}{weather.updated}MET Norway{weather.status}); + // Medium widget: icon, place and temperature in one row. + $render( + + + + + + {weather.name} + + + {weather.condition.title} + + + + + {weather.temperature} + + + + + {weather.updated} + + + + MET Norway + + + + {weather.status} + + , + ); } else { - $render({weather.name}{weather.condition.title}{weather.temperature}{"Wind " + weather.wind}{"Humidity " + weather.humidity}{weather.upcoming.map(point => {point.label}{point.temperature})}{weather.status + " · " + weather.updated}MET Norway · CC BY 4.0); + // Large and extra large widgets: also wind, humidity and the next forecast points. + $render( + + + + + {weather.name} + + + {weather.condition.title} + + + + + + + {weather.temperature} + + + + {"Wind " + weather.wind} + + + + {"Humidity " + weather.humidity} + + + + {weather.upcoming.map((point) => ( + + + {point.label} + + + + {point.temperature} + + + ))} + + + {weather.status + " · " + weather.updated} + + + MET Norway · CC BY 4.0 + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Location Snapshot/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Location Snapshot/main.jsx index bc4521db..6489b35e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Location Snapshot/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Location Snapshot/main.jsx @@ -5,53 +5,130 @@ // Location Snapshot // Requires Location permission in the main app. // +// Shows the latitude, longitude and accuracy of your position. +// Try changing the colors, or the number of decimals in toFixed(4). +// $location runs on iPhone and iPad, and on Android (widgets see the position saved +// while the app was open); not on Mac, Windows or Linux. +// widget.json must declare the permission "location". // The card of the two states without a location. At the small size a row has // no room for the icon beside the words, so the icon sits above them. const Card = ({ symbol, title, detail }) => { + // $getenv("widget-size") is the size being drawn, such as "small" or "medium". const compact = $getenv("widget-size") === "small"; - const words = LOCATION SNAPSHOT{title}{detail}; - return compact - ? {words} - : {words}; + const words = ( + + + LOCATION SNAPSHOT + + + {title} + + + {detail} + + + ); + return compact ? ( + + + {words} + + ) : ( + + + {words} + + ); }; +// isAvailable() is false on a system without the Location API. if (!$location.isAvailable()) { - $render(); + $render( + , + ); } else { + // Has the user allowed ScriptWidget to use the location? const status = $location.authorizationStatus(); const authorized = status === "authorizedWhenInUse" || status === "authorizedAlways"; if (!authorized) { - $render(); + $render( + , + ); } else { let location; try { + // Accept a position up to one hour old (maxAge is in seconds). `await` waits for it. location = await $location.current({ maxAge: 3600 }); - } catch(error) { + } catch (error) { + // No position. The error text tells whether widgets still have to be allowed. const message = String(error); const needsWidgetAccess = message.includes("widget_not_authorized"); const compactLocation = $getenv("widget-size") === "small"; $render( - - - {needsWidgetAccess ? (compactLocation ? "Allow widgets" : "Allow widget location") : (compactLocation ? "No location yet" : "Location unavailable")} - {needsWidgetAccess ? "In Settings, allow location for the app and widgets." : "Open ScriptWidget → Settings → Location, then refresh."} - + + + + {needsWidgetAccess + ? compactLocation + ? "Allow widgets" + : "Allow widget location" + : compactLocation + ? "No location yet" + : "Location unavailable"} + + + {needsWidgetAccess + ? "In Settings, allow location for the app and widgets." + : "Open ScriptWidget → Settings → Location, then refresh."} + + , ); + // Stop here: the message above is the widget. return; } + // Four decimals are about 11 metres. `accuracy` is in metres. const lat = location.latitude.toFixed(4); const lon = location.longitude.toFixed(4); const accuracy = Math.max(0, Math.round(location.accuracy)); + // frame="max" lets the stack fill the whole widget. $render( - Location Snapshot - {lat}, {lon} - Accuracy: {accuracy}m - {location.isStale ? "Saved · " + Math.round(location.age / 60) + "m ago" : "Updated " + new Date(location.timestamp).toLocaleTimeString(undefined, { hour: "2-digit", minute: "2-digit" })} - + + Location Snapshot + + + {lat}, {lon} + + + Accuracy: {accuracy}m + + {/* A saved position shows its age (location.age is in seconds), a fresh one its time. */} + + {location.isStale + ? "Saved · " + Math.round(location.age / 60) + "m ago" + : "Updated " + + new Date(location.timestamp).toLocaleTimeString(undefined, { + hour: "2-digit", + minute: "2-digit", + })} + + , ); } } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Lunar Date/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Lunar Date/main.jsx index 8b7050a0..ae207cb8 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Lunar Date/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Lunar Date/main.jsx @@ -1,535 +1,1164 @@ - // // ScriptWidget // https://atomsprout.com/scriptwidget // // +// Shows today in the Chinese lunar calendar: zodiac animal, month, day and festival. +// Try changing the gradient colors, or show another field such as today.gzYear. +// Most of this file is a calendar library; the widget itself is at the very end. var getLunarData = (function () { - //公历农历转换 - var calendar = { - lunarInfo: [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2, - 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, - 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, - 0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, - 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, - 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, - 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, - 0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, - 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, - 0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, - 0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, - 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, - 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, - 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, - 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, - 0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0, - 0x0a2e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4, - 0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0, - 0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160, - 0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252, - 0x0d520], - solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], - Gan: ["\u7532", "\u4e59", "\u4e19", "\u4e01", "\u620a", "\u5df1", "\u5e9a", "\u8f9b", "\u58ec", "\u7678"], - Zhi: ["\u5b50", "\u4e11", "\u5bc5", "\u536f", "\u8fb0", "\u5df3", "\u5348", "\u672a", "\u7533", "\u9149", "\u620c", "\u4ea5"], - Animals: ["\u9f20", "\u725b", "\u864e", "\u5154", "\u9f99", "\u86c7", "\u9a6c", "\u7f8a", "\u7334", "\u9e21", "\u72d7", "\u732a"], - solarTerm: ["\u5c0f\u5bd2", "\u5927\u5bd2", "\u7acb\u6625", "\u96e8\u6c34", "\u60ca\u86f0", "\u6625\u5206", "\u6e05\u660e", "\u8c37\u96e8", "\u7acb\u590f", "\u5c0f\u6ee1", "\u8292\u79cd", "\u590f\u81f3", "\u5c0f\u6691", "\u5927\u6691", "\u7acb\u79cb", "\u5904\u6691", "\u767d\u9732", "\u79cb\u5206", "\u5bd2\u9732", "\u971c\u964d", "\u7acb\u51ac", "\u5c0f\u96ea", "\u5927\u96ea", "\u51ac\u81f3"], - sTermInfo: ['9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', - '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', - '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', - '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', - 'b027097bd097c36b0b6fc9274c91aa', '9778397bd19801ec9210c965cc920e', '97b6b97bd19801ec95f8c965cc920f', - '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd197c36c9210c9274c91aa', - '97b6b97bd19801ec95f8c965cc920e', '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', - '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e', '97bcf97c3598082c95f8e1cfcc920f', - '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', - '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', - '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', - '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', - '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', - '97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', - '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd07f595b0b6fc920fb0722', - '9778397bd097c36b0b6fc9210c8dc2', '9778397bd19801ec9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f', - '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e', - '97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', - '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bd07f1487f595b0b0bc920fb0722', - '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', - '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', - '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', - '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722', - '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', - '97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', - '97b6b97bd19801ec9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', - '9778397bd097c36b0b6fc9210c91aa', '97b6b97bd197c36c9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', - '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e', - '97b6b7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', - '9778397bd097c36b0b70c9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722', - '7f0e397bd097c35b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', - '7f0e27f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', - '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', - '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', - '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', - '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9274c91aa', - '97b6b7f0e47f531b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', - '9778397bd097c36b0b6fc9210c91aa', '97b6b7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', - '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '977837f0e37f149b0723b0787b0721', - '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c35b0b6fc9210c8dc2', - '977837f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722', - '7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', - '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd', - '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', - '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', - '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', - '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', - '7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', - '977837f0e37f14998082b0723b06bd', '7f07e7f0e37f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', - '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721', - '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5', - '7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f531b0b0bb0b6fb0722', - '7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', - '7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd', - '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', - '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', - '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721', - '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd', - '7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35', - '7ec967f0e37f14998082b0723b06bd', '7f07e7f0e37f14998083b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', - '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14898082b0723b02d5', '7f07e7f0e37f14998082b0787b0721', - '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66aa89801e9808297c35', '665f67f0e37f14898082b0723b02d5', - '7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66a449801e9808297c35', - '665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', - '7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd', - '7f07e7f0e47f531b0723b0b6fb0721', '7f0e26665b66a449801e9808297c35', '665f67f0e37f1489801eb072297c35', - '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722'], - nStr1: ["\u65e5", "\u4e00", "\u4e8c", "\u4e09", "\u56db", "\u4e94", "\u516d", "\u4e03", "\u516b", "\u4e5d", "\u5341"], - nStr2: ["\u521d", "\u5341", "\u5eff", "\u5345"], - nStr3: ["\u6b63", "\u4e8c", "\u4e09", "\u56db", "\u4e94", "\u516d", "\u4e03", "\u516b", "\u4e5d", "\u5341", "\u51ac", "\u814a"], - lYearDays: function (y) { - var i, sum = 348; - for (i = 0x8000; i > 0x8; i >>= 1) { sum += (calendar.lunarInfo[y - 1900] & i) ? 1 : 0; } - return (sum + calendar.leapDays(y)); - }, - leapMonth: function (y) { - return (calendar.lunarInfo[y - 1900] & 0xf); - }, - leapDays: function (y) { - if (calendar.leapMonth(y)) { - return ((calendar.lunarInfo[y - 1900] & 0x10000) ? 30 : 29); - } - return (0); - }, - monthDays: function (y, m) { - if (m > 12 || m < 1) { return -1 } - return ((calendar.lunarInfo[y - 1900] & (0x10000 >> m)) ? 30 : 29); - }, - solarDays: function (y, m) { - if (m > 12 || m < 1) { return -1 } - var ms = m - 1; - if (ms == 1) { - return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28); - } else { - return (calendar.solarMonth[ms]); - } - }, - toGanZhi: function (offset) { - return (calendar.Gan[offset % 10] + calendar.Zhi[offset % 12]); - }, - getTerm: function (y, n) { - if (y < 1900 || y > 2100) { return -1; } - if (n < 1 || n > 24) { return -1; } - var _table = calendar.sTermInfo[y - 1900]; - var _info = [ - parseInt('0x' + _table.substr(0, 5)).toString(), - parseInt('0x' + _table.substr(5, 5)).toString(), - parseInt('0x' + _table.substr(10, 5)).toString(), - parseInt('0x' + _table.substr(15, 5)).toString(), - parseInt('0x' + _table.substr(20, 5)).toString(), - parseInt('0x' + _table.substr(25, 5)).toString() - ]; - var _calday = [ - _info[0].substr(0, 1), - _info[0].substr(1, 2), - _info[0].substr(3, 1), - _info[0].substr(4, 2), - _info[1].substr(0, 1), - _info[1].substr(1, 2), - _info[1].substr(3, 1), - _info[1].substr(4, 2), - _info[2].substr(0, 1), - _info[2].substr(1, 2), - _info[2].substr(3, 1), - _info[2].substr(4, 2), - _info[3].substr(0, 1), - _info[3].substr(1, 2), - _info[3].substr(3, 1), - _info[3].substr(4, 2), - _info[4].substr(0, 1), - _info[4].substr(1, 2), - _info[4].substr(3, 1), - _info[4].substr(4, 2), - _info[5].substr(0, 1), - _info[5].substr(1, 2), - _info[5].substr(3, 1), - _info[5].substr(4, 2), - ]; - return parseInt(_calday[n - 1]); - }, - toChinaMonth: function (m) { - if (m > 12 || m < 1) { return -1 } - var s = calendar.nStr3[m - 1]; - s += "\u6708"; - return s; - }, - toChinaDay: function (d) { - var s; - switch (d) { - case 10: - s = '\u521d\u5341'; - break; - case 20: - s = '\u4e8c\u5341'; - break; - case 30: - s = '\u4e09\u5341'; - break; - default: - s = calendar.nStr2[Math.floor(d / 10)]; - s += calendar.nStr1[d % 10]; - } - return (s); - }, - getAnimal: function (y) { - return calendar.Animals[(y - 4) % 12] - }, - solar2lunar: function (y, m, d) { - if (y < 1900 || y > 2100) { return -1; } - if (y == 1900 && m == 1 && d < 31) { return -1; } - if (!y) { - var objDate = new Date(); - } else { - var objDate = new Date(y, parseInt(m) - 1, d) - } - var i, leap = 0, temp = 0; - var y = objDate.getFullYear(), m = objDate.getMonth() + 1, d = objDate.getDate(); - var offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0, 31)) / 86400000; - for (i = 1900; i < 2101 && offset > 0; i++) { temp = calendar.lYearDays(i); offset -= temp; } - if (offset < 0) { offset += temp; i--; } - var isTodayObj = new Date(), isToday = false; - if (isTodayObj.getFullYear() == y && isTodayObj.getMonth() + 1 == m && isTodayObj.getDate() == d) { - isToday = true; - } - var nWeek = objDate.getDay(), cWeek = calendar.nStr1[nWeek]; - if (nWeek == 0) { nWeek = 7; } - var year = i; - var leap = calendar.leapMonth(i); - var isLeap = false; - for (i = 1; i < 13 && offset > 0; i++) { - if (leap > 0 && i == (leap + 1) && isLeap == false) { - --i; - isLeap = true; temp = calendar.leapDays(year); - } else { - temp = calendar.monthDays(year, i); - } - if (isLeap == true && i == (leap + 1)) { isLeap = false; } - offset -= temp; - } - if (offset == 0 && leap > 0 && i == leap + 1) { - if (isLeap) { - isLeap = false; - } else { - isLeap = true; --i; - } - } - if (offset < 0) { offset += temp; --i; } - var month = i; - var day = offset + 1; - var sm = m - 1; - var term3 = calendar.getTerm(year, 3); - var gzY = calendar.toGanZhi(year - 4); - gzY = calendar.toGanZhi(year - 4); //modify - var firstNode = calendar.getTerm(y, (m * 2 - 1)); - var secondNode = calendar.getTerm(y, (m * 2)); - var gzM = calendar.toGanZhi((y - 1900) * 12 + m + 11); - if (d >= firstNode) { - gzM = calendar.toGanZhi((y - 1900) * 12 + m + 12); - } - var isTerm = false; - var Term = null; - if (firstNode == d) { - isTerm = true; - Term = calendar.solarTerm[m * 2 - 2]; - } - if (secondNode == d) { - isTerm = true; - Term = calendar.solarTerm[m * 2 - 1]; - } - var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10; - var gzD = calendar.toGanZhi(dayCyclical + d - 1); - return { 'lYear': year, 'lMonth': month, 'lDay': day, 'Animal': calendar.getAnimal(year), 'IMonthCn': (isLeap ? "\u95f0" : '') + calendar.toChinaMonth(month), 'IDayCn': calendar.toChinaDay(day), 'cYear': y, 'cMonth': m, 'cDay': d, 'gzYear': gzY, 'gzMonth': gzM, 'gzDay': gzD, 'isToday': isToday, 'isLeap': isLeap, 'nWeek': nWeek, 'ncWeek': "\u661f\u671f" + cWeek, 'isTerm': isTerm, 'Term': Term }; + // A converter from the Gregorian to the Chinese lunar calendar, for 1900 to 2100. + //公历农历转换 + var calendar = { + // One number per lunar year from 1900. Its bits hold the month lengths and the leap month. + lunarInfo: [ + 0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2, + 0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, + 0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, + 0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, + 0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, + 0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, + 0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, + 0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, + 0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, + 0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x055c0, 0x0ab60, 0x096d5, 0x092e0, + 0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, + 0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, + 0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, + 0x05aa0, 0x076a3, 0x096d0, 0x04bd7, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, + 0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, + 0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0, + 0x0a2e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4, + 0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0, + 0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160, + 0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252, + 0x0d520, + ], + // Days in each Gregorian month of a common year. + solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], + // The ten heavenly stems, written as Unicode escapes. + Gan: [ + "\u7532", + "\u4e59", + "\u4e19", + "\u4e01", + "\u620a", + "\u5df1", + "\u5e9a", + "\u8f9b", + "\u58ec", + "\u7678", + ], + // The twelve earthly branches. + Zhi: [ + "\u5b50", + "\u4e11", + "\u5bc5", + "\u536f", + "\u8fb0", + "\u5df3", + "\u5348", + "\u672a", + "\u7533", + "\u9149", + "\u620c", + "\u4ea5", + ], + // The twelve zodiac animals. + Animals: [ + "\u9f20", + "\u725b", + "\u864e", + "\u5154", + "\u9f99", + "\u86c7", + "\u9a6c", + "\u7f8a", + "\u7334", + "\u9e21", + "\u72d7", + "\u732a", + ], + // The names of the 24 solar terms. + solarTerm: [ + "\u5c0f\u5bd2", + "\u5927\u5bd2", + "\u7acb\u6625", + "\u96e8\u6c34", + "\u60ca\u86f0", + "\u6625\u5206", + "\u6e05\u660e", + "\u8c37\u96e8", + "\u7acb\u590f", + "\u5c0f\u6ee1", + "\u8292\u79cd", + "\u590f\u81f3", + "\u5c0f\u6691", + "\u5927\u6691", + "\u7acb\u79cb", + "\u5904\u6691", + "\u767d\u9732", + "\u79cb\u5206", + "\u5bd2\u9732", + "\u971c\u964d", + "\u7acb\u51ac", + "\u5c0f\u96ea", + "\u5927\u96ea", + "\u51ac\u81f3", + ], + // The dates of the solar terms of each year from 1900, in a packed form. + sTermInfo: [ + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c3598082c95f8c965cc920f", + "97bd0b06bdb0722c965ce1cfcc920f", + "b027097bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c359801ec95f8c965cc920f", + "97bd0b06bdb0722c965ce1cfcc920f", + "b027097bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c359801ec95f8c965cc920f", + "97bd0b06bdb0722c965ce1cfcc920f", + "b027097bd097c36b0b6fc9274c91aa", + "9778397bd19801ec9210c965cc920e", + "97b6b97bd19801ec95f8c965cc920f", + "97bd09801d98082c95f8e1cfcc920f", + "97bd097bd097c36b0b6fc9210c8dc2", + "9778397bd197c36c9210c9274c91aa", + "97b6b97bd19801ec95f8c965cc920e", + "97bd09801d98082c95f8e1cfcc920f", + "97bd097bd097c36b0b6fc9210c8dc2", + "9778397bd097c36c9210c9274c91aa", + "97b6b97bd19801ec95f8c965cc920e", + "97bcf97c3598082c95f8e1cfcc920f", + "97bd097bd097c36b0b6fc9210c8dc2", + "9778397bd097c36c9210c9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c3598082c95f8c965cc920f", + "97bd097bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c3598082c95f8c965cc920f", + "97bd097bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c359801ec95f8c965cc920f", + "97bd097bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c359801ec95f8c965cc920f", + "97bd097bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf97c359801ec95f8c965cc920f", + "97bd097bd07f595b0b6fc920fb0722", + "9778397bd097c36b0b6fc9210c8dc2", + "9778397bd19801ec9210c9274c920e", + "97b6b97bd19801ec95f8c965cc920f", + "97bd07f5307f595b0b0bc920fb0722", + "7f0e397bd097c36b0b6fc9210c8dc2", + "9778397bd097c36c9210c9274c920e", + "97b6b97bd19801ec95f8c965cc920f", + "97bd07f5307f595b0b0bc920fb0722", + "7f0e397bd097c36b0b6fc9210c8dc2", + "9778397bd097c36c9210c9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bd07f1487f595b0b0bc920fb0722", + "7f0e397bd097c36b0b6fc9210c8dc2", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf7f1487f595b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf7f1487f595b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf7f1487f531b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c965cc920e", + "97bcf7f1487f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b97bd19801ec9210c9274c920e", + "97bcf7f0e47f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "9778397bd097c36b0b6fc9210c91aa", + "97b6b97bd197c36c9210c9274c920e", + "97bcf7f0e47f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "9778397bd097c36b0b6fc9210c8dc2", + "9778397bd097c36c9210c9274c920e", + "97b6b7f0e47f531b0723b0b6fb0722", + "7f0e37f5307f595b0b0bc920fb0722", + "7f0e397bd097c36b0b6fc9210c8dc2", + "9778397bd097c36b0b70c9274c91aa", + "97b6b7f0e47f531b0723b0b6fb0721", + "7f0e37f1487f595b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc9210c8dc2", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f595b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "9778397bd097c36b0b6fc9274c91aa", + "97b6b7f0e47f531b0723b0787b0721", + "7f0e27f0e47f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "9778397bd097c36b0b6fc9210c91aa", + "97b6b7f0e47f149b0723b0787b0721", + "7f0e27f0e47f531b0723b0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "9778397bd097c36b0b6fc9210c8dc2", + "977837f0e37f149b0723b0787b0721", + "7f07e7f0e47f531b0723b0b6fb0722", + "7f0e37f5307f595b0b0bc920fb0722", + "7f0e397bd097c35b0b6fc9210c8dc2", + "977837f0e37f14998082b0787b0721", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e37f1487f595b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc9210c8dc2", + "977837f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "977837f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd097c35b0b6fc920fb0722", + "977837f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "977837f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "977837f0e37f14998082b0787b06bd", + "7f07e7f0e47f149b0723b0787b0721", + "7f0e27f0e47f531b0b0bb0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "977837f0e37f14998082b0723b06bd", + "7f07e7f0e37f149b0723b0787b0721", + "7f0e27f0e47f531b0723b0b6fb0722", + "7f0e397bd07f595b0b0bc920fb0722", + "977837f0e37f14898082b0723b02d5", + "7ec967f0e37f14998082b0787b0721", + "7f07e7f0e47f531b0723b0b6fb0722", + "7f0e37f1487f595b0b0bb0b6fb0722", + "7f0e37f0e37f14898082b0723b02d5", + "7ec967f0e37f14998082b0787b0721", + "7f07e7f0e47f531b0723b0b6fb0722", + "7f0e37f1487f531b0b0bb0b6fb0722", + "7f0e37f0e37f14898082b0723b02d5", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e37f1487f531b0b0bb0b6fb0722", + "7f0e37f0e37f14898082b072297c35", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e37f0e37f14898082b072297c35", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e37f0e366aa89801eb072297c35", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f149b0723b0787b0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + "7f0e37f0e366aa89801eb072297c35", + "7ec967f0e37f14998082b0723b06bd", + "7f07e7f0e47f149b0723b0787b0721", + "7f0e27f0e47f531b0723b0b6fb0722", + "7f0e37f0e366aa89801eb072297c35", + "7ec967f0e37f14998082b0723b06bd", + "7f07e7f0e37f14998083b0787b0721", + "7f0e27f0e47f531b0723b0b6fb0722", + "7f0e37f0e366aa89801eb072297c35", + "7ec967f0e37f14898082b0723b02d5", + "7f07e7f0e37f14998082b0787b0721", + "7f07e7f0e47f531b0723b0b6fb0722", + "7f0e36665b66aa89801e9808297c35", + "665f67f0e37f14898082b0723b02d5", + "7ec967f0e37f14998082b0787b0721", + "7f07e7f0e47f531b0723b0b6fb0722", + "7f0e36665b66a449801e9808297c35", + "665f67f0e37f14898082b0723b02d5", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e36665b66a449801e9808297c35", + "665f67f0e37f14898082b072297c35", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e26665b66a449801e9808297c35", + "665f67f0e37f1489801eb072297c35", + "7ec967f0e37f14998082b0787b06bd", + "7f07e7f0e47f531b0723b0b6fb0721", + "7f0e27f1487f531b0b0bb0b6fb0722", + ], + nStr1: [ + "\u65e5", + "\u4e00", + "\u4e8c", + "\u4e09", + "\u56db", + "\u4e94", + "\u516d", + "\u4e03", + "\u516b", + "\u4e5d", + "\u5341", + ], + nStr2: ["\u521d", "\u5341", "\u5eff", "\u5345"], + nStr3: [ + "\u6b63", + "\u4e8c", + "\u4e09", + "\u56db", + "\u4e94", + "\u516d", + "\u4e03", + "\u516b", + "\u4e5d", + "\u5341", + "\u51ac", + "\u814a", + ], + // Days in lunar year y. + lYearDays: function (y) { + var i, + sum = 348; + for (i = 0x8000; i > 0x8; i >>= 1) { + sum += calendar.lunarInfo[y - 1900] & i ? 1 : 0; + } + return sum + calendar.leapDays(y); + }, + // The leap month of lunar year y (1 to 12), or 0 when it has none. + leapMonth: function (y) { + return calendar.lunarInfo[y - 1900] & 0xf; + }, + // Days in that leap month, or 0. + leapDays: function (y) { + if (calendar.leapMonth(y)) { + return calendar.lunarInfo[y - 1900] & 0x10000 ? 30 : 29; + } + return 0; + }, + // Days in month m of lunar year y: 29 or 30. + monthDays: function (y, m) { + if (m > 12 || m < 1) { + return -1; + } + return calendar.lunarInfo[y - 1900] & (0x10000 >> m) ? 30 : 29; + }, + // Days in month m of Gregorian year y. + solarDays: function (y, m) { + if (m > 12 || m < 1) { + return -1; + } + var ms = m - 1; + if (ms == 1) { + return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 ? 29 : 28; + } else { + return calendar.solarMonth[ms]; + } + }, + // The stem-branch name for a position in the cycle of 60. + toGanZhi: function (offset) { + return calendar.Gan[offset % 10] + calendar.Zhi[offset % 12]; + }, + // The day of the month on which solar term n (1 to 24) of year y falls. + getTerm: function (y, n) { + if (y < 1900 || y > 2100) { + return -1; + } + if (n < 1 || n > 24) { + return -1; + } + var _table = calendar.sTermInfo[y - 1900]; + var _info = [ + parseInt("0x" + _table.substr(0, 5)).toString(), + parseInt("0x" + _table.substr(5, 5)).toString(), + parseInt("0x" + _table.substr(10, 5)).toString(), + parseInt("0x" + _table.substr(15, 5)).toString(), + parseInt("0x" + _table.substr(20, 5)).toString(), + parseInt("0x" + _table.substr(25, 5)).toString(), + ]; + var _calday = [ + _info[0].substr(0, 1), + _info[0].substr(1, 2), + _info[0].substr(3, 1), + _info[0].substr(4, 2), + _info[1].substr(0, 1), + _info[1].substr(1, 2), + _info[1].substr(3, 1), + _info[1].substr(4, 2), + _info[2].substr(0, 1), + _info[2].substr(1, 2), + _info[2].substr(3, 1), + _info[2].substr(4, 2), + _info[3].substr(0, 1), + _info[3].substr(1, 2), + _info[3].substr(3, 1), + _info[3].substr(4, 2), + _info[4].substr(0, 1), + _info[4].substr(1, 2), + _info[4].substr(3, 1), + _info[4].substr(4, 2), + _info[5].substr(0, 1), + _info[5].substr(1, 2), + _info[5].substr(3, 1), + _info[5].substr(4, 2), + ]; + return parseInt(_calday[n - 1]); + }, + // A lunar month as Chinese text. + toChinaMonth: function (m) { + if (m > 12 || m < 1) { + return -1; + } + var s = calendar.nStr3[m - 1]; + s += "\u6708"; + return s; + }, + // A lunar day as Chinese text. + toChinaDay: function (d) { + var s; + switch (d) { + case 10: + s = "\u521d\u5341"; + break; + case 20: + s = "\u4e8c\u5341"; + break; + case 30: + s = "\u4e09\u5341"; + break; + default: + s = calendar.nStr2[Math.floor(d / 10)]; + s += calendar.nStr1[d % 10]; + } + return s; + }, + // The zodiac animal of a year. + getAnimal: function (y) { + return calendar.Animals[(y - 4) % 12]; + }, + // Convert a Gregorian date. A sample of the result is near the end of this file. + solar2lunar: function (y, m, d) { + if (y < 1900 || y > 2100) { + return -1; + } + if (y == 1900 && m == 1 && d < 31) { + return -1; + } + if (!y) { + var objDate = new Date(); + } else { + var objDate = new Date(y, parseInt(m) - 1, d); + } + var i, + leap = 0, + temp = 0; + var y = objDate.getFullYear(), + m = objDate.getMonth() + 1, + d = objDate.getDate(); + // Days from 31 January 1900, the first day of lunar year 1900, to the date. + var offset = + (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - + Date.UTC(1900, 0, 31)) / + 86400000; + // Take off whole lunar years, then whole lunar months; what is left is the day. + for (i = 1900; i < 2101 && offset > 0; i++) { + temp = calendar.lYearDays(i); + offset -= temp; + } + if (offset < 0) { + offset += temp; + i--; + } + var isTodayObj = new Date(), + isToday = false; + if ( + isTodayObj.getFullYear() == y && + isTodayObj.getMonth() + 1 == m && + isTodayObj.getDate() == d + ) { + isToday = true; + } + var nWeek = objDate.getDay(), + cWeek = calendar.nStr1[nWeek]; + if (nWeek == 0) { + nWeek = 7; + } + var year = i; + var leap = calendar.leapMonth(i); + var isLeap = false; + for (i = 1; i < 13 && offset > 0; i++) { + if (leap > 0 && i == leap + 1 && isLeap == false) { + --i; + isLeap = true; + temp = calendar.leapDays(year); + } else { + temp = calendar.monthDays(year, i); } + if (isLeap == true && i == leap + 1) { + isLeap = false; + } + offset -= temp; + } + if (offset == 0 && leap > 0 && i == leap + 1) { + if (isLeap) { + isLeap = false; + } else { + isLeap = true; + --i; + } + } + if (offset < 0) { + offset += temp; + --i; + } + var month = i; + var day = offset + 1; + var sm = m - 1; + var term3 = calendar.getTerm(year, 3); + var gzY = calendar.toGanZhi(year - 4); + gzY = calendar.toGanZhi(year - 4); //modify + var firstNode = calendar.getTerm(y, m * 2 - 1); + var secondNode = calendar.getTerm(y, m * 2); + var gzM = calendar.toGanZhi((y - 1900) * 12 + m + 11); + if (d >= firstNode) { + gzM = calendar.toGanZhi((y - 1900) * 12 + m + 12); + } + var isTerm = false; + var Term = null; + if (firstNode == d) { + isTerm = true; + Term = calendar.solarTerm[m * 2 - 2]; + } + if (secondNode == d) { + isTerm = true; + Term = calendar.solarTerm[m * 2 - 1]; + } + var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10; + var gzD = calendar.toGanZhi(dayCyclical + d - 1); + return { + lYear: year, + lMonth: month, + lDay: day, + Animal: calendar.getAnimal(year), + IMonthCn: (isLeap ? "\u95f0" : "") + calendar.toChinaMonth(month), + IDayCn: calendar.toChinaDay(day), + cYear: y, + cMonth: m, + cDay: d, + gzYear: gzY, + gzMonth: gzM, + gzDay: gzD, + isToday: isToday, + isLeap: isLeap, + nWeek: nWeek, + ncWeek: "\u661f\u671f" + cWeek, + isTerm: isTerm, + Term: Term, + }; + }, + }; + // Festivals on a fixed Gregorian date. The key is month and day (MMDD). + //公历节日 + var _festival1 = { + "0101": "元旦节", + "0202": "世界湿地日", + "0210": "国际气象节", + "0214": "情人节", + "0301": "国际海豹日", + "0303": "全国爱耳日", + "0305": "学雷锋纪念日", + "0308": "妇女节", + "0312": "植树节", + "0314": "国际警察日", + "0315": "消费者权益日", + "0317": "中国国医节 国际航海日", + "0321": "世界森林日 消除种族歧视国际日 世界儿歌日", + "0322": "世界水日", + "0323": "世界气象日", + "0324": "世界防治结核病日", + "0325": "全国中小学生安全教育日", + "0401": "愚人节", + "0407": "世界卫生日", + "0422": "世界地球日", + "0423": "世界图书和版权日", + "0424": "亚非新闻工作者日", + "0501": "劳动节", + "0504": "青年节", + "0515": "防治碘缺乏病日", + "0508": "世界红十字日", + "0512": "国际护士节", + "0515": "国际家庭日", + "0517": "世界电信日", + "0518": "国际博物馆日", + "0520": "全国学生营养日", + "0522": "国际生物多样性日", + "0531": "世界无烟日", + "0601": "国际儿童节 世界牛奶日", + "0605": "世界环境日", + "0606": "全国爱眼日", + "0617": "防治荒漠化和干旱日", + "0623": "国际奥林匹克日", + "0625": "全国土地日", + "0626": "国际禁毒日", + "0701": "建党节 香港回归纪念日", + "0702": "国际体育记者日", + "0711": "世界人口日 航海日", + "0801": "建军节", + "0808": "中国男子节(爸爸节)", + "0903": "抗日战争胜利纪念日", + "0908": "国际扫盲日 国际新闻工作者日", + "0910": "教师节", + "0916": "国际臭氧层保护日", + "0918": "九·一八事变纪念日", + "0920": "国际爱牙日", + "0927": "世界旅游日", + 1001: "国庆节 国际音乐日 国际老人节", + 1002: "国际非暴力日 国际和平与民主自由斗争日", + 1004: "世界动物日", + 1006: "老人节", + 1008: "全国高血压日", + 1005: "国际教师节", + 1009: "世界邮政日", + 1010: "辛亥革命纪念日 世界精神卫生日", + 1013: "世界保健日 国际减灾日", + 1014: "世界标准日", + 1015: "国际盲人节(白手杖节)", + 1016: "世界粮食日", + 1017: "世界消除贫困日", + 1022: "世界传统医药日", + 1024: "联合国日 世界发展信息日", + 1031: "世界勤俭日", + 1107: "十月社会主义革命纪念日", + 1108: "中国记者日", + 1109: "全国消防安全宣传教育日", + 1110: "世界青年节", + 1111: "国际科学与和平周(本日所属的一周)", + 1112: "孙中山诞辰纪念日", + 1114: "联合国糖尿病日", + 1117: "国际大学生节", + 1121: "世界问候日 世界电视日", + 1129: "国际声援巴勒斯坦人民国际日", + 1201: "世界艾滋病日", + 1203: "世界残疾人日", + 1204: "宪法日", + 1205: "国际志愿人员日", + 1209: "世界足球日", + 1210: "世界人权日", + 1212: "西安事变纪念日", + 1213: "南京大屠杀纪念日", + 1220: "澳门回归纪念", + 1221: "国际篮球日", + 1224: "平安夜", + 1225: "圣诞节", + 1226: "毛泽东诞辰纪念日", + }; + // Festivals on a certain weekday of a month. The key is the month, the number of the + // week (5 = the last one) and the weekday (0 = Sunday). + //某月的第几个星期几,第3位为5表示最后一星期 + var _festival2 = { + "0110": "黑人日", + "0150": "世界麻风日", + "0440": "世界儿童日", + "0520": "国际母亲节", + "0532": "国际牛奶日", + "0530": "全国助残日", + "0630": "父亲节", + "0711": "世界建筑日", + "0730": "被奴役国家周", + "0936": "世界清洁地球日", + "0932": "国际和平日", + "0940": "国际聋人节", + 1011: "国际住房日", + 1024: "世界视觉日", + 1144: "感恩节", + 1220: "国际儿童电视广播日", + }; + // Festivals on a lunar date. The key is the lunar month and day (MMDD). + //农历节日 + var _festival3 = { + "0101": "春节", + "0102": "初二", + "0103": "初三", + "0115": "元宵节", + "0202": "龙抬头节", + "0323": "妈祖生辰", + "0505": "端午节", + "0707": "七夕节", + "0715": "中元节", + "0815": "中秋节", + "0909": "重阳节", + 1208: "腊八节", + 1223: "小年", + "0100": "除夕", + }; + // Holiday arrangements per year, by MMDD: 1 = day off, 0 = working day. + //假日安排数据 + var _holiday = { + 2011: { + "0402": 0, + "0403": 1, + "0404": 1, + "0405": 1, + "0430": 1, + "0501": 1, + "0502": 1, + "0604": 1, + "0605": 1, + "0606": 1, + "0910": 1, + "0911": 1, + "0912": 1, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1008: 0, + 1009: 0, + 1231: 0, + }, + 2012: { + "0101": 1, + "0102": 1, + "0103": 1, + "0121": 0, + "0122": 1, + "0123": 1, + "0124": 1, + "0125": 1, + "0126": 1, + "0127": 1, + "0128": 1, + "0129": 0, + "0331": 0, + "0401": 0, + "0402": 1, + "0403": 1, + "0404": 1, + "0428": 0, + "0429": 1, + "0430": 1, + "0501": 1, + "0622": 1, + "0623": 1, + "0624": 1, + "0929": 0, + "0930": 1, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + }, + 2013: { + "0101": 1, + "0102": 1, + "0103": 1, + "0105": 0, + "0106": 0, + "0209": 1, + "0210": 1, + "0211": 1, + "0212": 1, + "0213": 1, + "0214": 1, + "0215": 1, + "0216": 0, + "0217": 0, + "0404": 1, + "0405": 1, + "0406": 1, + "0407": 0, + "0427": 0, + "0428": 0, + "0429": 1, + "0430": 1, + "0501": 1, + "0608": 0, + "0609": 0, + "0610": 1, + "0611": 1, + "0612": 1, + "0919": 1, + "0920": 1, + "0921": 1, + "0922": 0, + "0929": 0, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1012: 0, + }, + 2014: { + "0101": 1, + "0126": 0, + "0131": 1, + "0201": 1, + "0202": 1, + "0203": 1, + "0203": 1, + "0204": 1, + "0205": 1, + "0206": 1, + "0208": 0, + "0405": 1, + "0406": 1, + "0407": 1, + "0501": 1, + "0502": 1, + "0503": 1, + "0504": 0, + "0531": 1, + "0601": 1, + "0602": 1, + "0908": 1, + "0928": 0, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1011: 0, + }, + 2015: { + "0101": 1, + "0102": 1, + "0103": 1, + "0104": 0, + "0215": 0, + "0218": 1, + "0219": 1, + "0220": 1, + "0221": 1, + "0222": 1, + "0223": 1, + "0224": 1, + "0228": 0, + "0404": 1, + "0405": 1, + "0406": 1, + "0501": 1, + "0502": 1, + "0503": 1, + "0620": 1, + "0621": 1, + "0622": 1, + "0903": 1, + "0904": 1, + "0905": 1, + "0906": 0, + "0927": 1, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1010: 0, + }, + 2016: { + "0101": 1, + "0102": 1, + "0103": 1, + "0206": 0, + "0207": 1, + "0208": 1, + "0209": 1, + "0210": 1, + "0211": 1, + "0212": 1, + "0213": 1, + "0214": 0, + "0402": 1, + "0403": 1, + "0404": 1, + "0430": 1, + "0501": 1, + "0502": 1, + "0609": 1, + "0610": 1, + "0611": 1, + "0612": 0, + "0915": 1, + "0916": 1, + "0917": 1, + "0918": 0, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1008: 0, + 1009: 0, + }, + 2017: { + "0101": 1, + "0102": 1, + "0122": 0, + "0127": 1, + "0128": 1, + "0129": 1, + "0130": 1, + "0131": 1, + "0201": 1, + "0202": 1, + "0204": 0, + "0401": 0, + "0402": 1, + "0403": 1, + "0404": 1, + "0429": 1, + "0430": 1, + "0501": 1, + "0527": 0, + "0528": 1, + "0529": 1, + "0530": 1, + "0930": 0, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1008: 1, + 1230: 1, + 1231: 1, + }, + 2018: { + "0101": 1, + "0211": 0, + "0215": 1, + "0216": 1, + "0217": 1, + "0218": 1, + "0219": 1, + "0220": 1, + "0221": 1, + "0224": 0, + "0405": 1, + "0406": 1, + "0407": 1, + "0408": 0, + "0428": 0, + "0429": 1, + "0430": 1, + "0501": 1, + "0616": 1, + "0617": 1, + "0618": 1, + "0922": 1, + "0923": 1, + "0924": 1, + "0929": 0, + "0930": 0, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1229: 0, + 1230: 1, + 1231: 1, + }, + 2019: { + "0101": 1, + "0202": 0, + "0203": 0, + "0204": 1, + "0205": 1, + "0206": 1, + "0207": 1, + "0208": 1, + "0209": 1, + "0210": 1, + "0405": 1, + "0406": 1, + "0407": 1, + "0428": 0, + "0501": 1, + "0502": 1, + "0503": 1, + "0504": 1, + "0505": 0, + "0607": 1, + "0608": 1, + "0609": 1, + "0913": 1, + "0914": 1, + "0915": 1, + "0929": 0, + 1001: 1, + 1002: 1, + 1003: 1, + 1004: 1, + 1005: 1, + 1006: 1, + 1007: 1, + 1012: 0, + }, + }; + // A date as { year, month, day, week }; `week` is the weekday, 0 = Sunday. Default: today. + //获取日期数据 + var getDateObj = function (year, month, day) { + var date = arguments.length && year ? new Date(year, month - 1, day) : new Date(); + return { + year: date.getFullYear(), + month: date.getMonth() + 1, + day: date.getDate(), + week: date.getDay(), }; - //公历节日 - var _festival1 = { - '0101': '元旦节', - '0202': '世界湿地日', - '0210': '国际气象节', - '0214': '情人节', - '0301': '国际海豹日', - '0303': '全国爱耳日', - '0305': '学雷锋纪念日', - '0308': '妇女节', - '0312': '植树节', - '0314': '国际警察日', - '0315': '消费者权益日', - '0317': '中国国医节 国际航海日', - '0321': '世界森林日 消除种族歧视国际日 世界儿歌日', - '0322': '世界水日', - '0323': '世界气象日', - '0324': '世界防治结核病日', - '0325': '全国中小学生安全教育日', - '0401': '愚人节', - '0407': '世界卫生日', - '0422': '世界地球日', - '0423': '世界图书和版权日', - '0424': '亚非新闻工作者日', - '0501': '劳动节', - '0504': '青年节', - '0515': '防治碘缺乏病日', - '0508': '世界红十字日', - '0512': '国际护士节', - '0515': '国际家庭日', - '0517': '世界电信日', - '0518': '国际博物馆日', - '0520': '全国学生营养日', - '0522': '国际生物多样性日', - '0531': '世界无烟日', - '0601': '国际儿童节 世界牛奶日', - '0605': '世界环境日', - '0606': '全国爱眼日', - '0617': '防治荒漠化和干旱日', - '0623': '国际奥林匹克日', - '0625': '全国土地日', - '0626': '国际禁毒日', - '0701': '建党节 香港回归纪念日', - '0702': '国际体育记者日', - '0711': '世界人口日 航海日', - '0801': '建军节', - '0808': '中国男子节(爸爸节)', - '0903': '抗日战争胜利纪念日', - '0908': '国际扫盲日 国际新闻工作者日', - '0910': '教师节', - '0916': '国际臭氧层保护日', - '0918': '九·一八事变纪念日', - '0920': '国际爱牙日', - '0927': '世界旅游日', - '1001': '国庆节 国际音乐日 国际老人节', - '1002': '国际非暴力日 国际和平与民主自由斗争日', - '1004': '世界动物日', - '1006': '老人节', - '1008': '全国高血压日', - '1005': '国际教师节', - '1009': '世界邮政日', - '1010': '辛亥革命纪念日 世界精神卫生日', - '1013': '世界保健日 国际减灾日', - '1014': '世界标准日', - '1015': '国际盲人节(白手杖节)', - '1016': '世界粮食日', - '1017': '世界消除贫困日', - '1022': '世界传统医药日', - '1024': '联合国日 世界发展信息日', - '1031': '世界勤俭日', - '1107': '十月社会主义革命纪念日', - '1108': '中国记者日', - '1109': '全国消防安全宣传教育日', - '1110': '世界青年节', - '1111': '国际科学与和平周(本日所属的一周)', - '1112': '孙中山诞辰纪念日', - '1114': '联合国糖尿病日', - '1117': '国际大学生节', - '1121': '世界问候日 世界电视日', - '1129': '国际声援巴勒斯坦人民国际日', - '1201': '世界艾滋病日', - '1203': '世界残疾人日', - '1204': '宪法日', - '1205': '国际志愿人员日', - '1209': '世界足球日', - '1210': '世界人权日', - '1212': '西安事变纪念日', - '1213': '南京大屠杀纪念日', - '1220': '澳门回归纪念', - '1221': '国际篮球日', - '1224': '平安夜', - '1225': '圣诞节', - '1226': '毛泽东诞辰纪念日' - }; - //某月的第几个星期几,第3位为5表示最后一星期 - var _festival2 = { - '0110': '黑人日', - '0150': '世界麻风日', - '0440': '世界儿童日', - '0520': '国际母亲节', - '0532': '国际牛奶日', - '0530': '全国助残日', - '0630': '父亲节', - '0711': '世界建筑日', - '0730': '被奴役国家周', - '0936': '世界清洁地球日', - '0932': '国际和平日', - '0940': '国际聋人节', - '1011': '国际住房日', - '1024': '世界视觉日', - '1144': '感恩节', - '1220': '国际儿童电视广播日' - }; - //农历节日 - var _festival3 = { - '0101': '春节', - '0102': '初二', - '0103': '初三', - '0115': '元宵节', - '0202': '龙抬头节', - '0323': '妈祖生辰', - '0505': '端午节', - '0707': '七夕节', - '0715': '中元节', - '0815': '中秋节', - '0909': '重阳节', - '1208': '腊八节', - '1223': '小年', - '0100': '除夕' - }; - //假日安排数据 - var _holiday = { - '2011': { '0402': 0, '0403': 1, '0404': 1, '0405': 1, '0430': 1, '0501': 1, '0502': 1, '0604': 1, '0605': 1, '0606': 1, '0910': 1, '0911': 1, '0912': 1, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1008': 0, '1009': 0, '1231': 0 }, - '2012': { - '0101': 1, '0102': 1, '0103': 1, '0121': 0, '0122': 1, '0123': 1, '0124': 1, '0125': 1, '0126': 1, '0127': 1, '0128': 1, '0129': 0, '0331': 0, '0401' - : 0, '0402': 1, '0403': 1, '0404': 1, '0428': 0, '0429': 1, '0430': 1, '0501': 1, '0622': 1, '0623': 1, '0624': 1, '0929': 0, '0930': 1, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1 - }, - '2013': { '0101': 1, '0102': 1, '0103': 1, '0105': 0, '0106': 0, '0209': 1, '0210': 1, '0211': 1, '0212': 1, '0213': 1, '0214': 1, '0215': 1, '0216': 0, '0217': 0, '0404': 1, '0405': 1, '0406': 1, '0407': 0, '0427': 0, '0428': 0, '0429': 1, '0430': 1, '0501': 1, '0608': 0, '0609': 0, '0610': 1, '0611': 1, '0612': 1, '0919': 1, '0920': 1, '0921': 1, '0922': 0, '0929': 0, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1012': 0 }, - '2014': { '0101': 1, '0126': 0, '0131': 1, '0201': 1, '0202': 1, '0203': 1, '0203': 1, '0204': 1, '0205': 1, '0206': 1, '0208': 0, '0405': 1, '0406': 1, '0407': 1, '0501': 1, '0502': 1, '0503': 1, '0504': 0, '0531': 1, '0601': 1, '0602': 1, '0908': 1, '0928': 0, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1011': 0 }, - '2015': { '0101': 1, '0102': 1, '0103': 1, '0104': 0, '0215': 0, '0218': 1, '0219': 1, '0220': 1, '0221': 1, '0222': 1, '0223': 1, '0224': 1, '0228': 0, '0404': 1, '0405': 1, '0406': 1, '0501': 1, '0502': 1, '0503': 1, '0620': 1, '0621': 1, '0622': 1, '0903': 1, '0904': 1, '0905': 1, '0906': 0, '0927': 1, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1010': 0 }, - '2016': { '0101': 1, '0102': 1, '0103': 1, '0206': 0, '0207': 1, '0208': 1, '0209': 1, '0210': 1, '0211': 1, '0212': 1, '0213': 1, '0214': 0, '0402': 1, '0403': 1, '0404': 1, '0430': 1, '0501': 1, '0502': 1, '0609': 1, '0610': 1, '0611': 1, '0612': 0, '0915': 1, '0916': 1, '0917': 1, '0918': 0, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1008': 0, '1009': 0 }, - '2017': { '0101': 1, '0102': 1, '0122': 0, '0127': 1, '0128': 1, '0129': 1, '0130': 1, '0131': 1, '0201': 1, '0202': 1, '0204': 0, '0401': 0, '0402': 1, '0403': 1, '0404': 1, '0429': 1, '0430': 1, '0501': 1, '0527': 0, '0528': 1, '0529': 1, '0530': 1, '0930': 0, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1008': 1, '1230': 1, '1231': 1 }, - '2018': { '0101': 1, '0211': 0, '0215': 1, '0216': 1, '0217': 1, '0218': 1, '0219': 1, '0220': 1, '0221': 1, '0224': 0, '0405': 1, '0406': 1, '0407': 1, '0408': 0, '0428': 0, '0429': 1, '0430': 1, '0501': 1, '0616': 1, '0617': 1, '0618': 1, '0922': 1, '0923': 1, '0924': 1, '0929': 0, '0930': 0, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1229': 0, '1230': 1, '1231': 1 }, - '2019': { '0101': 1, '0202': 0, '0203': 0, '0204': 1, '0205': 1, '0206': 1, '0207': 1, '0208': 1, '0209': 1, '0210': 1, '0405': 1, '0406': 1, '0407': 1, '0428': 0, '0501': 1, '0502': 1, '0503': 1, '0504': 1, '0505': 0, '0607': 1, '0608': 1, '0609': 1, '0913': 1, '0914': 1, '0915': 1, '0929': 0, '1001': 1, '1002': 1, '1003': 1, '1004': 1, '1005': 1, '1006': 1, '1007': 1, '1012': 0 } - }; - //获取日期数据 - var getDateObj = function (year, month, day) { - var date = arguments.length && year ? new Date(year, month - 1, day) : new Date(); - return { - 'year': date.getFullYear(), - 'month': date.getMonth() + 1, - 'day': date.getDate(), - 'week': date.getDay() - }; - }; - //当天 - var _today = getDateObj(); - //获取当月天数 - var getMonthDays = function (obj) { - var day = new Date(obj.year, obj.month, 0); - return day.getDate(); + }; + //当天 + var _today = getDateObj(); + // Days in the Gregorian month of a date. + //获取当月天数 + var getMonthDays = function (obj) { + var day = new Date(obj.year, obj.month, 0); + return day.getDate(); + }; + if (!String.prototype.trim) { + String.prototype.trim = function () { + return this.replace(/^\s+|\s+$/g, ""); }; - if (!String.prototype.trim) { - String.prototype.trim = function () { - return this.replace(/^\s+|\s+$/g, ''); - }; + } + // Everything about one day: the lunar date, plus `festival` and `sign`. + //获取某天日期信息 + var getDateInfo = function (obj) { + var info = calendar.solar2lunar(obj.year, obj.month, obj.day); + var cMonth = info.cMonth > 9 ? "" + info.cMonth : "0" + info.cMonth; + var cDay = info.cDay > 9 ? "" + info.cDay : "0" + info.cDay; + var lMonth = info.lMonth > 9 ? "" + info.lMonth : "0" + info.lMonth; + var lDay = info.lDay > 9 ? "" + info.lDay : "0" + info.lDay; + var code1 = cMonth + cDay; + var code2 = cMonth + Math.ceil(info.cDay / 7) + (info.nWeek % 7); + var code3 = lMonth + lDay; + var days = getMonthDays(obj); + //节日信息 + info["festival"] = ""; + if (_festival3[code3]) { + info["festival"] += _festival3[code3]; } - //获取某天日期信息 - var getDateInfo = function (obj) { - var info = calendar.solar2lunar(obj.year, obj.month, obj.day); - var cMonth = info.cMonth > 9 ? '' + info.cMonth : '0' + info.cMonth; - var cDay = info.cDay > 9 ? '' + info.cDay : '0' + info.cDay; - var lMonth = info.lMonth > 9 ? '' + info.lMonth : '0' + info.lMonth; - var lDay = info.lDay > 9 ? '' + info.lDay : '0' + info.lDay; - var code1 = cMonth + cDay; - var code2 = cMonth + Math.ceil(info.cDay / 7) + info.nWeek % 7; - var code3 = lMonth + lDay; - var days = getMonthDays(obj); - //节日信息 - info['festival'] = ''; - if (_festival3[code3]) { - info['festival'] += _festival3[code3]; - } - if (_festival1[code1]) { - info['festival'] += ' ' + _festival1[code1]; - } - if (_festival2[code2]) { - info['festival'] += ' ' + _festival2[code2]; - } - if (obj['day'] + 7 > days) { - var code4 = cMonth + 5 + info.nWeek % 7; - if (code4 != code2 && _festival2[code4]) { - info['festival'] += ' ' + _festival2[code4]; - } - } - info['festival'] = info['festival'].trim(); - //放假、调休等标记 - info['sign'] = ''; - if (_holiday[info.cYear]) { - var holiday = _holiday[info.cYear]; - if (typeof holiday[code1] != 'undefined') { - info['sign'] = holiday[code1] ? 'holiday' : 'work'; - } - } - if (info.cYear == _today.year && info.cMonth == _today.month && info.cDay == _today.day) { - info['sign'] = 'today'; - } - return info; + if (_festival1[code1]) { + info["festival"] += " " + _festival1[code1]; + } + if (_festival2[code2]) { + info["festival"] += " " + _festival2[code2]; + } + if (obj["day"] + 7 > days) { + var code4 = cMonth + 5 + (info.nWeek % 7); + if (code4 != code2 && _festival2[code4]) { + info["festival"] += " " + _festival2[code4]; + } + } + info["festival"] = info["festival"].trim(); + //放假、调休等标记 + info["sign"] = ""; + if (_holiday[info.cYear]) { + var holiday = _holiday[info.cYear]; + if (typeof holiday[code1] != "undefined") { + info["sign"] = holiday[code1] ? "holiday" : "work"; + } + } + if (info.cYear == _today.year && info.cMonth == _today.month && info.cDay == _today.day) { + info["sign"] = "today"; + } + return info; + }; + // This function becomes getLunarData. It returns `date`, the info of the given day, and + // `data`, the days of its month padded to full weeks. + //获取日历信息 + return function (date) { + var date = date || _today; + var first = getDateObj(date["year"], date["month"], 1); //当月第一天 + var days = getMonthDays(date); //当月天数 + var data = []; //日历信息 + var obj = {}; + //上月日期 + for (var i = first["week"]; i > 0; i--) { + obj = getDateObj(first["year"], first["month"], first["day"] - i); + var info = getDateInfo(obj); + info["disabled"] = 1; + data.push(info); + } + //当月日期 + for (var i = 0; i < days; i++) { + obj = { + year: first["year"], + month: first["month"], + day: first["day"] + i, + week: (first["week"] + i) % 7, + }; + var info = getDateInfo(obj); + info["disabled"] = 0; + data.push(info); + } + //下月日期 + var last = obj; + for (var i = 1; last["week"] + i < 7; i++) { + obj = getDateObj(last["year"], last["month"], last["day"] + i); + var info = getDateInfo(obj); + info["disabled"] = 1; + data.push(info); + } + return { + date: getDateInfo(date), //当前日历选中日期 + data: data, }; - //获取日历信息 - return (function (date) { - var date = date || _today; - var first = getDateObj(date['year'], date['month'], 1); //当月第一天 - var days = getMonthDays(date); //当月天数 - var data = []; //日历信息 - var obj = {}; - //上月日期 - for (var i = first['week']; i > 0; i--) { - obj = getDateObj(first['year'], first['month'], first['day'] - i); - var info = getDateInfo(obj); - info['disabled'] = 1; - data.push(info); - } - //当月日期 - for (var i = 0; i < days; i++) { - obj = { - 'year': first['year'], - 'month': first['month'], - 'day': first['day'] + i, - 'week': (first['week'] + i) % 7 - }; - var info = getDateInfo(obj); - info['disabled'] = 0; - data.push(info); - } - //下月日期 - var last = obj; - for (var i = 1; last['week'] + i < 7; i++) { - obj = getDateObj(last['year'], last['month'], last['day'] + i); - var info = getDateInfo(obj); - info['disabled'] = 1; - data.push(info); - } - return { - 'date': getDateInfo(date), //当前日历选中日期 - 'data': data - }; - }); + }; })(); - - +// Read the data: the lunar info of today. var d = new Date(); var lunarInfo = getLunarData({ - 'year': d.getFullYear(), - 'month': d.getMonth() + 1, - 'day': d.getDate() + year: d.getFullYear(), + month: d.getMonth() + 1, + day: d.getDate(), }); // console.log(JSON.stringify(lunarInfo, 2)); +// What lunarInfo.date looks like: /* "date": { "lYear": 2022, @@ -558,29 +1187,28 @@ var lunarInfo = getLunarData({ let today = lunarInfo.date; +// A background that runs from red at the top to yellow at the bottom. let linearGradient = { - type: "linear", - colors: ["red", "yellow"], - startPoint: "top", - endPoint: "bottom", + type: "linear", + colors: ["red", "yellow"], + startPoint: "top", + endPoint: "bottom", }; +// $render draws the widget. $gradient(…) turns the description above into a background. +// frame="max,center" fills the widget and centers the content. $render( - - - {today.Animal} 年 - - - {today.IMonthCn} - {today.IDayCn} - - + + + {today.Animal} 年 - {today.festival} + + {today.IMonthCn} + {today.IDayCn} + + - + {/* Empty when today is no festival. */} + {today.festival} + , ); - diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Material Study/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Material Study/main.jsx index f604d3a3..da83736b 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Material Study/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Material Study/main.jsx @@ -1,24 +1,46 @@ // Public SwiftUI material blurs these shapes inside the widget, not the wallpaper. // The system supplies Clear/Tinted backgrounds. No timer or private animation. +// Shows a frosted card over two colored shapes. Try another backgroundMaterial: +// ultraThin, thin, regular, thick or ultraThick. + +// $device.isdarkmode() is true when the system uses the dark appearance. const dark = $device.isdarkmode(); +// The size being drawn. The Lock Screen sizes start with "accessory". const family = $getenv("widget-size"); +// "fullColor", "accented" or "vibrant". The colored shapes are hidden unless it is fullColor. const fullColor = ($getenv("widget-rendering-mode") || "fullColor") === "fullColor"; const ink = dark ? "#EFFAF5" : "#1C4C39"; const muted = dark ? "#C2DCD0" : "#4E7764"; if (family.startsWith("accessory")) { - $render({family === "accessoryCircular" ? "Calm" : "A little calm"}); + // Lock Screen: text only. + $render( + + {family === "accessoryCircular" ? "Calm" : "A little calm"} + , + ); } else { $render( + {/* The shapes behind the card. rotation3d="12,0,1,0" tilts them 12 degrees on the y axis. */} - - + + - - A little calm - Your own quiet corner. + {/* The card. `background` is what shows when Reduce Transparency is turned on. */} + + + A little calm + + + Your own quiet corner. + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meal Planner/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meal Planner/main.jsx index 31925e40..f504a3f3 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meal Planner/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meal Planner/main.jsx @@ -1,3 +1,29 @@ // widget-param: breakfast,lunch,dinner (optional) -const meals=($getenv("widget-param")||"Oatmeal,Grain bowl,Pasta").split(","); const labels=["Morning","Lunch","Dinner"]; -$render(Today's menu{labels.map((label,i)=>{label}{(meals[i]||"Flexible").trim()})}); +// Shows three meals for today. Try changing the default meals, the labels or the color. +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget +// you place. It is empty when nothing was set, so the defaults are used. +const meals = ($getenv("widget-param") || "Oatmeal,Grain bowl,Pasta").split(","); +const labels = ["Morning", "Lunch", "Dinner"]; +$render( + + + + Today's menu + + + + + {/* One row per label. A meal that is missing from the parameter shows as "Flexible". */} + {labels.map((label, i) => ( + + + {label} + + + + {(meals[i] || "Flexible").trim()} + + + ))} + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meeting Countdown/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meeting Countdown/main.jsx index 00cea0a5..317f9d05 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meeting Countdown/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Meeting Countdown/main.jsx @@ -5,28 +5,42 @@ // Meeting Countdown // widget-param: "2026-02-01 09:30" or ISO string // +// Shows the time left until a meeting. Try your own time in the widget parameter, +// or change the texts and colors. +// Without a parameter the meeting is 90 minutes from now, so there is something to show. const defaultTarget = new Date(Date.now() + 90 * 60000).toISOString(); +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const param = ($getenv("widget-param") || defaultTarget).trim(); let target = null; if (param) { + // "2026-02-01 09:30" becomes "2026-02-01T09:30", which new Date() reads as local time. const normalized = param.includes("T") ? param : param.replace(" ", "T"); const parsed = new Date(normalized); + // An unreadable date has the time NaN; `target` stays null then. if (!Number.isNaN(parsed.getTime())) { target = parsed; } } +// No usable date: show how to set one. if (!target) { $render( - Meeting Countdown - Set widget-param - Example: 2026-02-01 09:30 - + + Meeting Countdown + + + Set widget-param + + + Example: 2026-02-01 09:30 + + , ); } else { + // Split the time left into days, hours and minutes. A time in the past counts as 0. const now = new Date(); const diffMs = target.getTime() - now.getTime(); const diffMin = Math.max(0, Math.floor(diffMs / 60000)); @@ -35,11 +49,26 @@ if (!target) { const hours = diffHour % 24; const minutes = diffMin % 60; + // $render draws the widget. frame="max" fills the whole widget; padding is the space + // in points around the content. $render( - NEXT MEETING - {diffDay > 0 ? `${diffDay}d ${hours}h` : `${hours}h ${minutes}m`} - Starts {target.toLocaleTimeString([], {hour:"2-digit", minute:"2-digit"})} - + + + NEXT MEETING + + + + + {/* The two share the free space, which centers the countdown. */} + + + {diffDay > 0 ? `${diffDay}d ${hours}h` : `${hours}h ${minutes}m`} + + + Starts {target.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })} + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Month Calendar/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Month Calendar/main.jsx index 80f5c831..6b1732c5 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Month Calendar/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Month Calendar/main.jsx @@ -5,7 +5,10 @@ // Month Calendar: the date, a month grid, and the next events. // Edit `events` to show your own schedule. // +// The grid follows today's date; the events are fixed samples. +// Try changing `accent`, or the cell sizes passed to . +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); const now = new Date(); const accent = "#FF3B30"; @@ -16,70 +19,135 @@ const events = [ { time: "19:30", title: "Call Mom", color: "#BF5AF2" }, ]; +// Names in English, such as "Sunday" and "March". const weekday = now.toLocaleString("en-US", { weekday: "long" }); const month = now.toLocaleString("en-US", { month: "long" }); const day = now.getDate(); +// getDay() of the 1st: 0 = Sunday. Day 0 of next month is the last day of this month. const firstWeekday = new Date(now.getFullYear(), now.getMonth(), 1).getDay(); const dayCount = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate(); // A month that touches six weeks gets smaller cells, so the grid keeps its height. const sixWeeks = firstWeekday + dayCount > 35; +// The month as a grid of 7 columns; `cell` is the size of one cell in points. +// takes its columns as JSON text: here seven columns of a fixed width. const MonthGrid = ({ cell, font, spacing }) => { - const columns = JSON.stringify(Array.from({ length: 7 }, () => ({ type: "fixed", value: String(cell) }))); + const columns = JSON.stringify( + Array.from({ length: 7 }, () => ({ type: "fixed", value: String(cell) })), + ); const cells = []; - ["S", "M", "T", "W", "T", "F", "S"].forEach((name) => cells.push({name})); - for (let i = 0; i < firstWeekday; i++) cells.push( ); + // First row: the letters of the weekdays. + ["S", "M", "T", "W", "T", "F", "S"].forEach((name) => + cells.push( + + {name} + , + ), + ); + // Empty cells before the 1st. + for (let i = 0; i < firstWeekday; i++) + cells.push( + + {" "} + , + ); + // One cell per day. Today gets a filled circle. for (let d = 1; d <= dayCount; d++) { const today = d === day; - cells.push({d}); + cells.push( + + {d} + , + ); } - return {cells}; + return ( + + {cells} + + ); }; +// One event: a colored bar, the title and the time. const EventRow = ({ event, font }) => ( - {event.title} - {event.time} + + {event.title} + + + {event.time} + ); +// The weekday and the day number in large type. const Today = () => ( - {weekday.toUpperCase()} - {day} + + {weekday.toUpperCase()} + + + {day} + ); +// Choose a layout for the widget size. if (size === "accessoryCircular") { + // Lock Screen, circular: weekday and day. $render( - {weekday.slice(0, 3).toUpperCase()} - {day} - + + {weekday.slice(0, 3).toUpperCase()} + + + {day} + + , ); } else if (size === "accessoryRectangular") { + // Lock Screen, rectangular: the date and the first two events. $render( - {weekday}, {month} {day} - {events[0].time} {events[0].title} - {events[1].time} {events[1].title} - + + {weekday}, {month} {day} + + + {events[0].time} {events[0].title} + + + {events[1].time} {events[1].title} + + , ); } else if (size === "accessoryInline") { - $render({weekday.slice(0, 3)} {day} · {events[0].title} {events[0].time}); + // Lock Screen, inline: one line of text. + $render( + + {weekday.slice(0, 3)} {day} · {events[0].title} {events[0].time} + , + ); } else if (size === "small") { + // Small widget: today and the first event. $render( - + , ); } else if (size === "medium") { + // Medium widget: today on the left, the month grid on the right. $render( @@ -88,31 +156,50 @@ if (size === "accessoryCircular") { - {month.toUpperCase()} + + {month.toUpperCase()} + - + , ); } else { + // Large widget: the month grid above two events. + // Extra large widget: the grid and four events side by side. const wide = size === "extraLarge"; const agenda = ( - UP NEXT - {events.slice(0, wide ? 4 : 2).map((event) => )} + + UP NEXT + + {events.slice(0, wide ? 4 : 2).map((event) => ( + + ))} ); $render( - {month} - {now.getFullYear()} + + {month} + + + {now.getFullYear()} + - {wide ? weekday : weekday.slice(0, 3)} + + {wide ? weekday : weekday.slice(0, 3)} + - {wide - ? {agenda} - : } + {wide ? ( + + + {agenda} + + ) : ( + + )} {wide ? null : agenda} - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Monthly Budget Planner/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Monthly Budget Planner/main.jsx index 6fd6afa5..deda0f8a 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Monthly Budget Planner/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Monthly Budget Planner/main.jsx @@ -1,56 +1,204 @@ // Designed for the large widget; the small and medium sizes show the essentials. widget-param: budget,spent,housing,food,fun +// Shows a monthly budget: what is left, what is spent, and three categories. +// Try your own numbers in the widget parameter, or change the categories below. +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const values = ($getenv("widget-param") || "4200,2675,1450,620,280").split(",").map(Number); +// A missing or unreadable number falls back to a default. const budget = values[0] || 4200; const spent = Math.max(0, values[1] || 0); const remaining = Math.max(0, budget - spent); +// `cap` is the most a category should use: a share of the budget. const categories = [ { name: "Housing", value: values[2] || 0, cap: budget * 0.4, color: "#818cf8" }, { name: "Food", value: values[3] || 0, cap: budget * 0.2, color: "#34d399" }, - { name: "Flexible", value: values[4] || 0, cap: budget * 0.15, color: "#fb7185" } + { name: "Flexible", value: values[4] || 0, cap: budget * 0.15, color: "#fb7185" }, ]; -const money = value => `$${Math.round(value).toLocaleString()}`; +// An amount rounded to whole dollars, such as "$2,675". +const money = (value) => `$${Math.round(value).toLocaleString()}`; +// One category: name, value / cap, and a bar. fills value / total of its width. const Category = ({ item }) => ( - {item.name}{money(item.value)} / {money(item.cap)} - + + + {item.name} + + + + {money(item.value)} / {money(item.cap)} + + + ); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); -const used = `${Math.round(spent / budget * 100)}% USED`; +// The share of the budget that is spent, in percent. +const used = `${Math.round((spent / budget) * 100)}% USED`; if (size === "small") { // Small: what is left of the budget. $render( - REMAINING - {money(remaining)}of {money(budget)} - - {used.toLowerCase()} - + + + REMAINING + + + + + + + {money(remaining)} + + + of {money(budget)} + + + + + {used.toLowerCase()} + + , ); } else if (size === "medium") { // Medium: what is left, beside the three categories. $render( - REMAINING{money(remaining)}of {money(budget)} - - {categories.map(item => {item.name}{money(item.value)} / {money(item.cap)})} + + + REMAINING + + + {money(remaining)} + + + of {money(budget)} + + - + + {categories.map((item) => ( + + + + {item.name} + + + + {money(item.value)} / {money(item.cap)} + + + + + ))} + + , ); } else { + // Large and extra large widgets: two cards on top, the categories below. $render( - Monthly Budget + {/* The title row. shows today's date. */} + + + + Monthly Budget + + + + + + - REMAINING{money(remaining)}{Math.round(remaining / budget * 100)}% available - SPENT{money(spent)}of {money(budget)} + + + + REMAINING + + + + + {money(remaining)} + + + {Math.round((remaining / budget) * 100)}% available + + + + + + SPENT + + + + + {money(spent)} + + + of {money(budget)} + + - - CATEGORY GUARDRAILS - {categories.map(item => )} + + + + CATEGORY GUARDRAILS + + + + + {categories.map((item) => ( + + ))} - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/main.jsx index 8f0eae14..dc64f0b8 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Mood Check-in/main.jsx @@ -1,43 +1,171 @@ // Choose a mood to save today's entry. Render/refresh never checks in automatically. // Optional widget-param: an intention, or {"intention":"Take a pause"} (up to 80 characters). -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); -const size = $getenv("widget-size"), parameter = ($getenv("widget-param") || "").trim(); +// Shows five faces to tap, today's mood and the last 7 days. +// Try other faces and names in `moods` and `names`, or change the colors. +// Saving needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. +const size = $getenv("widget-size"), + parameter = ($getenv("widget-param") || "").trim(); +// The intention line: the parameter, else the one saved by Records & Configuration. let intention = parameter || localRecords.configuration("mood").intention; if (parameter.startsWith("{")) { let config; - try { config = JSON.parse(parameter); } catch (_) { throw new Error("Use a JSON object or a short intention."); } - if (!config || Array.isArray(config) || Object.keys(config).some((key) => key !== "intention") || typeof config.intention !== "string") throw new Error("Mood settings accept a text intention only."); + try { + config = JSON.parse(parameter); + } catch (_) { + throw new Error("Use a JSON object or a short intention."); + } + if ( + !config || + Array.isArray(config) || + Object.keys(config).some((key) => key !== "intention") || + typeof config.intention !== "string" + ) + throw new Error("Mood settings accept a text intention only."); intention = config.intention.trim(); } if (intention.length > 80) throw new Error("Keep your intention to 80 characters."); -const moods = ["😔", "😕", "😐", "🙂", "😊"], names = ["Low", "Uneasy", "Okay", "Good", "Great"]; -const log = localRecords.create("mood.v1", (value) => Number.isInteger(value) && value >= 1 && value <= 5, 0); -function saveMood(value) { log.edit(() => value); $render(Mood saved); } -function moodOne() { saveMood(1); } -function moodTwo() { saveMood(2); } -function moodThree() { saveMood(3); } -function moodFour() { saveMood(4); } -function moodFive() { saveMood(5); } -function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); } -function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); } +const moods = ["😔", "😕", "😐", "🙂", "😊"], + names = ["Low", "Uneasy", "Okay", "Good", "Great"]; +// One record per day under the key "mood.v1": 1 (Low) to 5 (Great); 0 means no record. +const log = localRecords.create( + "mood.v1", + (value) => Number.isInteger(value) && value >= 1 && value <= 5, + 0, +); +// Save today's mood. +function saveMood(value) { + log.edit(() => value); + $render(Mood saved); +} +// The functions below are named by the "actions" in widget.json. A tap on a )} - {caption} - {size !== "small" && {intention}} - - {!["small", "medium"].includes(size) && Last 7 days{log.recent(state).map((day) => {day.date.slice(5)}{day.recorded ? `${moods[day.value - 1]} ${names[day.value - 1]}` : "—"})}} - ); + // Home Screen sizes. frame="max" fills the widget; padding is the space around the content. + $render( + + + + {size === "small" ? "Mood" : "How are you?"} + + + + {log.today.slice(5)} + + + {/* One button per face. A filled dot marks today's mood. */} + + {moods.map((mood, index) => ( + + ))} + + + {caption} + + {/* The small widget leaves out the intention. */} + {size !== "small" && ( + + {intention} + + )} + + + + + {/* Large sizes also list the last 7 days. day.date.slice(5) is the MM-DD part. */} + {!["small", "medium"].includes(size) && ( + + + Last 7 days + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? `${moods[day.value - 1]} ${names[day.value - 1]}` : "—"} + + + ))} + + )} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Music Playback/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Music Playback/main.jsx index aa134a6b..a957cd3f 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Music Playback/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Music Playback/main.jsx @@ -1,39 +1,141 @@ // iOS Music app only. Allow Music access in ScriptWidget Settings. // The browser uses editable samples. No queue changes or playback actions. -const family = $getenv("widget-size"), accessory = family.startsWith("accessory"); -const dark = $device.isdarkmode(), compact = family === "small"; +// Shows what the system music player is playing: state, title, artist and position. +// Try changing the colors, or the texts in `states`. +// $music runs on iPhone and iPad, and on Android (the active media session of any app); +// not on Mac, Windows or Linux. widget.json must declare the permission "music". + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". +const family = $getenv("widget-size"), + accessory = family.startsWith("accessory"); +// $device.isdarkmode() is true when the system uses the dark appearance. +const dark = $device.isdarkmode(), + compact = family === "small"; +// Lock Screen sizes get a clear background and the system's own text colors. const background = accessory ? "clear" : dark ? "#262235" : "#f5f1fc"; const primary = accessory ? "primary" : dark ? "#f4ecff" : "#3e3159"; const secondary = accessory ? "secondary" : dark ? "#bfb1d4" : "#796b90"; -let playback = null, notice = "Allow Music access", detail = "Open Music access in ScriptWidget Settings."; +// Read the data. Without it, `notice` and `detail` say what to do. +let playback = null, + notice = "Allow Music access", + detail = "Open Music access in ScriptWidget Settings."; try { - if (!$music.isAvailable()) { notice = "Music unavailable"; detail = "This platform cannot read the system Music player."; } - else if ($music.authorizationStatus() === "authorized") playback = await $music.current(); + // isAvailable() is false on a system without this API. + if (!$music.isAvailable()) { + notice = "Music unavailable"; + detail = "This platform cannot read the system Music player."; + } else if ($music.authorizationStatus() === "authorized") playback = await $music.current(); } catch (error) { + // A failed call throws an error whose text contains a code such as music_permission. const permission = String(error).includes("music_permission"); notice = permission ? "Allow Music access" : "Unable to refresh"; - detail = permission ? "Review Music access in ScriptWidget Settings." : "Open ScriptWidget and refresh this widget."; + detail = permission + ? "Review Music access in ScriptWidget Settings." + : "Open ScriptWidget and refresh this widget."; } -const states = {playing:"Playing",paused:"Paused",stopped:"Stopped",interrupted:"Interrupted",seeking:"Seeking",unknown:"Playback snapshot"}; +// A text for each playback state. +const states = { + playing: "Playing", + paused: "Paused", + stopped: "Stopped", + interrupted: "Interrupted", + seeking: "Seeking", + unknown: "Playback snapshot", +}; +// The texts to show, with a fallback when a detail is missing. const status = playback ? states[playback.state] : notice; -const title = playback ? playback.title || (playback.state === "stopped" ? "No current track" : "Track details unavailable") : notice; -const subtitle = playback ? [playback.artist, playback.album].filter(Boolean).join(" · ") || "Music app" : detail; -const symbol = playback?.state === "paused" ? "pause.fill" : playback?.state === "playing" ? "waveform" : "music.note"; -const time = seconds => `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2,"0")}`; -const progress = playback?.duration !== null && playback?.duration > 0 && playback?.position !== null ? Math.min(1,playback.position / playback.duration) : null; +const title = playback + ? playback.title || + (playback.state === "stopped" ? "No current track" : "Track details unavailable") + : notice; +const subtitle = playback + ? [playback.artist, playback.album].filter(Boolean).join(" · ") || "Music app" + : detail; +const symbol = + playback?.state === "paused" + ? "pause.fill" + : playback?.state === "playing" + ? "waveform" + : "music.note"; +// Seconds as m:ss, so 94 becomes "1:34". +const time = (seconds) => + `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`; +// The played share of the track, 0 to 1; null when position or duration is unknown. +const progress = + playback?.duration !== null && playback?.duration > 0 && playback?.position !== null + ? Math.min(1, playback.position / playback.duration) + : null; if (family === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({`${status} · ${title}`}); } else if (family === "accessoryCircular") { - $render({playback ? status : "Setup"}); + // Lock Screen, circular: a symbol and the state. + $render( + + + {playback ? status : "Setup"} + , + ); } else if (family === "accessoryRectangular") { - $render({title}{`${status} · ${playback ? playback.artist || "Music app" : "Open ScriptWidget"}`}); + // Lock Screen, rectangular: title, state and artist. + $render( + + {title} + {`${status} · ${playback ? playback.artist || "Music app" : "Open ScriptWidget"}`} + , + ); } else { - $render( - {compact && !playback ? "Setup" : status}Music - - {title} - {subtitle} - {progress !== null && {time(playback.position)}{time(playback.duration)}} - {!compact && family !== "medium" && <>A playback snapshot. Refresh to update.} - ); + // Home Screen sizes. frame="max" fills the widget; padding is the space around the content. + $render( + + + + + {compact && !playback ? "Setup" : status} + + + + Music + + + + + {title} + + + {subtitle} + + {/* The bar and the two times appear only when the position is known. */} + {progress !== null && ( + + + + + {time(playback.position)} + + + + {time(playback.duration)} + + + + )} + {/* Large sizes add a note. <>… groups children without adding a stack. */} + {!compact && family !== "medium" && ( + <> + + + A playback snapshot. Refresh to update. + + + )} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/New Episode Tracker/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/New Episode Tracker/main.jsx index 42085dd4..f37f303e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/New Episode Tracker/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/New Episode Tracker/main.jsx @@ -1,158 +1,116 @@ -const API_URL = "https://episodate.com/api/show-details?q=" +// Shows when the next episode of each of your TV series airs. +// Try your own series: put the names used in episodate.com addresses into `series`. +// The data comes from the episodate.com API, so the widget needs a connection. + +const API_URL = "https://episodate.com/api/show-details?q="; const colors = { primary: "#080808", secondary: "green", text: { primary: "white", - secondary: "green" - } -} + secondary: "green", + }, +}; -const series = [ - "the-lord-of-the-rings", - "house-of-the-dragon" -] +const series = ["the-lord-of-the-rings", "house-of-the-dragon"]; -const fetchSeries = async seriesList => { - let response = [] +// Load the details of every series, one request after another. fetch resolves to the +// text of the response, which JSON.parse turns into an object. +const fetchSeries = async (seriesList) => { + let response = []; for (let series of seriesList) { - response.push( - JSON.parse( - await fetch(API_URL + series) - ) - ) + response.push(JSON.parse(await fetch(API_URL + series))); } - return response -} + return response; +}; -const getTimeLeft = airDate => { +// The time until `airDate` as text, such as "3d 4h left" or "25 m left". +const getTimeLeft = (airDate) => { + let res; + const millis = airDate - Date.now(); + const secondsLeft = millis / 1000; - let res - const millis = airDate - Date.now() - const secondsLeft = millis / 1000 + const getDays = (seconds) => { + return Math.round(seconds / (3600 * 24)); + }; - const getDays = seconds => { - return Math.round(seconds / (3600 * 24)) - } + const getHours = (seconds) => { + return Math.round((seconds % (3600 * 24)) / 3600); + }; - const getHours = seconds => { - return Math.round(seconds % (3600 * 24) / 3600) - } + const getMinutes = (seconds) => { + return Math.round((seconds % 3600) / 60); + }; - const getMinutes = seconds => { - return Math.round(seconds % 3600 / 60) - } - if (getDays(secondsLeft) > 0) { - res = getDays(secondsLeft) + "d " - res += getHours(secondsLeft) + "h " - + res = getDays(secondsLeft) + "d "; + res += getHours(secondsLeft) + "h "; } else if (getHours(secondsLeft) > 0) { - res = getHours(secondsLeft) + " h " - + res = getHours(secondsLeft) + " h "; } else { - res = getMinutes(secondsLeft) + " m " + res = getMinutes(secondsLeft) + " m "; } - - return res + "left" -} -const Logo = ({logoPath}) => { - return ( + return res + "left"; +}; + +// The poster of a series with a thin outline. stacks its children on each other. +const Logo = ({ logoPath }) => { + return ( - - + + - ) -} + ); +}; -const Entry = ({info}) => { +// One row: poster, name, next episode (such as s2e5) and the time left. +const Entry = ({ info }) => { + const getNextEpisode = (countdown) => `s${countdown.season}e${countdown.episode}`; - const getNextEpisode = countdown => - `s${countdown.season}e${countdown.episode}` + const nextEpisodeRemaining = (countdown) => { + // air_date is a UTC time with a space in the middle; this makes it an ISO date. + const airDate = countdown.air_date.replace(" ", "T") + "Z"; + + return getTimeLeft(new Date(airDate)); + }; - const nextEpisodeRemaining = countdown => { - const airDate = countdown.air_date - .replace(" ", "T") + "Z" - - return getTimeLeft(new Date(airDate)) - } - return ( - - - - - + + + + + {info.name} + {/* `countdown` is null when no further episode is announced. */} - - { - info.countdown === null ? "ended" - : getNextEpisode(info.countdown) - } + + {info.countdown === null ? "ended" : getNextEpisode(info.countdown)} - - { - info.countdown === null ? "" - : nextEpisodeRemaining(info.countdown) - } + + {info.countdown === null ? "" : nextEpisodeRemaining(info.countdown)} - + - ) -} + ); +}; -const seriesJson = await fetchSeries(series) +// Read the data. `await` waits for all answers before anything is drawn. +const seriesJson = await fetchSeries(series); +// $render draws the widget. frame="max,top" fills it and keeps the rows at the top. $render( - - - { - seriesJson?.map(series => - - ) - } + + + {seriesJson?.map((series) => ( + + ))} - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Now Playing/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Now Playing/main.jsx index 64b8a68e..5b3e58be 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Now Playing/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Now Playing/main.jsx @@ -4,31 +4,73 @@ // // Now Playing: a music card. Replace `track` and `queue` with your own. // +// The track is sample data: this card does not read your music player, and the three +// control icons are pictures, not buttons. Try other colors in the two gradients. +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". const size = $getenv("widget-size"); -const track = { title: "Midnight Drive", artist: "Neon Coast", album: "Afterglow", elapsed: 94, length: 236 }; -const queue = [["Ocean Avenue", "Neon Coast"], ["Paper Planes", "Lumen"], ["Static Bloom", "Velvet Hours"]]; -const art = $gradient({ type: "linear", colors: ["#FF5F6D", "#7B2FF7"], startPoint: "topLeading", endPoint: "bottomTrailing" }); -const backdrop = $gradient({ type: "linear", colors: ["#2A1B3D", "#120E1E"], startPoint: "top", endPoint: "bottom" }); +// `elapsed` and `length` are in seconds. +const track = { + title: "Midnight Drive", + artist: "Neon Coast", + album: "Afterglow", + elapsed: 94, + length: 236, +}; +const queue = [ + ["Ocean Avenue", "Neon Coast"], + ["Paper Planes", "Lumen"], + ["Static Bloom", "Velvet Hours"], +]; +// $gradient(…) makes a background that blends colors, here from corner to corner. +const art = $gradient({ + type: "linear", + colors: ["#FF5F6D", "#7B2FF7"], + startPoint: "topLeading", + endPoint: "bottomTrailing", +}); +const backdrop = $gradient({ + type: "linear", + colors: ["#2A1B3D", "#120E1E"], + startPoint: "top", + endPoint: "bottom", +}); +// Seconds as m:ss, so 94 becomes "1:34". const clock = (seconds) => `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`; +// The cover: a gradient square with a note. `side` is its size in points. const Artwork = ({ side }) => ( ); +// Title and artist. const Titles = ({ font }) => ( - {track.title} - {track.artist} + + {track.title} + + + {track.artist} + ); +// A progress bar with the time played and the time left. const Progress = () => ( - {clock(track.elapsed)}-{clock(track.length - track.elapsed)} + + + {clock(track.elapsed)} + + + + -{clock(track.length - track.elapsed)} + + ); +// Previous, pause and next icons. const Controls = ({ size: iconSize }) => ( @@ -37,27 +79,42 @@ const Controls = ({ size: iconSize }) => ( ); +// Choose a layout for the widget size. if (size === "accessoryCircular") { - $render(); + // Lock Screen, circular: a ring that shows how far the track is. + $render( + + + + , + ); } else if (size === "accessoryRectangular") { + // Lock Screen, rectangular: title, artist and a progress bar. $render( {track.title} {track.artist} - + , ); } else if (size === "accessoryInline") { - $render(♪ {track.title} · {track.artist}); + // Lock Screen, inline: one line of text. + $render( + + ♪ {track.title} · {track.artist} + , + ); } else if (size === "small") { + // Small widget: cover, title and artist. $render( - + , ); } else if (size === "medium") { + // Medium widget: the cover on the left; titles, progress and controls on the right. $render( @@ -65,39 +122,74 @@ if (size === "accessoryCircular") { - + + + + + - + , ); } else { + // Large widget: the track above the queue. Extra large widget: side by side. + // JSX can be kept in a variable and placed later with {nowPlaying}. const wide = size === "extraLarge"; const nowPlaying = ( - NOW PLAYING + + NOW PLAYING + - {track.album} + + {track.album} + - + + + + + ); const upNext = ( - UP NEXT + + UP NEXT + {queue.slice(0, wide ? 3 : 2).map(([title, artist]) => ( - {title}{artist} + + + {title} + + + {artist} + + ))} ); - $render(wide - ? {nowPlaying}{upNext} - : {nowPlaying}{upNext}); + $render( + wide ? ( + + {nowPlaying} + {upNext} + + ) : ( + + {nowPlaying} + + {upNext} + + + ), + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Nyan Cat/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Nyan Cat/main.jsx index 0f1efa27..e189da28 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Nyan Cat/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Nyan Cat/main.jsx @@ -6,11 +6,11 @@ // // Description: Shape Example // - - +// Shows an animated GIF. file="cat" is image/cat.gif in this widget's folder. +// Try a GIF of your own. A Mac shows only its first frame. $render( - + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Open Link/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Open Link/main.jsx index 36c93395..06edc3e9 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Open Link/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Open Link/main.jsx @@ -1,23 +1,61 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Template for component link -// +// +// Shows a card that opens a web page when it is tapped. Try your own address in linkurl. +// $getenv("widget-size") is the size being drawn. +// linkurl on the outer stack makes the whole card a link. if ($getenv("widget-size") === "small") { // Small: the name of the link, without the sentence that needs the width. $render( - - - ScriptWidgetTAP TO OPEN - + + + + + ScriptWidget + + + TAP TO OPEN + + + , ); } else { + // Other sizes: also a sentence under the name. $render( - - TAP TO OPEN - ScriptWidgetA full-card link with one simple URL. - + + + + + + TAP TO OPEN + + + + + ScriptWidget + + + A full-card link with one simple URL. + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/main.jsx index c594a5e4..d2686f0e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Packing Checklist/main.jsx @@ -1,12 +1,37 @@ // A real daily checklist. Optional widget-param: Passport,Charger,Headphones // Up to 8 unique labels. Exact labels identify items, so reordering preserves checks. // Reset affects today only; Undo restores the most recent change. Large shows history. -if (!$import("lib/records.js")) throw new Error("Install the complete template, including lib/records.js."); -const size = $getenv("widget-size"), parameter = ($getenv("widget-param") || "").trim(); -const items = parameter ? parameter.split(",").map((item) => item.trim().normalize("NFC")) : localRecords.configuration("checklist").items; -if (items.length > 8 || items.some((item) => !item || item.length > 60) || new Set(items).size !== items.length) throw new Error("Use 1–8 unique checklist labels, at most 60 characters each."); -const validChecks = (value) => Array.isArray(value) && value.length <= 8 && value.every((item) => typeof item === "string" && item.length > 0 && item.length <= 60) && new Set(value).size === value.length; +// Shows a checklist whose items you tick by tapping, with Undo and Reset. +// Try your own items in the widget parameter, or change the colors. +// Saving needs the permission "storage" in widget.json; the buttons need its "actions". + +// $import runs another file of this package; lib/records.js defines `localRecords`. +// It returns false when the file is missing. +if (!$import("lib/records.js")) + throw new Error("Install the complete template, including lib/records.js."); +// $getenv("widget-size") is the size being drawn, such as "small" or "accessoryInline". +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. +const size = $getenv("widget-size"), + parameter = ($getenv("widget-param") || "").trim(); +// The items: from the parameter, else those saved by Records & Configuration. +const items = parameter + ? parameter.split(",").map((item) => item.trim().normalize("NFC")) + : localRecords.configuration("checklist").items; +if ( + items.length > 8 || + items.some((item) => !item || item.length > 60) || + new Set(items).size !== items.length +) + throw new Error("Use 1–8 unique checklist labels, at most 60 characters each."); +// A day's record is the list of ticked labels: up to 8 different texts. +const validChecks = (value) => + Array.isArray(value) && + value.length <= 8 && + value.every((item) => typeof item === "string" && item.length > 0 && item.length <= 60) && + new Set(value).size === value.length; +// One record per day under the key "checklist.v1"; a day without a record is []. const log = localRecords.create("checklist.v1", validChecks, []); +// Tick or untick one item of today's list. function toggleItem(index) { const item = items[index]; if (!item) throw new Error("Checklist item is unavailable."); @@ -17,34 +42,149 @@ function toggleItem(index) { }); $render(Checklist saved); } -function toggleOne() { toggleItem(0); } -function toggleTwo() { toggleItem(1); } -function toggleThree() { toggleItem(2); } -function toggleFour() { toggleItem(3); } -function toggleFive() { toggleItem(4); } -function toggleSix() { toggleItem(5); } -function toggleSeven() { toggleItem(6); } -function toggleEight() { toggleItem(7); } -function undoRecord() { const changed = log.undo(); $render({changed ? "Change undone" : "Nothing to undo"}); } -function resetToday() { log.reset(); $render(Today cleared; Undo can restore it); } -const actions = ["toggleOne", "toggleTwo", "toggleThree", "toggleFour", "toggleFive", "toggleSix", "toggleSeven", "toggleEight"]; -const state = log.read(), checked = log.value(state), completed = items.filter((item) => checked.includes(item)).length; -const dark = $device.isdarkmode(), ink = dark ? "#E0F2FE" : "#0C4A6E", muted = dark ? "#7DD3FC" : "#0369A1", background = dark ? "#082F49" : "#F0F9FF"; +// The functions below are named by the "actions" in widget.json. A tap on a )} - {items.length > limit && {size === "small" ? `+ ${items.length - limit} more · use Large` : `+ ${items.length - limit} items · use a larger widget`}} - - {!["small", "medium"].includes(size) && Recent days · completed items{log.recent(state, 3).map((day) => {day.date.slice(5)}{day.recorded ? String(day.value.length) : "—"})}} - ); + $render( + + + + {size === "small" ? "Pack" : "Ready to go"} + + + + {summary} + + + {/* One button per item. The icon shows whether it is ticked. */} + {items.slice(0, limit).map((item, index) => ( + + ))} + {/* Say how many items did not fit. */} + {items.length > limit && ( + + {size === "small" + ? `+ ${items.length - limit} more · use Large` + : `+ ${items.length - limit} items · use a larger widget`} + + )} + + + + + {/* Large sizes also show how many items were ticked on each of the last 3 days. */} + {!["small", "medium"].includes(size) && ( + + + Recent days · completed items + + {log.recent(state, 3).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? String(day.value.length) : "—"} + + + ))} + + )} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Personal Dashboard/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Personal Dashboard/main.jsx index eca91e7f..34a15b34 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Personal Dashboard/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Personal Dashboard/main.jsx @@ -1,38 +1,64 @@ // Personal Dashboard // widget-param: your first name (optional) +// Shows a greeting for the time of day and how much of today has passed. +// Try changing the greetings, the colors or the Focus line. +// $getenv("widget-param") is the optional widget parameter, a text you set on each widget. const name = ($getenv("widget-param") || "Friend").trim(); +// The hour in local time, 0 to 23. const hour = new Date().getHours(); const greeting = hour < 12 ? "Good morning" : hour < 18 ? "Good afternoon" : "Good evening"; +// The share of the day that has passed, from 0 to 1. A day has 1440 minutes. const dayProgress = Math.min(1, (hour * 60 + new Date().getMinutes()) / 1440); if ($getenv("widget-size") === "small") { // Small: how much of today has passed, under a two-line greeting. $render( - {greeting},{name} + + + + {greeting}, + + + {name} + + + + + - {Math.round(dayProgress * 100)}% + + {Math.round(dayProgress * 100)}% + - of today complete + + of today complete + - + , ); } else { + // Other sizes: greeting and date, then a Focus line and the progress of the day. $render( - {greeting}, {name} + + {greeting}, {name} + + {/* draws a line; shows a title with its value. */} - {Math.round(dayProgress * 100)}% of today complete - + + {Math.round(dayProgress * 100)}% of today complete + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Album Rotator/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Album Rotator/main.jsx index d3f86d3e..a813aa00 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Album Rotator/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Album Rotator/main.jsx @@ -1,35 +1,121 @@ // Live selected Photos sources on iPhone, iPad and Mac; browser samples only. // In ScriptWidget Settings → Photos, authorize and select photos/albums. // Open the installed widget in ScriptWidget to prepare its private snapshot. +// Shows one of up to four selected photos, and the next one every six hours. +// Try other texts and colors, or another photo height. +// $photos runs on iPhone, iPad and Mac, and on Android for individual photos picked in +// the app (no albums); not on Windows or Linux. widget.json must declare the permission +// "photos"; its "timeline" plans an entry at 00:00, 06:00, 12:00 and 18:00. + +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", +// "extraLarge", or a Lock Screen size whose name starts with "accessory". const family = $getenv("widget-size"); const accessory = family.startsWith("accessory"); const small = family === "small" || family === "systemSmall"; const dark = $device.isdarkmode(); const background = accessory ? "clear" : dark ? "#162522" : "#eff7f3"; const foreground = accessory ? "primary" : dark ? "#e7f2eb" : "#204039"; -let photos = [], message = "", partial = false; +// Read the data. `message` says what to do when there is no photo. +let photos = [], + message = "", + partial = false; try { - if (!$photos.isAvailable() || !["authorized", "limited"].includes($photos.authorizationStatus())) message = "Connect Photos in ScriptWidget Settings."; + if (!$photos.isAvailable() || !["authorized", "limited"].includes($photos.authorizationStatus())) + message = "Connect Photos in ScriptWidget Settings."; else { - const result = await $photos.items({limit:4,maxAgeSeconds:3600}); - photos = result.items; partial = result.unavailableCount > 0; - if (!photos.length) message = partial ? "Download selected photos in Photos first." : "No photos in the selected sources."; + // Up to 4 photos (limit) from a snapshot at most one hour old (maxAgeSeconds). + const result = await $photos.items({ limit: 4, maxAgeSeconds: 3600 }); + photos = result.items; + // unavailableCount counts selected photos whose picture is not on this device. + partial = result.unavailableCount > 0; + if (!photos.length) + message = partial + ? "Download selected photos in Photos first." + : "No photos in the selected sources."; } } catch (error) { - message = String(error).includes("cache_miss") ? "Open this widget in ScriptWidget to prepare photos." : "Choose photos or albums in ScriptWidget Settings."; + // A failed call throws an error whose text contains a code such as cache_miss. + message = String(error).includes("cache_miss") + ? "Open this widget in ScriptWidget to prepare photos." + : "Choose photos or albums in ScriptWidget Settings."; } -const compactMessage = message.includes("Download") ? "Download in Photos\nthen refresh here." : message.includes("prepare") ? "Open in ScriptWidget\nto prepare photos." : "Choose photos in\nSettings → Photos"; +// A two-line form of the message for the small widget. +const compactMessage = message.includes("Download") + ? "Download in Photos\nthen refresh here." + : message.includes("prepare") + ? "Open in ScriptWidget\nto prepare photos." + : "Choose photos in\nSettings → Photos"; +// "timeline-date" is the time this entry is planned for. It is used instead of the +// current time because the system may draw an entry ahead of its time. const date = new Date($getenv("timeline-date") || Date.now()); -const photoHeight = family === "small" || family === "medium" ? 112 : family === "extraLargePortrait" ? 480 : 290; -const photo = photos.length ? photos[Math.floor(date.getHours()/6) % photos.length] : null; +// The height of the photo in points, by size. +const photoHeight = + family === "small" || family === "medium" ? 112 : family === "extraLargePortrait" ? 480 : 290; +// Hours 0 to 5 show the first photo, 6 to 11 the second, and so on, starting over at the end. +const photo = photos.length ? photos[Math.floor(date.getHours() / 6) % photos.length] : null; if (family === "accessoryInline") { + // Lock Screen, inline: one line of text. $render({photo ? "My moments" : "Set up Photos"}); } else if (family === "accessoryCircular") { - $render({photos.length ? `${photos.length} photos` : "Set up"}); + // Lock Screen, circular: the number of photos. + $render( + + + {photos.length ? `${photos.length} photos` : "Set up"} + , + ); } else if (accessory) { - $render(My moments{photo ? `${photos.length} selected photos` : "Open ScriptWidget to connect Photos."}); + // Lock Screen, rectangular: two lines. + $render( + + My moments + + {photo ? `${photos.length} selected photos` : "Open ScriptWidget to connect Photos."} + + , + ); } else if (photo) { - $render(My moments{partial && }); + // A photo. `photo.image` is the picture as a data URL. + // mode="fill" with clip="rect" crops it to the frame. + $render( + + + + + My moments + + + {partial && } + + , + ); } else { - $render(My moments{small ? compactMessage : message}{small ? "Photos settings →" : "Open Photos settings →"}); + // No photo: a card that says why. opens its url when the card is tapped. + $render( + + + + + My moments + + + {small ? compactMessage : message} + + + + {small ? "Photos settings →" : "Open Photos settings →"} + + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/lib/configuration.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/lib/configuration.js index e71f04cb..2d393b72 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/lib/configuration.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/lib/configuration.js @@ -1,28 +1,83 @@ +// Settings for Photo Card. main.jsx loads this file and calls +// photoCardConfiguration.read(). A file loaded this way shares its top-level names +// with main.jsx, so everything else is kept private inside one function. var photoCardConfiguration = (() => { - const defaults = {title:"Little moments",caption:"",layout:"single",photos:[]}; - const valid = value => value && typeof value === "object" && !Array.isArray(value) && + // Used when nothing has been saved yet. + const defaults = { title: "Little moments", caption: "", layout: "single", photos: [] }; + // True when the settings have exactly the four expected keys and every value is in range: + // a title of 1–40 characters, a caption of up to 80, a known layout, and at most four + // different photo names of the form photo-. + const valid = (value) => + value && + typeof value === "object" && + !Array.isArray(value) && Object.keys(value).sort().join(",") === "caption,layout,photos,title" && - typeof value.title === "string" && value.title.trim().length > 0 && value.title.length <= 40 && - typeof value.caption === "string" && value.caption.length <= 80 && ["single","duo","grid"].includes(value.layout) && - Array.isArray(value.photos) && value.photos.length <= 4 && new Set(value.photos).size === value.photos.length && - value.photos.every(name => typeof name === "string" && /^photo-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(name)); + typeof value.title === "string" && + value.title.trim().length > 0 && + value.title.length <= 40 && + typeof value.caption === "string" && + value.caption.length <= 80 && + ["single", "duo", "grid"].includes(value.layout) && + Array.isArray(value.photos) && + value.photos.length <= 4 && + new Set(value.photos).size === value.photos.length && + value.photos.every( + (name) => + typeof name === "string" && + /^photo-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(name), + ); + // raw: the saved settings string ("" when nothing is saved). parameter: the widget + // parameter. Returns the settings to draw with, or throws an error for the widget to show. function read(raw, parameter) { - let values = {...defaults,photos:[]}; + let values = { ...defaults, photos: [] }; + // Saved settings look like {"version":1,"kind":"photoCard","values":{…}}. Anything else + // is refused instead of being guessed at. if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved photo settings are invalid. Open Records & Configuration to repair them."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || !state || - Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== "photoCard" || !valid(state.values)) throw new Error("Saved photo settings are invalid. Open Records & Configuration to repair them."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved photo settings are invalid. Open Records & Configuration to repair them.", + ); + } + // unescape(encodeURIComponent(raw)).length is the size in UTF-8 bytes; the limit is 4096. + if ( + typeof raw !== "string" || + unescape(encodeURIComponent(raw)).length > 4096 || + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== "photoCard" || + !valid(state.values) + ) + throw new Error( + "Saved photo settings are invalid. Open Records & Configuration to repair them.", + ); values = state.values; } + // The widget parameter may override some settings for one widget. Unknown keys are refused. if ((parameter || "").trim()) { let overrides; - try { overrides = JSON.parse(parameter); } catch (_) { throw new Error("Photo Card parameters must be a JSON object."); } - if (!overrides || Array.isArray(overrides) || Object.keys(overrides).some(key => !Object.prototype.hasOwnProperty.call(defaults,key))) throw new Error("Photo Card accepts title, caption, layout and photos only."); - values = {...values,...overrides}; + try { + overrides = JSON.parse(parameter); + } catch (_) { + throw new Error("Photo Card parameters must be a JSON object."); + } + if ( + !overrides || + Array.isArray(overrides) || + Object.keys(overrides).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error("Photo Card accepts title, caption, layout and photos only."); + values = { ...values, ...overrides }; } - if (!valid(values)) throw new Error("Choose up to 4 imported photos, a single/duo/grid layout and valid title/caption text."); + // Check the merged result too, because the parameter is typed by hand. + if (!valid(values)) + throw new Error( + "Choose up to 4 imported photos, a single/duo/grid layout and valid title/caption text.", + ); return values; } - return {read}; + return { read }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/main.jsx index b41992d9..6c2cfd2b 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Photo Card/main.jsx @@ -1,25 +1,125 @@ // Import, crop, select and order photos in Records & Configuration, then save. // Assets stay inside the package. Export the package to back up photo files; // a record backup contains the settings only. No album or network access. -if (!$import("lib/configuration.js")) throw new Error("Install the complete Photo Card template, including lib/configuration.js."); -const options = photoCardConfiguration.read($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); +// +// This template shows how to draw image files stored in the package, in a layout that +// depends on the widget size. Try changing the frame heights or the background colors. + +// $import runs another file of this package and returns false when that fails. +// lib/configuration.js defines photoCardConfiguration, which reads and checks the settings. +if (!$import("lib/configuration.js")) + throw new Error("Install the complete Photo Card template, including lib/configuration.js."); +// $storage holds values saved for this package (widget.json declares the "storage" +// permission). $getenv("widget-param") is the parameter text set for this widget; here it +// may be JSON that overrides title, caption, layout or photos. +const options = photoCardConfiguration.read( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); +// How many photos the chosen layout shows. const limit = options.layout === "grid" ? 4 : options.layout === "duo" ? 2 : 1; -const photos = options.photos.slice(0,limit); -function Photo({name,height}) { return ; } +const photos = options.photos.slice(0, limit); +// One photo. name is an image file in the package; mode="fit" keeps the whole picture +// visible; frame "max,88" means as wide as possible and 88 points high. +function Photo({ name, height }) { + return ; +} if (size === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only). Inline: one line of text. $render({photos.length ? options.title : "Choose photos in ScriptWidget"}); } else if (size === "accessoryCircular") { - $render(photos.length ? : ); + // Lock Screen circle: the first photo, or an icon when none is chosen. + $render( + photos.length ? ( + + ) : ( + + ), + ); } else if (size === "accessoryRectangular") { - $render({photos.length ? : }{options.title}{photos.length ? options.caption : "Choose your photos in the app"}); + // Lock Screen rectangle: a thumbnail beside the title and caption. + $render( + + {photos.length ? ( + + ) : ( + + )} + + {options.title} + + {photos.length ? options.caption : "Choose your photos in the app"} + + + , + ); } else if (!photos.length) { - $render(Add your photosOpen Records & Configuration); + // No photos yet: say where to add them. frame="max" fills the widget; padding is the + // space around the content, in points. + $render( + + + + Add your photos + + + Open Records & Configuration + + , + ); } else if (size === "small") { - $render({Array.from(options.title).slice(0,16).join("")}); + // Small: one photo above the title, cut to 16 characters. Array.from splits the text + // by character, so an emoji is not cut in half. + $render( + + + + {Array.from(options.title).slice(0, 16).join("")} + + , + ); } else if (size === "medium") { - $render({photos.map(name => )}{options.title}{photos.length + (photos.length === 1 ? " photo" : " photos")}); + // Medium: the photos side by side, then the title and a count. + $render( + + + {photos.map((name) => ( + + ))} + + + + {options.title} + + + + {photos.length + (photos.length === 1 ? " photo" : " photos")} + + + , + ); } else { - const rows = photos.length > 2 ? [photos.slice(0,2),photos.slice(2)] : [photos]; - $render({options.title}{rows.map(row => {row.map(name => 1 ? "120" : "240"}/>)})}{options.caption ? {options.caption} : null}); + // Large and extra large: one or two rows of photos, the title above, the caption below. + const rows = photos.length > 2 ? [photos.slice(0, 2), photos.slice(2)] : [photos]; + $render( + + + {options.title} + + {rows.map((row) => ( + + {row.map((name) => ( + 1 ? "120" : "240"} /> + ))} + + ))} + {options.caption ? ( + + {options.caption} + + ) : null} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/main.jsx index 69010901..1b22d428 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Plant Care/main.jsx @@ -1,18 +1,184 @@ // A personal care journal, not a sensor reading. Rendering never creates records. +// +// This template shows a widget with buttons: a tap runs a function in this file, which +// saves a record in package storage. Try changing the status texts, the level names or the +// colors. + +// $import runs lib/records.js from this package and returns false when that fails. The +// file defines localRecords: a diary with one entry per calendar day, kept in package storage +// (widget.json declares the "storage" permission). if (!$import("lib/records.js")) throw new Error("Install the complete Plant Care template."); -const config=localRecords.configuration("plantCare"),parameter=$getenv("widget-param")||""; +// The saved settings (plant name, days between care) and the widget parameter: the +// parameter text set for this widget, empty when there is none. +const config = localRecords.configuration("plantCare"), + parameter = $getenv("widget-param") || ""; // Preserve the name from the earlier name,days demo; its invented countdown is not a care record. -const title=parameter?parameter.split(",")[0].trim():config.title; -if(!title||title.length>40)throw new Error("Use a plant name of 1–40 characters."); -const log=localRecords.create("plantCare.v1",value=>value===1,0,new Date($getenv("timeline-date")||Date.now())); -function waterPlant(){const changed=log.edit(()=>1);$render({changed?"Care recorded":"Already recorded today"});} -function undoRecord(){const changed=log.undo();$render({changed?"Change undone":"Nothing to undo"});} -function resetToday(){log.reset();$render(Today cleared; Undo can restore it);} -const state=log.read(),days=state.entries.filter(entry=>entry.date<=log.today).map(entry=>entry.date).sort(),last=days[days.length-1]||"",done=log.value(state)===1; -const ordinal=key=>{const [y,m,d]=key.split("-").map(Number);return Date.UTC(y,m-1,d)/86400000;}; -const elapsed=last?ordinal(log.today)-ordinal(last):null,remaining=elapsed===null?null:Math.max(0,config.intervalDays-elapsed); -const status=done?"Cared for today":last?(remaining>0?`Next care in ${remaining} ${remaining===1?"day":"days"}`:"Care due"):"No care recorded"; -const level=days.length>=15?"Blooming routine":days.length>=5?"Growing routine":"New beginning"; -const dark=$device.isdarkmode(),background=dark?"#102a22":"#f0fdf4",ink=dark?"#dcfce7":"#14532d",muted=dark?"#86efac":"#166534",family=$getenv("widget-size"); -const Plant=()=> ; -if(family==="function"||family==="action"){}else if(family==="accessoryInline"){$render({`${title} · ${status}`});}else if(family==="accessoryCircular"){$render({done?"Done":remaining===null?"Start":remaining===0?"Due":`${remaining}d`});}else if(family==="accessoryRectangular"){$render({title}{status});}else{$render({title}{family!=="small"&&CARE JOURNAL}{status}{family!=="small"&&{`${days.length} care ${days.length===1?"day":"days"} · last year`}}{family!=="small"&&{level}}{!["small","medium"].includes(family)&&{last?`Last care: ${last}`:"Your first care check-in starts the journal."}{`Personal interval: ${config.intervalDays} days`}{log.recent(state).map(day=>{day.date.slice(5)}{day.recorded?"✓":"—"})}});} +const title = parameter ? parameter.split(",")[0].trim() : config.title; +if (!title || title.length > 40) throw new Error("Use a plant name of 1–40 characters."); +// Open the diary stored under the key "plantCare.v1". A day's value is 1 when care was +// recorded; 0 stands for a day without an entry. "timeline-date" is the moment this entry +// is drawn for, which is later than now when the system prepares the widget in advance. +const log = localRecords.create( + "plantCare.v1", + (value) => value === 1, + 0, + new Date($getenv("timeline-date") || Date.now()), +); +// The next three functions are the actions listed in widget.json; a button with +// actionID="waterPlant" runs waterPlant(). Each one changes the diary and renders a short +// confirmation. edit() returns false when today already has that value. +function waterPlant() { + const changed = log.edit(() => 1); + $render({changed ? "Care recorded" : "Already recorded today"}); +} +function undoRecord() { + const changed = log.undo(); + $render({changed ? "Change undone" : "Nothing to undo"}); +} +function resetToday() { + log.reset(); + $render(Today cleared; Undo can restore it); +} +// Read the diary (reading never writes) and work out what to show. +// days: every recorded date up to today, as sorted "YYYY-MM-DD" strings. +const state = log.read(), + days = state.entries + .filter((entry) => entry.date <= log.today) + .map((entry) => entry.date) + .sort(), + last = days[days.length - 1] || "", + done = log.value(state) === 1; +// Turns "YYYY-MM-DD" into a day number, so that two dates can be subtracted. +const ordinal = (key) => { + const [y, m, d] = key.split("-").map(Number); + return Date.UTC(y, m - 1, d) / 86400000; +}; +// Days since the last care, and days until the next one is due (never below 0). +const elapsed = last ? ordinal(log.today) - ordinal(last) : null, + remaining = elapsed === null ? null : Math.max(0, config.intervalDays - elapsed); +// The sentence shown in the widget. +const status = done + ? "Cared for today" + : last + ? remaining > 0 + ? `Next care in ${remaining} ${remaining === 1 ? "day" : "days"}` + : "Care due" + : "No care recorded"; +// A label that grows with the number of recorded days. +const level = + days.length >= 15 ? "Blooming routine" : days.length >= 5 ? "Growing routine" : "New beginning"; +// Colors for light and dark mode, and the size being drawn ("small", "medium", …). +const dark = $device.isdarkmode(), + background = dark ? "#102a22" : "#f0fdf4", + ink = dark ? "#dcfce7" : "#14532d", + muted = dark ? "#86efac" : "#166534", + family = $getenv("widget-size"); +// The plant, drawn from shapes: two leaves, a stem and a pot. frame is "width,height" in +// points; rotation is in degrees. +const Plant = () => ( + + + + + + + + +); +// While a button or a Shortcuts action runs, widget-size is "function" or "action". The +// function above then renders its own message, so nothing is drawn here. +if (family === "function" || family === "action") { +} else if (family === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only): text and an icon. + $render({`${title} · ${status}`}); +} else if (family === "accessoryCircular") { + $render( + + + + {done ? "Done" : remaining === null ? "Start" : remaining === 0 ? "Due" : `${remaining}d`} + + , + ); +} else if (family === "accessoryRectangular") { + $render( + + {title} + {status} + , + ); +} else { + // Home Screen sizes share one layout; the parts marked family !== "small" are left out + // where there is no room. frame="max" fills the widget; padding is the space around the + // content, in points. + $render( + + + + {title} + + + {family !== "small" && ( + + CARE JOURNAL + + )} + + + + + + {status} + + {family !== "small" && ( + {`${days.length} care ${days.length === 1 ? "day" : "days"} · last year`} + )} + {family !== "small" && ( + + {level} + + )} + + + {/* Each button runs the action with this id from widget.json. */} + + + + + {/* Large sizes only: the last care, the interval and the last seven days. */} + {!["small", "medium"].includes(family) && ( + + + {last ? `Last care: ${last}` : "Your first care check-in starts the journal."} + + {`Personal interval: ${config.intervalDays} days`} + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? "✓" : "—"} + + + ))} + + )} + , + ); +} diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/lib/records.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/lib/records.js index e9eaef0f..3e1682ad 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/lib/records.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/lib/records.js @@ -1,111 +1,216 @@ // Identical package-local helper in the built-in record templates. // Rendering is read-only. Keep at most 366 local calendar days; no network/iCloud sync. +// main.jsx imports this file ("lib/records.js") and then uses `localRecords`. +// It keeps one value per calendar day in $storage (permission "storage" in widget.json) +// and reads the settings saved by Records & Configuration in the app. var localRecords = (() => { - const keyFor = (date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; - const offset = (date, days) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // Day key in local time, for example "2026-03-08". + const keyFor = (date) => + `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`; + // The same calendar day shifted by `days`, at noon so daylight saving time cannot move it. + const offset = (date, days) => + new Date(date.getFullYear(), date.getMonth(), date.getDate() + days, 12); + // True for a real calendar date written as YYYY-MM-DD (2026-02-31 is rejected). const validDate = (key) => { if (typeof key !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(key)) return false; const parts = key.split("-").map(Number); return parts[0] >= 1970 && keyFor(new Date(parts[0], parts[1] - 1, parts[2], 12)) === key; }; + // A deep copy, so a caller cannot change the saved state by accident. const clone = (value) => JSON.parse(JSON.stringify(value)); + // create(key, validValue, empty) returns the record log stored under `key`. + // validValue(value) says whether a day's value is acceptable; `empty` is the value of a + // day without a record; `at` is the current time. function create(key, validValue, empty, at = new Date()) { - const now = offset(at, 0), today = keyFor(now), oldest = keyFor(offset(now, -365)); - const invalid = () => { throw new Error("Saved history is invalid. Restore your records before making changes."); }; + const now = offset(at, 0), + today = keyFor(now), + oldest = keyFor(offset(now, -365)); + const invalid = () => { + throw new Error("Saved history is invalid. Restore your records before making changes."); + }; + // Turn the saved text into { version, revision, entries: [{ date, value }], undo }, + // or throw if anything about it is unexpected. function parse(raw) { - if (raw === "") return {version: 1, revision: 0, entries: [], undo: null}; + // Nothing saved yet: start with an empty history. + if (raw === "") return { version: 1, revision: 0, entries: [], undo: null }; if (typeof raw !== "string" || raw.length > 64000) return invalid(); let state; - try { state = JSON.parse(raw); } catch (_) { return invalid(); } - if (!state || state.version !== 1 || !Number.isSafeInteger(state.revision) || state.revision < 0 || - Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || !Array.isArray(state.entries) || state.entries.length > 366) return invalid(); + try { + state = JSON.parse(raw); + } catch (_) { + return invalid(); + } + // Exactly the four expected keys, and at most 366 days. + if ( + !state || + state.version !== 1 || + !Number.isSafeInteger(state.revision) || + state.revision < 0 || + Object.keys(state).sort().join(",") !== "entries,revision,undo,version" || + !Array.isArray(state.entries) || + state.entries.length > 366 + ) + return invalid(); const dates = new Set(); + // Every entry is { date, value } with a real, unique date and an acceptable value. for (const entry of state.entries) { - if (!entry || Object.keys(entry).sort().join(",") !== "date,value" || !validDate(entry.date) || dates.has(entry.date) || !validValue(entry.value)) return invalid(); + if ( + !entry || + Object.keys(entry).sort().join(",") !== "date,value" || + !validDate(entry.date) || + dates.has(entry.date) || + !validValue(entry.value) + ) + return invalid(); dates.add(entry.date); } - if (state.undo !== null && (!state.undo || Object.keys(state.undo).sort().join(",") !== "date,value" || !validDate(state.undo.date) || - (state.undo.value !== null && !validValue(state.undo.value)))) return invalid(); + // `undo` is null, or the { date, value } that the last change replaced (null = no record). + if ( + state.undo !== null && + (!state.undo || + Object.keys(state.undo).sort().join(",") !== "date,value" || + !validDate(state.undo.date) || + (state.undo.value !== null && !validValue(state.undo.value))) + ) + return invalid(); return state; } + // $storage.getString returns "" when nothing was saved under the key. const read = () => parse($storage.getString(key)); + // The value recorded on `date` (today by default), or a copy of `empty`. const value = (state, date = today) => { const entry = state.entries.find((item) => item.date === date); return entry ? clone(entry.value) : clone(empty); }; + // Save a change. transform(state) returns the new state, or null for "nothing to save". + // compareAndSetString writes only if the stored text is still `raw`; if the app or + // another widget saved in between, read again and retry, up to 4 times. function commit(transform) { for (let attempt = 0; attempt < 4; attempt++) { - const raw = $storage.getString(key), state = parse(raw); + const raw = $storage.getString(key), + state = parse(raw); const next = transform(clone(state)); if (next === null) return false; if (state.revision >= Number.MAX_SAFE_INTEGER) return invalid(); next.revision = state.revision + 1; - next.entries = next.entries.filter((entry) => entry.date >= oldest).sort((a, b) => a.date.localeCompare(b.date)); - if (next.entries.length > 366) throw new Error("History is full. Export records before adding another date."); + // Drop days older than 365 days and keep the entries sorted by date. + next.entries = next.entries + .filter((entry) => entry.date >= oldest) + .sort((a, b) => a.date.localeCompare(b.date)); + if (next.entries.length > 366) + throw new Error("History is full. Export records before adding another date."); const encoded = JSON.stringify(next); - if (encoded.length > 64000) throw new Error("History is full. Export records before adding more data."); + if (encoded.length > 64000) + throw new Error("History is full. Export records before adding more data."); if ($storage.compareAndSetString(key, raw, encoded)) return true; } throw new Error("Could not save. Storage is busy or unavailable; please try again."); } - const edit = (update) => commit((state) => { - const old = state.entries.find((entry) => entry.date === today); - const next = update(value(state)); - if (next !== null && !validValue(next)) throw new Error("Invalid record value."); - if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) return null; - state.undo = {date: today, value: old ? old.value : null}; - state.entries = state.entries.filter((entry) => entry.date !== today); - if (next !== null) state.entries.push({date: today, value: next}); - return state; - }); - const undo = () => commit((state) => { - if (!state.undo) return null; - if (state.undo.date < oldest) throw new Error("The last change is outside the retained history window."); - const previous = state.undo; - state.entries = state.entries.filter((entry) => entry.date !== previous.date); - if (previous.value !== null) state.entries.push(previous); - state.undo = null; - return state; - }); - const recent = (state, count = 7) => Array.from({length: count}, (_, index) => { - const date = keyFor(offset(now, index - count + 1)); - return {date, value: value(state, date), recorded: state.entries.some((entry) => entry.date === date)}; - }); - return {today, read, value, edit, undo, reset: () => edit(() => null), recent}; + // Replace today's value with update(currentValue). Returning null removes today's record. + const edit = (update) => + commit((state) => { + const old = state.entries.find((entry) => entry.date === today); + const next = update(value(state)); + if (next !== null && !validValue(next)) throw new Error("Invalid record value."); + // Nothing changed: do not save, and keep the undo step as it is. + if ((old && JSON.stringify(old.value) === JSON.stringify(next)) || (!old && next === null)) + return null; + // Remember what today looked like, so undo() can put it back. + state.undo = { date: today, value: old ? old.value : null }; + state.entries = state.entries.filter((entry) => entry.date !== today); + if (next !== null) state.entries.push({ date: today, value: next }); + return state; + }); + // Put back what the last edit replaced. Only one step can be undone. + const undo = () => + commit((state) => { + if (!state.undo) return null; + if (state.undo.date < oldest) + throw new Error("The last change is outside the retained history window."); + const previous = state.undo; + state.entries = state.entries.filter((entry) => entry.date !== previous.date); + if (previous.value !== null) state.entries.push(previous); + state.undo = null; + return state; + }); + // The last `count` days, oldest first: { date, value, recorded } for each. + const recent = (state, count = 7) => + Array.from({ length: count }, (_, index) => { + const date = keyFor(offset(now, index - count + 1)); + return { + date, + value: value(state, date), + recorded: state.entries.some((entry) => entry.date === date), + }; + }); + // What main.jsx can use. `today` is today's day key. + return { today, read, value, edit, undo, reset: () => edit(() => null), recent }; } + // configuration(kind) returns the settings of one template. Records & Configuration saves + // them under "recordTemplate.config.v1"; without a saved copy the defaults below apply. function configuration(kind) { const defaults = { - plantCare: {title: "My plant", intervalDays: 3}, pocketPet: {title: "Pebble"}, - hydration: {goal: 8, glassML: 250}, mood: {intention: "Pause, breathe, and notice"}, - checklist: {items: ["Passport", "Charger", "Headphones"]}, habitStreak: {title: "Daily habit"}, - habitHeatmap: {readName: "Read", runName: "Run", meditateName: "Meditate"}, + plantCare: { title: "My plant", intervalDays: 3 }, + pocketPet: { title: "Pebble" }, + hydration: { goal: 8, glassML: 250 }, + mood: { intention: "Pause, breathe, and notice" }, + checklist: { items: ["Passport", "Charger", "Headphones"] }, + habitStreak: { title: "Daily habit" }, + habitHeatmap: { readName: "Read", runName: "Run", meditateName: "Meditate" }, + }; + const invalid = () => { + throw new Error( + "Saved template configuration is invalid. Open Records & Configuration to repair it.", + ); }; - const invalid = () => { throw new Error("Saved template configuration is invalid. Open Records & Configuration to repair it."); }; if (!Object.prototype.hasOwnProperty.call(defaults, kind)) return invalid(); const raw = $storage.getString("recordTemplate.config.v1"); if (raw === "") return clone(defaults[kind]); if (typeof raw !== "string" || raw.length > 4096) return invalid(); let state; try { + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. if (unescape(encodeURIComponent(raw)).length > 4096) return invalid(); state = JSON.parse(raw); - } catch (_) { return invalid(); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== kind || - !state.values || Array.isArray(state.values) || Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",")) return invalid(); + } catch (_) { + return invalid(); + } + // It must be { version: 1, kind, values }, and `values` must have the keys of the defaults. + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== kind || + !state.values || + Array.isArray(state.values) || + Object.keys(state.values).sort().join(",") !== Object.keys(defaults[kind]).sort().join(",") + ) + return invalid(); const value = state.values; - const text = (input, length, empty = false) => typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); - const integer = (input, minimum, maximum) => Number.isInteger(input) && input >= minimum && input <= maximum; + // Two small checks: a text of at most `length` characters, a whole number in a range. + const text = (input, length, empty = false) => + typeof input === "string" && input.length <= length && (empty || input.trim() !== ""); + const integer = (input, minimum, maximum) => + Number.isInteger(input) && input >= minimum && input <= maximum; let valid = false; + // Each template has its own limits. if (kind === "plantCare") valid = text(value.title, 40) && integer(value.intervalDays, 1, 30); if (kind === "pocketPet") valid = text(value.title, 40); - if (kind === "hydration") valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); + if (kind === "hydration") + valid = integer(value.goal, 1, 32) && integer(value.glassML, 25, 2000); if (kind === "mood") valid = text(value.intention, 80, true); if (kind === "habitStreak") valid = text(value.title, 40); - if (kind === "habitHeatmap") valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); - if (kind === "checklist") valid = Array.isArray(value.items) && value.items.length >= 1 && value.items.length <= 8 && - new Set(value.items).size === value.items.length && value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); + if (kind === "habitHeatmap") + valid = ["readName", "runName", "meditateName"].every((key) => text(value[key], 40)); + if (kind === "checklist") + valid = + Array.isArray(value.items) && + value.items.length >= 1 && + value.items.length <= 8 && + new Set(value.items).size === value.items.length && + value.items.every((item) => text(item, 60) && item === item.trim().normalize("NFC")); if (!valid) return invalid(); return clone(value); } - return {create, configuration}; + return { create, configuration }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/main.jsx index 0442b10c..604b3a74 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pocket Pet/main.jsx @@ -1,19 +1,251 @@ // A local virtual companion. Only explicit daily care changes its journal. -if(!$import("lib/records.js"))throw new Error("Install the complete Pocket Pet template."); -const config=localRecords.configuration("pocketPet"),title=($getenv("widget-param")||config.title).trim(),order=["feed","play","rest"]; -if(!title||title.length>40)throw new Error("Use a pet name of 1–40 characters."); -const valid=value=>Array.isArray(value)&&value.length>=1&&value.length<=3&&new Set(value).size===value.length&&value.every(action=>order.includes(action)); -const log=localRecords.create("pocketPet.v1",valid,[],new Date($getenv("timeline-date")||Date.now())); -function care(action){const changed=log.edit(value=>order.filter(item=>value.includes(item)||item===action));$render({changed?"Care saved":"Already done today"});} -function feedPet(){care("feed");}function playPet(){care("play");}function restPet(){care("rest");} -function undoRecord(){const changed=log.undo();$render({changed?"Change undone":"Nothing to undo"});} -function resetToday(){log.reset();$render(Today cleared; Undo can restore it);} -const state=log.read(),today=log.value(state),days=state.entries.filter(entry=>entry.date<=log.today),careDays=days.length,rested=today.includes("rest"),complete=today.length===3; -const last=days.map(entry=>entry.date).sort().pop(),ordinal=key=>{const [y,m,d]=key.split("-").map(Number);return Date.UTC(y,m-1,d)/86400000;}; -const gap=last?ordinal(log.today)-ordinal(last):null,status=complete?"A lovely day":rested?"Resting happily":today.length?"Enjoying your company":gap!==null&&gap>=3?"Ready to reconnect":"Ready for care",level=careDays>=30?"Close companions":careDays>=7?"Good friends":"New friends"; -const dark=$device.isdarkmode(),background=dark?"#302443":"#faf5ff",ink=dark?"#f3e8ff":"#581c87",muted=dark?"#d8b4fe":"#7e22ce",family=$getenv("widget-size"); +// +// This template shows several buttons that each save a different action for today, and +// a face drawn from shapes that changes with the saved state. Try changing the status +// texts or the colors. + +// $import runs lib/records.js from this package and returns false when that fails. The +// file defines localRecords: a diary with one entry per calendar day, kept in package storage +// (widget.json declares the "storage" permission). +if (!$import("lib/records.js")) throw new Error("Install the complete Pocket Pet template."); +// The pet's name is the widget parameter (the parameter text set for this widget), or +// else the name from the saved settings. +const config = localRecords.configuration("pocketPet"), + title = ($getenv("widget-param") || config.title).trim(), + order = ["feed", "play", "rest"]; +if (!title || title.length > 40) throw new Error("Use a pet name of 1–40 characters."); +// A day's value is a list of one to three different actions, for example ["feed", "rest"]. +const valid = (value) => + Array.isArray(value) && + value.length >= 1 && + value.length <= 3 && + new Set(value).size === value.length && + value.every((action) => order.includes(action)); +// Open the diary stored under the key "pocketPet.v1"; [] stands for a day without care. +// "timeline-date" is the moment this entry is drawn for, which is later than now when the +// system prepares the widget in advance. +const log = localRecords.create( + "pocketPet.v1", + valid, + [], + new Date($getenv("timeline-date") || Date.now()), +); +// Adds one action to today's list, keeping the order feed, play, rest. edit() returns +// false when nothing changed. +function care(action) { + const changed = log.edit((value) => + order.filter((item) => value.includes(item) || item === action), + ); + $render({changed ? "Care saved" : "Already done today"}); +} +// The functions below are the actions listed in widget.json; a button with +// actionID="feedPet" runs feedPet(). +function feedPet() { + care("feed"); +} +function playPet() { + care("play"); +} +function restPet() { + care("rest"); +} +function undoRecord() { + const changed = log.undo(); + $render({changed ? "Change undone" : "Nothing to undo"}); +} +function resetToday() { + log.reset(); + $render(Today cleared; Undo can restore it); +} +// Read the diary (reading never writes) and work out what to show. +const state = log.read(), + today = log.value(state), + days = state.entries.filter((entry) => entry.date <= log.today), + careDays = days.length, + rested = today.includes("rest"), + complete = today.length === 3; +// The latest care date, and a helper that turns "YYYY-MM-DD" into a day number. +const last = days + .map((entry) => entry.date) + .sort() + .pop(), + ordinal = (key) => { + const [y, m, d] = key.split("-").map(Number); + return Date.UTC(y, m - 1, d) / 86400000; + }; +// gap: days since the last care. status and level are the two sentences in the widget. +const gap = last ? ordinal(log.today) - ordinal(last) : null, + status = complete + ? "A lovely day" + : rested + ? "Resting happily" + : today.length + ? "Enjoying your company" + : gap !== null && gap >= 3 + ? "Ready to reconnect" + : "Ready for care", + level = careDays >= 30 ? "Close companions" : careDays >= 7 ? "Good friends" : "New friends"; +// Colors for light and dark mode, and the size being drawn ("small", "medium", …). +const dark = $device.isdarkmode(), + background = dark ? "#302443" : "#faf5ff", + ink = dark ? "#f3e8ff" : "#581c87", + muted = dark ? "#d8b4fe" : "#7e22ce", + family = $getenv("widget-size"); // Original JSX geometry; static artwork works without animation or network resources. -const Pet=()=> {rested?"−":"•"}{complete?"ᴗ":"ω"}{rested?"−":"•"}; -const CareButton=({action})=>; -const UndoButton=()=> ; -if(family==="function"||family==="action"){}else if(family==="accessoryInline"){$render({`${title} · ${today.length}/3 care`});}else if(family==="accessoryCircular"){$render({`${today.length}/3`});}else if(family==="accessoryRectangular"){$render({title}{status});}else{$render({title}{`${today.length}/3`}{status}{family!=="small"&&{level}}{family!=="small"&&{`${careDays} care days · last year`}}{family==="small"?:{order.map(action=>)}}{!["small","medium"].includes(family)&&Last 7 days{log.recent(state).map(day=>{day.date.slice(5)}{day.recorded?`${day.value.length}/3`:"—"})}Care counts once per day. Nothing to catch up or buy.});} +// Two ears above a face. The eyes close after rest, and the mouth changes when all three +// actions are done. frame is "width,height" in points; rotation is in degrees. +const Pet = () => ( + + + + + + + + + + {rested ? "−" : "•"} + + + {complete ? "ᴗ" : "ω"} + + + {rested ? "−" : "•"} + + + + +); +// A button for one action. Its text tells whether the action is already done today. +const CareButton = ({ action }) => ( + +); +const UndoButton = () => ( + +); +// While a button or a Shortcuts action runs, widget-size is "function" or "action". The +// function above then renders its own message, so nothing is drawn here. +if (family === "function" || family === "action") { +} else if (family === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only). + $render({`${title} · ${today.length}/3 care`}); +} else if (family === "accessoryCircular") { + $render( + + + {`${today.length}/3`} + , + ); +} else if (family === "accessoryRectangular") { + $render( + + {title} + {status} + , + ); +} else { + // Home Screen sizes. frame="max" fills the widget; padding is the space around the + // content, in points. The small widget gets less of both. + $render( + + + + {title} + + + {`${today.length}/3`} + + + + + + {status} + + {family !== "small" && ( + + {level} + + )} + {family !== "small" && ( + {`${careDays} care days · last year`} + )} + + + {/* Buttons: two rows in the small widget, one row in the others. */} + {family === "small" ? ( + + + + + + + + + + + ) : ( + + {order.map((action) => ( + + ))} + + + )} + {/* Large sizes only: the last seven days. */} + {!["small", "medium"].includes(family) && ( + + + Last 7 days + + {log.recent(state).map((day) => ( + + + {day.date.slice(5)} + + + + {day.recorded ? `${day.value.length}/3` : "—"} + + + ))} + + Care counts once per day. Nothing to catch up or buy. + + + )} + , + ); +} diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pomodoro Focus/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pomodoro Focus/main.jsx index c02238d5..67818857 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pomodoro Focus/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Pomodoro Focus/main.jsx @@ -1,8 +1,56 @@ // widget-param: focus minutes (optional) +// +// This template shows a number read from the widget parameter, with its own layout for +// the small widget. The progress bar is a fixed sample; nothing counts down. +// Try changing the default of 25 minutes or the colors. + +// $getenv("widget-param") is the parameter text set for this widget. An empty or +// non-numeric parameter gives 25, and anything below 5 becomes 5. const minutes = Math.max(5, Number($getenv("widget-param")) || 25); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the length of the session. - $render(FOCUS{minutes}:00One task at a time.); + // frame="max" fills the widget; padding is the space around the content, in points. + $render( + + + + + FOCUS + + + + + {minutes}:00 + + + One task at a time. + + + {/* The bar is fixed at 20%; it does not follow a timer. */} + + , + ); } else { - $render(Focus session{minutes}:00One task. No distractions.); + // Medium and larger: the same parts, with elements pushing them apart. + $render( + + + + + Focus session + + + + + + {minutes}:00 + + + One task. No distractions. + + + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Portfolio Pulse/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Portfolio Pulse/main.jsx index 4a4367b2..69ac0cda 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Portfolio Pulse/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Portfolio Pulse/main.jsx @@ -6,62 +6,139 @@ // Sample numbers keep it offline; replace them with your own data. // +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); -const history = [96.2, 97.1, 96.8, 98.4, 99.0, 98.1, 99.6, 100.4, 101.2, 100.6, 101.9, 102.4, 101.8, 103.1, 104.0, 103.2, 104.8, 105.5, 104.9, 106.2, 107.0, 106.4, 107.9, 108.6, 108.1, 109.4, 110.2, 109.6, 111.0, 112.4]; -const holdings = [["AAPL", "Apple", 231.4, 1.24], ["MSFT", "Microsoft", 421.8, 0.62], ["NVDA", "NVIDIA", 132.6, -1.85], ["AMZN", "Amazon", 186.3, 0.41], ["TSLA", "Tesla", 198.1, -2.37]]; +// Sample data: 30 daily values for the sparkline, oldest first. +const history = [ + 96.2, 97.1, 96.8, 98.4, 99.0, 98.1, 99.6, 100.4, 101.2, 100.6, 101.9, 102.4, 101.8, 103.1, 104.0, + 103.2, 104.8, 105.5, 104.9, 106.2, 107.0, 106.4, 107.9, 108.6, 108.1, 109.4, 110.2, 109.6, 111.0, + 112.4, +]; +// Each holding: [symbol, name, price, today's change in percent]. +const holdings = [ + ["AAPL", "Apple", 231.4, 1.24], + ["MSFT", "Microsoft", 421.8, 0.62], + ["NVDA", "NVIDIA", 132.6, -1.85], + ["AMZN", "Amazon", 186.3, 0.41], + ["TSLA", "Tesla", 198.1, -2.37], +]; +// The total value in dollars and today's change in percent. const value = 48261.37; const change = 1.27; -const up = "#30D158"; const down = "#FF453A"; -const money = (amount) => `$${amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; +// Colors for a rise and a fall. +const up = "#30D158"; +const down = "#FF453A"; +// money(48261.37) gives "$48,261.37"; signed(1.27) gives "+1.27%". +const money = (amount) => + `$${amount.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`; const signed = (percent) => `${percent >= 0 ? "+" : ""}${percent.toFixed(2)}%`; +// The sparkline: an area chart without axes. data is a JSON string of { label, value } +// points. 90 is subtracted so that the small ups and downs use the whole height. const Spark = ({ height }) => ( - ({ label: String(index), value: Math.round((point - 90) * 10) / 10 })))} /> + ({ + label: String(index), + value: Math.round((point - 90) * 10) / 10, + })), + )} + /> ); +// The total, with today's change in green or red. const Total = ({ font }) => ( - PORTFOLIO - {money(value)} + + PORTFOLIO + + + {money(value)} + - = 0 ? "arrow.up.right" : "arrow.down.right"} size="11" color={change >= 0 ? up : down} /> - = 0 ? up : down}>{signed(change)} today + = 0 ? "arrow.up.right" : "arrow.down.right"} + size="11" + color={change >= 0 ? up : down} + /> + = 0 ? up : down}> + {signed(change)} today + ); +// One row of the holdings list; item is one entry of `holdings`. const Holding = ({ item }) => ( - {item[0]} - {item[1]} + + {item[0]} + + + {item[1]} + - {item[2].toFixed(2)} - = 0 ? up : down} corner="5" padding="horizontal,6" frame="64,22">{signed(item[3])} + + {item[2].toFixed(2)} + + = 0 ? up : down} + corner="5" + padding="horizontal,6" + frame="64,22" + > + {signed(item[3])} + ); +// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets +// (iPhone and iPad only). if (size === "accessoryCircular") { - $render({signed(change)}); + $render( + + + + {signed(change)} + + , + ); } else if (size === "accessoryRectangular") { $render( {money(value)} {signed(change)} today - {holdings[0][0]} {signed(holdings[0][3])} · {holdings[2][0]} {signed(holdings[2][3])} - + + {holdings[0][0]} {signed(holdings[0][3])} · {holdings[2][0]} {signed(holdings[2][3])} + + , ); } else if (size === "accessoryInline") { - $render(Portfolio {signed(change)} · {money(value)}); + $render( + + Portfolio {signed(change)} · {money(value)} + , + ); } else if (size === "small") { + // Small: the total above the sparkline. padding is the space around the content. $render( - + , ); } else if (size === "medium") { + // Medium: total and sparkline on the left, three holdings on the right. $render( @@ -72,31 +149,52 @@ if (size === "accessoryCircular") { {holdings.slice(0, 3).map((item) => ( - {item[0]} + + {item[0]} + - = 0 ? up : down} corner="5" frame="62,22">{signed(item[3])} + = 0 ? up : down} + corner="5" + frame="62,22" + > + {signed(item[3])} + ))} - + , ); } else if (size === "extraLarge") { + // Extra large: a taller chart and all five holdings. $render( - {holdings.map((item) => )} - + + {holdings.map((item) => ( + + ))} + + , ); } else { + // Large: total, sparkline and four holdings. $render( - {holdings.slice(0, 4).map((item) => )} + + {holdings.slice(0, 4).map((item) => ( + + ))} + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/lib/launcher.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/lib/launcher.js index bd919728..10a44319 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/lib/launcher.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/lib/launcher.js @@ -1,46 +1,179 @@ -var quickLauncher=(()=>{ - const icons=["globe","map.fill","play.fill","star.fill","music.note","envelope.fill","phone.fill","message.fill","house.fill","checkmark.circle.fill"]; - const defaults={title:"Quick Launch",accent:"blue",items:[ - {id:"github",title:"GitHub",icon:"globe",type:"web",target:"https://github.com",input:""}, - {id:"maps",title:"Maps",icon:"map.fill",type:"app",target:"maps://",input:""}, - {id:"search",title:"Search",icon:"star.fill",type:"web",target:"https://www.google.com",input:""} - ]}; - const closed=(value,keys)=>value&&typeof value==="object"&&!Array.isArray(value)&&Object.keys(value).sort().join(",")===keys.split(",").sort().join(","); - const plain=(value,max)=>typeof value==="string"&&value.length<=max&&value.trim().length>0&&!/[\p{Cc}\p{Cf}]/u.test(value); - const encode=value=>encodeURIComponent(value).replace(/[!'()*]/g,c=>"%"+c.charCodeAt(0).toString(16).toUpperCase()); - function destination(item){ - if(!closed(item,"id,title,icon,type,target,input")||typeof item.id!=="string"||!/^[A-Za-z0-9][A-Za-z0-9-]{0,39}$/.test(item.id)||!plain(item.title,24)||!icons.includes(item.icon)||!["web","app","shortcut"].includes(item.type)||typeof item.input!=="string"||item.input.length>500||item.input.includes("\u0000"))throw new Error("Invalid launcher item. Open Records & Configuration."); - if(item.type==="shortcut"){ - if(!plain(item.target,128))throw new Error("Enter the name of a saved shortcut."); - return "shortcuts://run-shortcut?name="+encode(item.target)+(item.input?"&input=text&text="+encode(item.input):""); +// Settings for Quick Launcher. main.jsx loads this file and calls +// quickLauncher.options(). The checks are strict because a link is typed by the user and +// then opened by the system. +var quickLauncher = (() => { + // The SF Symbol names that an item may use as its icon. + const icons = [ + "globe", + "map.fill", + "play.fill", + "star.fill", + "music.note", + "envelope.fill", + "phone.fill", + "message.fill", + "house.fill", + "checkmark.circle.fill", + ]; + // Used when nothing has been saved. type is "web", "app" (an app's own URL scheme, such + // as maps://) or "shortcut" (target is the name of a shortcut in Apple's Shortcuts app, + // input is optional text passed to it). + const defaults = { + title: "Quick Launch", + accent: "blue", + items: [ + { + id: "github", + title: "GitHub", + icon: "globe", + type: "web", + target: "https://github.com", + input: "", + }, + { id: "maps", title: "Maps", icon: "map.fill", type: "app", target: "maps://", input: "" }, + { + id: "search", + title: "Search", + icon: "star.fill", + type: "web", + target: "https://www.google.com", + input: "", + }, + ], + }; + // True for a plain object that has exactly the listed keys. + const closed = (value, keys) => + value && + typeof value === "object" && + !Array.isArray(value) && + Object.keys(value).sort().join(",") === keys.split(",").sort().join(","); + // True for a non-blank string of at most `max` characters without control characters. + const plain = (value, max) => + typeof value === "string" && + value.length <= max && + value.trim().length > 0 && + !/[\p{Cc}\p{Cf}]/u.test(value); + // Percent-encodes text for a URL, including the characters encodeURIComponent leaves. + const encode = (value) => + encodeURIComponent(value).replace( + /[!'()*]/g, + (c) => "%" + c.charCodeAt(0).toString(16).toUpperCase(), + ); + // Checks one item and returns the URL to open for it. + function destination(item) { + if ( + !closed(item, "id,title,icon,type,target,input") || + typeof item.id !== "string" || + !/^[A-Za-z0-9][A-Za-z0-9-]{0,39}$/.test(item.id) || + !plain(item.title, 24) || + !icons.includes(item.icon) || + !["web", "app", "shortcut"].includes(item.type) || + typeof item.input !== "string" || + item.input.length > 500 || + item.input.includes("\u0000") + ) + throw new Error("Invalid launcher item. Open Records & Configuration."); + // A shortcut is run by name through the URL scheme of the Shortcuts app. + if (item.type === "shortcut") { + if (!plain(item.target, 128)) throw new Error("Enter the name of a saved shortcut."); + return ( + "shortcuts://run-shortcut?name=" + + encode(item.target) + + (item.input ? "&input=text&text=" + encode(item.input) : "") + ); } - if(item.input!==""||!plain(item.target,2048)||/[\s\\]/u.test(item.target)||/%(?![0-9a-f]{2})/i.test(item.target))throw new Error("Enter a valid URL without spaces or credentials."); - const match=/^([A-Za-z][A-Za-z0-9+.-]*):/.exec(item.target);if(!match)throw new Error("An absolute URL is required."); - const scheme=match[1].toLowerCase(),authority=item.target.slice(match[0].length).startsWith("//")?item.target.slice(match[0].length+2).split(/[/?#]/)[0]:""; - if(authority.includes("@"))throw new Error("URL credentials are not supported."); - if(item.type==="web"){ - const web=/^https?:\/\/(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::([0-9]{1,5}))?(?:[/?#]|$)/i.exec(item.target); - if(!web||(web[1]!==undefined&&(Number(web[1])<1||Number(web[1])>65535)))throw new Error("Use an HTTP(S) web link."); - }else if(["http","https","file","data","javascript","about","blob","widget-deeplink","scriptwidget","prefs","app-prefs"].includes(scheme))throw new Error("Use an external app URL scheme."); + // Web and app links: no input text, spaces, backslashes or broken percent escapes. + if ( + item.input !== "" || + !plain(item.target, 2048) || + /[\s\\]/u.test(item.target) || + /%(?![0-9a-f]{2})/i.test(item.target) + ) + throw new Error("Enter a valid URL without spaces or credentials."); + // Take the scheme ("https", "maps", …) and the host part, and refuse user:password@host. + const match = /^([A-Za-z][A-Za-z0-9+.-]*):/.exec(item.target); + if (!match) throw new Error("An absolute URL is required."); + const scheme = match[1].toLowerCase(), + authority = item.target.slice(match[0].length).startsWith("//") + ? item.target.slice(match[0].length + 2).split(/[/?#]/)[0] + : ""; + if (authority.includes("@")) throw new Error("URL credentials are not supported."); + if (item.type === "web") { + // A web link must be http or https with a host and, if given, a port from 1 to 65535. + const web = + /^https?:\/\/(?:[A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(?::([0-9]{1,5}))?(?:[/?#]|$)/i.exec( + item.target, + ); + if (!web || (web[1] !== undefined && (Number(web[1]) < 1 || Number(web[1]) > 65535))) + throw new Error("Use an HTTP(S) web link."); + } else if ( + [ + "http", + "https", + "file", + "data", + "javascript", + "about", + "blob", + "widget-deeplink", + "scriptwidget", + "prefs", + "app-prefs", + ].includes(scheme) + ) + // An app link must use the app's own scheme, not a web, file or ScriptWidget one. + throw new Error("Use an external app URL scheme."); return item.target; } - function validate(value){ - if(!closed(value,"title,accent,items")||!plain(value.title,40)||!["blue","green","rose"].includes(value.accent)||!Array.isArray(value.items)||value.items.length<1||value.items.length>6||new Set(value.items.map(item=>item?.id)).size!==value.items.length)throw new Error("Configure a title, accent and 1–6 unique launcher links."); + // Checks the whole settings object: a title, an accent color and 1–6 items with different ids. + function validate(value) { + if ( + !closed(value, "title,accent,items") || + !plain(value.title, 40) || + !["blue", "green", "rose"].includes(value.accent) || + !Array.isArray(value.items) || + value.items.length < 1 || + value.items.length > 6 || + new Set(value.items.map((item) => item?.id)).size !== value.items.length + ) + throw new Error("Configure a title, accent and 1–6 unique launcher links."); value.items.forEach(destination); - if(unescape(encodeURIComponent(JSON.stringify({version:1,kind:"launcher",values:value}))).length>32768)throw new Error("Launcher configuration exceeds 32 KiB."); + // The size limit is measured in UTF-8 bytes. + if ( + unescape(encodeURIComponent(JSON.stringify({ version: 1, kind: "launcher", values: value }))) + .length > 32768 + ) + throw new Error("Launcher configuration exceeds 32 KiB."); return value; } - function options(raw,parameter){ - let result={...defaults,items:defaults.items.map(item=>({...item}))}; - if(raw!==null&&raw!==undefined&&raw!==""){ - if(typeof raw!=="string"||raw.length>32768)throw new Error("Invalid launcher configuration."); - const saved=JSON.parse(raw);if(!closed(saved,"version,kind,values")||saved.version!==1||saved.kind!=="launcher")throw new Error("Invalid launcher configuration.");result=validate(saved.values); + // raw: the saved settings string. parameter: the widget parameter, a JSON object that may + // replace title, accent or items for one widget. Returns the settings with a url on + // every item. + function options(raw, parameter) { + let result = { ...defaults, items: defaults.items.map((item) => ({ ...item })) }; + if (raw !== null && raw !== undefined && raw !== "") { + if (typeof raw !== "string" || raw.length > 32768) + throw new Error("Invalid launcher configuration."); + const saved = JSON.parse(raw); + if (!closed(saved, "version,kind,values") || saved.version !== 1 || saved.kind !== "launcher") + throw new Error("Invalid launcher configuration."); + result = validate(saved.values); } - if(parameter){ - if(typeof parameter!=="string"||parameter.length>32768)throw new Error("Invalid launcher parameter."); - const overrides=JSON.parse(parameter);if(!overrides||typeof overrides!=="object"||Array.isArray(overrides)||Object.keys(overrides).some(key=>!Object.hasOwn(defaults,key)))throw new Error("Unknown launcher setting.");result={...result,...overrides}; + if (parameter) { + if (typeof parameter !== "string" || parameter.length > 32768) + throw new Error("Invalid launcher parameter."); + const overrides = JSON.parse(parameter); + if ( + !overrides || + typeof overrides !== "object" || + Array.isArray(overrides) || + Object.keys(overrides).some((key) => !Object.hasOwn(defaults, key)) + ) + throw new Error("Unknown launcher setting."); + result = { ...result, ...overrides }; } - validate(result);return {...result,items:result.items.map(item=>({...item,url:destination(item)}))}; + validate(result); + return { ...result, items: result.items.map((item) => ({ ...item, url: destination(item) })) }; } - return {options,destination}; + return { options, destination }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/main.jsx index 5e4135d9..5232f471 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Quick Launcher/main.jsx @@ -1,17 +1,105 @@ // Configure web links, app URLs and saved Shortcuts in Records & Configuration. -if(!$import("lib/launcher.js"))throw new Error("Install the complete Quick Launcher template."); -const config=quickLauncher.options($storage.getString("recordTemplate.config.v1"),$getenv("widget-param")); -const size=$getenv("widget-size"),dark=$device.isdarkmode(),small=size==="small"; -const background=dark?"#111827":"#eff6ff",text=dark?"#f8fafc":"#1e3a8a",muted=dark?"#cbd5e1":"#475569",accent={blue:"#2563eb",green:"#15803d",rose:"#be185d"}[config.accent]; -const Tile=({item})=>{item.title}; -if(size==="accessoryInline"){ - const first=config.items[0];$render({first.title}); -}else if(size==="accessoryCircular"){ - const first=config.items[0];$render({first.title}); -}else if(size==="accessoryRectangular"){ - const first=config.items[0];$render({first.title}{config.title}); -}else{ - const columns=small?1:3,limit=small?1:size==="medium"?3:6,items=config.items.slice(0,limit),rows=[]; - for(let i=0;i{config.title}{rows.map(row=>{row.map(item=>)})}{!small&&size!=="medium"&&Tap a link · test and reorder in ScriptWidget}); +// +// This template shows tiles to tap: each opens a web page, an app or a Shortcut. +// Try changing the colors below, or the default links in lib/launcher.js. + +// $import runs lib/launcher.js from this package and returns false when that fails. +// The file defines quickLauncher. +if (!$import("lib/launcher.js")) throw new Error("Install the complete Quick Launcher template."); +// Read the saved settings from $storage (widget.json declares the "storage" permission) +// and the widget parameter: the parameter text set for this widget, here optional JSON. +// Every item comes back with a ready-to-open `url`. +const config = quickLauncher.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// The size being drawn, and whether the system is in dark mode. +const size = $getenv("widget-size"), + dark = $device.isdarkmode(), + small = size === "small"; +// Colors for light and dark mode; the accent color is chosen in the settings. +const background = dark ? "#111827" : "#eff6ff", + text = dark ? "#f8fafc" : "#1e3a8a", + muted = dark ? "#cbd5e1" : "#475569", + accent = { blue: "#2563eb", green: "#15803d", rose: "#be185d" }[config.accent]; +// One tile: an icon above a title. Tapping it opens item.url. +const Tile = ({ item }) => ( + + + + + {item.title} + + + +); +if (size === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only) show the first link only. + const first = config.items[0]; + $render( + + {first.title} + , + ); +} else if (size === "accessoryCircular") { + const first = config.items[0]; + $render( + + + + {first.title} + + , + ); +} else if (size === "accessoryRectangular") { + const first = config.items[0]; + $render( + + + + + {first.title} + {config.title} + + + , + ); +} else { + // Home Screen sizes: one tile in the small widget, three in the medium, up to six in the + // larger ones, in rows of `columns` tiles. + const columns = small ? 1 : 3, + limit = small ? 1 : size === "medium" ? 3 : 6, + items = config.items.slice(0, limit), + rows = []; + // Cut the list into rows. + for (let i = 0; i < items.length; i += columns) rows.push(items.slice(i, i + columns)); + // linkurl on the root element is the fallback target, the first link, for a tap that + // does not open a tile. frame="max" fills the widget; padding is the space around the + // content, in points. + $render( + + + {config.title} + + {rows.map((row) => ( + + {row.map((item) => ( + + ))} + + ))} + {!small && size !== "medium" && ( + + Tap a link · test and reorder in ScriptWidget + + )} + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reading Goal/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reading Goal/main.jsx index 7bdf01d9..6f0626cf 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reading Goal/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reading Goal/main.jsx @@ -1,8 +1,55 @@ // widget-param: books read,goal (optional), e.g. 7,12 -const values = ($getenv("widget-param") || "7,12").split(",").map(Number); const read = values[0] || 0; const goal = values[1] || 12; +// +// This template shows two numbers from the widget parameter and a progress bar. +// Try changing the default "7,12" or the texts. + +// $getenv("widget-param") is the parameter text set for this widget; "7,12" becomes [7, 12]. +const values = ($getenv("widget-param") || "7,12").split(",").map(Number); +// A missing or non-numeric part falls back to 0 books read and a goal of 12. +const read = values[0] || 0; +const goal = values[1] || 12; +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: books read out of the goal. - $render(READING{read} of {goal}books · {Math.max(0, goal-read)} to go); + // frame="max" fills the widget; padding is the space around the content, in points. + $render( + + + + + READING + + + + + {read} of {goal} + + + books · {Math.max(0, goal - read)} to go + + + {/* draws a bar filled to value out of total. */} + + , + ); } else { - $render(READING GOAL{read} of {goal} books{Math.max(0, goal-read)} to go · keep turning pages); + // Medium and larger: the same information with longer texts. + $render( + + + + + + READING GOAL + + + + {read} of {goal} books + + + + {Math.max(0, goal - read)} to go · keep turning pages + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reminders Agenda/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reminders Agenda/main.jsx index 8fac2240..0809063e 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reminders Agenda/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Reminders Agenda/main.jsx @@ -2,57 +2,113 @@ // Declare reminders, remindersWrite and storage. Grant access and select lists in Settings. // Optional widget parameter: comma-separated list IDs from $reminders.lists(). // Browser previews use editable samples; native templates never seed fake reminders. +// +// $reminders runs on iPhone and iPad, and on Mac. It does not run on Android, Windows +// or Linux. +// This template shows how to read system data that needs permission, how to show a +// helpful message for every way that can fail, and how a button changes data safely. +// Try changing `limit` or the colors. + +// The size being drawn. The Lock Screen sizes (iPhone and iPad only) start with "accessory". const size = $getenv("widget-size"); const accessory = size.startsWith("accessory"); +// Lock Screen widgets use the system's own colors ("primary", "secondary"). const dark = $device.isdarkmode(); -const foreground = accessory ? "primary" : (dark ? "#f3f4f6" : "#172033"); -const secondary = accessory ? "secondary" : (dark ? "#9ca3af" : "#68758b"); -const background = accessory ? "clear" : (dark ? "#131b2a" : "#f4f7fc"); +const foreground = accessory ? "primary" : dark ? "#f3f4f6" : "#172033"; +const secondary = accessory ? "secondary" : dark ? "#9ca3af" : "#68758b"; +const background = accessory ? "clear" : dark ? "#131b2a" : "#f4f7fc"; const accent = accessory ? "primary" : "#5274d9"; const small = size === "small" || size === "systemSmall"; -const limit = accessory || small ? 2 : (size === "medium" || size === "systemMedium" ? 3 : 6); -let items = [], message = "", authorized = false, stale = false, failed = false; +// How many reminders to ask for: 2 in small and Lock Screen sizes, 3 in medium, else 6. +const limit = accessory || small ? 2 : size === "medium" || size === "systemMedium" ? 3 : 6; +// What the query found. `message` is shown instead of the list, or below it. +let items = [], + message = "", + authorized = false, + stale = false, + failed = false; +// A "complete" request that was started and not yet confirmed; {} when there is none. +// $storage holds values saved for this package ("storage" permission in widget.json). const pendingWrite = $storage.getJSON("pending-reminder-write"); - +// Read the reminders, unless a button action is running: widget-size is then "action" or +// "function", and the action reads what it needs itself. if (size !== "action" && size !== "function") { -try { - if (!$reminders.isAvailable()) message = "Reminders is unavailable on this device."; - else if ($reminders.authorizationStatus() !== "authorized") message = small ? "Settings → Reminders in ScriptWidget." : "Connect Reminders in ScriptWidget Settings."; - else { - authorized = true; - const parameter = $getenv("widget-param").trim(); - const options = { limit, maxAgeSeconds: 60 }; - if (parameter) options.listIDs = parameter.split(",").map(id => id.trim()).filter(Boolean); - const result = await $reminders.items(options); - items = Array.isArray(result.items) ? result.items : []; - stale = result.stale; - if (!items.length) message = "No reminders due today."; + try { + // Check in order: does this system have Reminders, and has the user granted access? + if (!$reminders.isAvailable()) message = "Reminders is unavailable on this device."; + else if ($reminders.authorizationStatus() !== "authorized") + message = small + ? "Settings → Reminders in ScriptWidget." + : "Connect Reminders in ScriptWidget Settings."; + else { + authorized = true; + // The widget parameter (the parameter text set for this widget) may name the lists to + // read. maxAgeSeconds: a saved result up to 60 seconds old may be reused. + const parameter = $getenv("widget-param").trim(); + const options = { limit, maxAgeSeconds: 60 }; + if (parameter) + options.listIDs = parameter + .split(",") + .map((id) => id.trim()) + .filter(Boolean); + // Needs the "reminders" permission in widget.json. Without start and end, items() + // returns the reminders due today, from local midnight to the next. + const result = await $reminders.items(options); + items = Array.isArray(result.items) ? result.items : []; + // stale is true when the result is a saved one that is older than 60 seconds. + stale = result.stale; + if (!items.length) message = "No reminders due today."; + } + } catch (error) { + // The error text contains a code. Turn the known ones into a hint, shorter in small sizes. + failed = true; + message = String(error).includes("No Reminder lists") + ? small || accessory + ? "Choose reminder lists in Settings." + : "Choose reminder lists in ScriptWidget Settings." + : String(error).includes("invalid_options") + ? small || accessory + ? "Review Reminders selection." + : "Review your Reminders selection and widget parameter." + : small || accessory + ? "Open ScriptWidget to check access." + : "Reminders could not load. Open ScriptWidget to check access."; } -} catch (error) { - failed = true; - message = String(error).includes("No Reminder lists") ? (small || accessory ? "Choose reminder lists in Settings." : "Choose reminder lists in ScriptWidget Settings.") - : String(error).includes("invalid_options") ? (small || accessory ? "Review Reminders selection." : "Review your Reminders selection and widget parameter.") - : (small || accessory ? "Open ScriptWidget to check access." : "Reminders could not load. Open ScriptWidget to check access."); -} - } +// A random id in UUID format that names one write request. function newRequestID() { - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, key => { const value = Math.floor(Math.random() * 16); return (key === "x" ? value : (value & 3) | 8).toString(16); }); + return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (key) => { + const value = Math.floor(Math.random() * 16); + return (key === "x" ? value : (value & 3) | 8).toString(16); + }); } +// The "complete-next" action from widget.json. The request is saved before it is sent +// and removed after it succeeded. If the outcome is unknown, the next tap sends the +// same request again, which cannot complete a second reminder. async function completeNext() { let request = $storage.getJSON("pending-reminder-write"); if (!request.requestID) { - const options = {limit: 1, maxAgeSeconds: 0}; + // maxAgeSeconds: 0 asks for fresh data, never a saved result. + const options = { limit: 1, maxAgeSeconds: 0 }; const parameter = $getenv("widget-param").trim(); - if (parameter) options.listIDs = parameter.split(",").map(id => id.trim()).filter(Boolean); + if (parameter) + options.listIDs = parameter + .split(",") + .map((id) => id.trim()) + .filter(Boolean); const result = await $reminders.items(options); - if (!result.items.length) { $render(Nothing due today); return; } + if (!result.items.length) { + $render(Nothing due today); + return; + } const item = result.items[0]; - request = {requestID: newRequestID(), listID: item.listID, id: item.id, completed: true}; - if (!$storage.setJSON("pending-reminder-write", request)) throw new Error("Could not save the reminder request. Nothing was changed."); + request = { requestID: newRequestID(), listID: item.listID, id: item.id, completed: true }; + if (!$storage.setJSON("pending-reminder-write", request)) + throw new Error("Could not save the reminder request. Nothing was changed."); } + // Needs the "remindersWrite" permission in widget.json. Always await a write. await $reminders.setCompleted(request); $storage.remove("pending-reminder-write"); $render(Reminder completed); @@ -64,34 +120,118 @@ function clearPending() { $render(Pending request cleared. Check Reminders before starting another action.); } +// The time of a reminder in the device's format, or "Today" for one without a time. function reminderTime(item) { if (!item.hasTime) return "Today"; return new Date(item.due).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); } +// Choose a layout. if (size === "action" || size === "function") { $render(Reminder action); } else if (small && (!authorized || failed)) { - $render( - Reminders - {failed ? "Review list access in Settings." : "Connect in ScriptWidget Settings."} - - Open Settings → - ); + // Small and not connected: the whole widget is a link into the ScriptWidget app. + $render( + + + + Reminders + + + {failed ? "Review list access in Settings." : "Connect in ScriptWidget Settings."} + + + + Open Settings → + + + , + ); } else if (size === "accessoryInline") { - $render({items.length ? `${reminderTime(items[0])} ${items[0].title}` : (failed ? "Check Reminders access" : authorized ? "Nothing due today" : "Connect Reminders")}); + // Lock Screen sizes (iPhone and iPad only). + $render( + + {items.length + ? `${reminderTime(items[0])} ${items[0].title}` + : failed + ? "Check Reminders access" + : authorized + ? "Nothing due today" + : "Connect Reminders"} + , + ); } else if (size === "accessoryCircular") { - $render({failed ? "Check" : authorized ? `${items.length} items` : "Connect"}); + $render( + + + + {failed ? "Check" : authorized ? `${items.length} items` : "Connect"} + + , + ); } else { + // Every other size: a header, the reminders, a message, and buttons where there is room. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - - {small ? "AGENDA" : "DUE TODAY"}{stale && Cached} - {items.map(item => {item.title || "Untitled reminder"}{reminderTime(item)})} - {!!message && {message}} - {(!authorized || failed) && !accessory && {small ? "Settings" : "Open ScriptWidget"}} - {!accessory && !small && pendingWrite.requestID && } - {!accessory && !small && authorized && !failed && items.length > 0 && } - {!accessory && } - + + + + + {small ? "AGENDA" : "DUE TODAY"} + + + {stale && ( + + Cached + + )} + + {items.map((item) => ( + + + + + {item.title || "Untitled reminder"} + + + {reminderTime(item)} + + + + + ))} + {/* The message: "No reminders due today.", or what to do about a problem. */} + {!!message && ( + + {message} + + )} + {(!authorized || failed) && !accessory && ( + + + + {small ? "Settings" : "Open ScriptWidget"} + + + )} + {/* The buttons run the actions with these ids from widget.json. */} + {!accessory && !small && pendingWrite.requestID && ( + + )} + {!accessory && !small && authorized && !failed && items.length > 0 && ( + + )} + {!accessory && } + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Savings Goal/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Savings Goal/main.jsx index de9815de..676b4354 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Savings Goal/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Savings Goal/main.jsx @@ -1,3 +1,31 @@ // widget-param: saved,target (optional), e.g. 1250,3000 -const values = ($getenv("widget-param") || "1250,3000").split(",").map(Number); const saved = values[0] || 0; const target = values[1] || 3000; -$render(Savings${saved.toLocaleString()}{Math.round(saved/target*100)}% of ${target.toLocaleString()} goal); +// +// This template shows an amount, a progress bar and a percentage, all from the widget +// parameter. Try changing the default "1250,3000" or the "$" sign. + +// $getenv("widget-param") is the parameter text set for this widget; "1250,3000" becomes +// [1250, 3000]. A missing or non-numeric part falls back to 0 saved and a target of 3000. +const values = ($getenv("widget-param") || "1250,3000").split(",").map(Number); +const saved = values[0] || 0; +const target = values[1] || 3000; +// $render draws the widget: call it once with one root element. +// frame="max" fills the widget; padding is the space around the content, in points. +$render( + + + + Savings + + + + + {/* In JSX text "$" is an ordinary character; {…} inserts a JavaScript value. */} + + ${saved.toLocaleString()} + + + + {Math.round((saved / target) * 100)}% of ${target.toLocaleString()} goal + + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Shape/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Shape/main.jsx index 3c89a2cf..8a402e7d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Shape/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Shape/main.jsx @@ -1,26 +1,54 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Shape Template -// +// // Description: Shape Example -// - +// +// Shows how to build a picture from shapes: a lays its children on top of each +// other. Try changing the frames, colors and corner radii. +// +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the shapes alone. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - - SHAPES - + {/* animation="clockCustom,20" asks for a slow rotation: half a turn every 20 seconds. */} + {/* The system decides whether a widget really moves; otherwise the shapes stand still. */} + + {/* frame is "width,height" in points; radius rounds the corners. */} + + + + + + SHAPES + + , ); } else { + // Medium and larger: the same shapes beside a column of text. $render( - - SHAPESBuild with primitivesCompose, color, rotate. - + + + + + + + + SHAPES + + + Build with primitives + + + Compose, color, rotate. + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sleep Schedule/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sleep Schedule/main.jsx index 9e350779..965ef7ff 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sleep Schedule/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sleep Schedule/main.jsx @@ -1,8 +1,74 @@ // widget-param: bedtime,wake time (optional) -const t=($getenv("widget-param")||"10:30 PM,6:30 AM").split(","); +// +// This template shows two texts from the widget parameter, with one layout for the small +// widget and one for the others. Try changing the default times or the colors. + +// $getenv("widget-param") is the parameter text set for this widget, split at the comma. +const t = ($getenv("widget-param") || "10:30 PM,6:30 AM").split(","); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the two times under each other. - $render(SLEEPBEDTIME{t[0].trim()}WAKE UP{(t[1]||"6:30 AM").trim()}); + // frame="max" fills the widget; padding is the space around the content, in points. + $render( + + + + SLEEP + + + + + + + BEDTIME + + + {t[0].trim()} + + + + + WAKE UP + + {/* The fallback covers a parameter with only one time in it. */} + + {(t[1] || "6:30 AM").trim()} + + + , + ); } else { - $render(Sleep scheduleBEDTIME{t[0].trim()}WAKE UP{(t[1]||"6:30 AM").trim()}); + // Medium and larger: the two times side by side, kept apart by . + $render( + + + + Sleep schedule + + + + + + + + + BEDTIME + + + {t[0].trim()} + + + + + + WAKE UP + + + {(t[1] || "6:30 AM").trim()} + + + + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Stock Snapshot/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Stock Snapshot/main.jsx index 4f32c42b..f3fe073f 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Stock Snapshot/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Stock Snapshot/main.jsx @@ -5,15 +5,25 @@ // Stock Snapshot (stooq.com) // widget-param: symbol, e.g. "aapl.us" // +// Shows how to download text with fetch and pick values out of CSV. +// Try another symbol in the widget parameter. +// +// $getenv("widget-param") is the parameter text set for this widget; when it is empty +// the symbol is "aapl.us". const symbol = ($getenv("widget-param") || "aapl.us").trim().toLowerCase(); const url = `https://stooq.com/q/l/?s=${symbol}&i=d`; +// fetch returns the response body as a string. A package with a widget.json must declare +// the "network" permission and the host in networkDomains for this call to work. const result = await fetch(url); +// The answer is CSV: one row per line, values separated by commas. const lines = result.trim().split("\n"); let closeValue = "-"; let openValue = "-"; let dateValue = "-"; +// The code expects a line of column names first and reads the values from the second +// line. With fewer lines, every value stays "-". if (lines.length > 1) { const cols = lines[1].split(","); dateValue = cols[1] || "-"; @@ -21,6 +31,7 @@ if (lines.length > 1) { closeValue = cols[5] || "-"; } +// The change from open to close, as an amount and as a percentage of the open. let change = "-"; if (openValue !== "-" && closeValue !== "-") { const openNum = parseFloat(openValue); @@ -32,12 +43,23 @@ if (openValue !== "-" && closeValue !== "-") { } } +// frame="max" makes the stack, and with it the background, fill the widget. $render( - Stock Snapshot - {symbol.toUpperCase()} - Close: {closeValue} - Change: {change} - Date: {dateValue} - + + Stock Snapshot + + + {symbol.toUpperCase()} + + + Close: {closeValue} + + + Change: {change} + + + Date: {dateValue} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Storage Ring/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Storage Ring/main.jsx index e4fed691..b4876234 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Storage Ring/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Storage Ring/main.jsx @@ -1,23 +1,33 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// Battery Percent Template -// -// Description: Display system battery percentage -// +// +// Storage Ring Template +// +// Description: Display how much of the device's storage is used +// +// Shows how to draw a ring from two circles. Try changing the colors or the line width. +// +// Both sizes are in bytes. let total = $device.totalDiskSpace(); let free = $device.freeDiskSpace(); let used = total - free; -let percent = used/total; +// The used share, from 0 to 1. +let percent = used / total; +// console.log writes to the script's log, not to the widget. console.log(`total = ${total}, used = ${used}, percent = ${percent}`); +// lays its children on top of each other. frame="max" fills the widget; +// padding is the space around the content, in points. $render( + {/* A full yellow ring; stroke is the line width in points. */} - - { `${Math.round(percent * 100)}%`} - + {/* trim={x} keeps the part of the circle from x to 1, so the green arc is as long as */} + {/* the used share. rotation, in degrees, turns the arc so that it ends at the top. */} + + {`${Math.round(percent * 100)}%`} + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Study Tracker/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Study Tracker/main.jsx index 50ecd7d9..37e3d752 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Study Tracker/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Study Tracker/main.jsx @@ -1,3 +1,28 @@ // widget-param: completed sessions,target (optional), e.g. 3,5 -const v=($getenv("widget-param")||"3,5").split(",").map(Number); const done=v[0]||0; const target=v[1]||5; -$render(Study streak{done>=target?"Goal complete — great work!":`${target-done} sessions left today`}); +// +// This template shows a badge, a progress bar and a text that changes when the goal is +// reached. Try changing the default "3,5" or the two messages. + +// $getenv("widget-param") is the parameter text set for this widget; "3,5" becomes [3, 5]. +const v = ($getenv("widget-param") || "3,5").split(",").map(Number); +// A missing or non-numeric part falls back to 0 sessions done and a target of 5. +const done = v[0] || 0; +const target = v[1] || 5; +// frame="max" fills the widget; padding is the space around the content, in points. +$render( + + + + + + + + Study streak + + + {/* One of two messages, chosen with a ? : expression. */} + + {done >= target ? "Goal complete — great work!" : `${target - done} sessions left today`} + + , +); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sunrise & Sunset/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sunrise & Sunset/main.jsx index a1370e7e..3a5101b5 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sunrise & Sunset/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Sunrise & Sunset/main.jsx @@ -5,9 +5,15 @@ // Sunrise & Sunset // widget-param: "lat,lon" (optional) // +// Shows how to call a web service that answers in JSON, and how to format a time. +// Try your own coordinates in the widget parameter. +// +// The default place is San Francisco. Latitude and longitude are in degrees. let lat = 37.7749; let lon = -122.4194; +// $getenv("widget-param") is the parameter text set for this widget. "48.85,2.35" +// replaces the default place; anything that is not two numbers is ignored. const param = $getenv("widget-param"); if (param) { const parts = param.split(",").map((p) => p.trim()); @@ -21,34 +27,47 @@ if (param) { } } +// formatted=0 asks the service for times in a form that new Date() can read. const url = `https://api.sunrise-sunset.org/json?lat=${lat}&lng=${lon}&formatted=0`; +// fetch returns the response body as a string. A package with a widget.json must declare +// the "network" permission and the host in networkDomains for this call to work. const result = await fetch(url); const data = JSON.parse(result); +// ?. gives undefined instead of an error when the answer has no results. const sunrise = data.results?.sunrise ? new Date(data.results.sunrise) : null; const sunset = data.results?.sunset ? new Date(data.results.sunset) : null; +// The time in the device's own format and time zone, or "-" when it is missing. const formatTime = (date) => { if (!date) return "-"; return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); }; +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the two times under each other. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - Sunrise & Sunset + + Sunrise & Sunset + + {/* + , ); } else { + // Medium and larger: the two times side by side. $render( - Sunrise & Sunset + + Sunrise & Sunset + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Insights/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Insights/main.jsx index 824fb5e8..7d603acb 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Insights/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Insights/main.jsx @@ -4,38 +4,80 @@ // // System Insights // +// Shows values from $system, which runs on every system. Try adding another value, +// such as $system.thermalState(). +// +// memory.physical is the installed memory in bytes; systemUptime() is in seconds. const memory = $system.memory(); const uptimeHours = ($system.systemUptime() / 3600).toFixed(1); const cpuCount = $system.processorCount(); const activeCpu = $system.activeProcessorCount(); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the platform and the three numbers, one on each line. - const Line = ({ title, value, color }) => {title}{value}; + // A small component: a function that returns JSX and is used below as . + const Line = ({ title, value, color }) => ( + + + {title} + + + + {value} + + + ); + // frame="max" fills the widget; padding is the space around the content, in points. $render( - SYSTEM - {$system.platform().toUpperCase()} - - - - + + + + SYSTEM + + + + {$system.platform().toUpperCase()} + + + + + , ); } else { + // Medium and larger: the platform on the left, three values on the right. $render( - SYSTEM - {$system.platform().toUpperCase()} - {$system.osVersionString()} + + + + SYSTEM + + + + {$system.platform().toUpperCase()} + + + {$system.osVersionString()} + - + - - - + + + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Status Panel/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Status Panel/main.jsx index 093a4b64..21ae34f6 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Status Panel/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/System Status Panel/main.jsx @@ -4,25 +4,35 @@ // // System Status Panel // +// Shows two gauges with colored sections, filled from $device and $system. +// Try changing the colors and sizes of the sections. +// +// battery.level is from 0 to 1; the disk sizes are in bytes. const battery = $device.battery(); const totalDisk = $device.totalDiskSpace(); const freeDisk = $device.freeDiskSpace(); +// Shares from 0 to 1. Math.max and the "> 0" test guard against odd device values. const usedDisk = Math.max(0, totalDisk - freeDisk); const diskRatio = totalDisk > 0 ? usedDisk / totalDisk : 0; const batteryRatio = battery.level || 0; +// The colored bands of a gauge: 40% green, 30% yellow, 30% red. const gaugeSections = [ { color: "#22c55e", value: 0.4 }, { color: "#fbbf24", value: 0.3 }, - { color: "#ef4444", value: 0.3 } + { color: "#ef4444", value: 0.3 }, ]; +// frame="max" makes the stack, and with it the background, fill the widget. $render( - System Status + + System Status + + {/* sections takes a JSON string; $json(value) is short for JSON.stringify(value). */} - Low Power: {$system.lowPowerMode() ? "On" : "Off"} - Thermal: {$system.thermalState()} - + {/* lowPowerMode() is true or false; thermalState() is a word such as "nominal". */} + + Low Power: {$system.lowPowerMode() ? "On" : "Off"} + + + Thermal: {$system.thermalState()} + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days To End Of Month/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days To End Of Month/main.jsx index ddfe398e..d71f0666 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days To End Of Month/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days To End Of Month/main.jsx @@ -1,18 +1,36 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// +// Shows a number computed with the Moment.js library, which ScriptWidget loads when a +// script uses `moment`. Try changing the colors or the icon. +// +// Today's weekday number (0 is Sunday). It only goes to the log; the widget does not use it. var d = new Date(); var n = d.getDay(); console.log(n); -var a = moment().endOf('month'); +// Whole days from now to the end of this month: 0 on the last day. +var a = moment().endOf("month"); var b = moment(); -var days = a.diff(b, 'days'); +var days = a.diff(b, "days"); +// frame="max" fills the widget; padding is the space around the content, in points. $render( - THIS MONTH{days}days remaining - + + + THIS MONTH + + + {days} + + + days remaining + + + + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days to End Of Year/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days to End Of Year/main.jsx index 521bf56c..fcd5a036 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days to End Of Year/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Days to End Of Year/main.jsx @@ -1,18 +1,36 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// +// Shows a number computed with the Moment.js library, which ScriptWidget loads when a +// script uses `moment`. Try changing the colors or the icon. +// +// Today's weekday number (0 is Sunday). It only goes to the log; the widget does not use it. var d = new Date(); var n = d.getDay(); console.log(n); -var a = moment().endOf('year'); +// Whole days from now to the end of this year: 0 on 31 December. +var a = moment().endOf("year"); var b = moment(); -var days = a.diff(b, 'days'); +var days = a.diff(b, "days"); +// frame="max" fills the widget; padding is the space around the content, in points. $render( - THIS YEAR{days}days remaining - + + + THIS YEAR + + + {days} + + + days remaining + + + + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Today Week/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Today Week/main.jsx index 0f86aac5..b03d6324 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Today Week/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Today Week/main.jsx @@ -1,27 +1,57 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// +// +// +// Shows the name of today's weekday. Try translating the names in `weekday`. +// var d = new Date(); +// getDay() gives 0 for Sunday up to 6 for Saturday: the position in this list. const weekday = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; let day = weekday[d.getDay()]; - +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: the weekday in a size that fits "Wednesday", and a short date. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - TODAY - {day}{d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} - + + + TODAY + + + + + + + {day} + + {/* A short date such as "Nov 18". */} + + {d.toLocaleDateString("en-US", { month: "short", day: "numeric" })} + + + , ); } else { + // Medium and larger: a bigger weekday, and the date drawn by the element. $render( - - TODAY{day} - + + + + TODAY + + + {day} + + {/* date="now" with style="date" shows today's date. */} + + + + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Year Days Left/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Year Days Left/main.jsx index 116328f1..679dcd68 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Year Days Left/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Text Year Days Left/main.jsx @@ -1,20 +1,41 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Year Days Left Template -// +// // Description: Show you how many days left this year -// +// +// The texts are Chinese: "今年还剩" is "left this year", "天" is "days" and the last +// line is "make today count". Try replacing them with your own. +// var today = new Date(); // Whole days from today's date to 31 December: 0 on the last day of the year. // Both are counted as calendar dates, so the time of day does not matter. +// The number of milliseconds in a day. Date.UTC counts months from 0, so 11 is December. var perDay = 1000 * 60 * 60 * 24; -var leftDays = Math.round((Date.UTC(today.getFullYear(), 11, 31) - Date.UTC(today.getFullYear(), today.getMonth(), today.getDate())) / perDay); +var leftDays = Math.round( + (Date.UTC(today.getFullYear(), 11, 31) - + Date.UTC(today.getFullYear(), today.getMonth(), today.getDate())) / + perDay, +); +// frame="max" fills the widget; padding is the space around the content, in points. $render( - 今年还剩{leftDays} 天把今天过得有意义 - + + + 今年还剩 + + + {leftDays} 天 + + + 把今天过得有意义 + + + + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Travel Day Dashboard/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Travel Day Dashboard/main.jsx index 171d3dab..ca130733 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Travel Day Dashboard/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Travel Day Dashboard/main.jsx @@ -1,57 +1,254 @@ // Designed for the large widget; the small and medium sizes show the essentials. widget-param: flight|origin|destination|departure|gate|weather|essentials comma-separated -const parts = ($getenv("widget-param") || "SW 218|SFO|SEA|10:40 AM|B12|58° · Light rain|Passport,Headphones,Charger").split("|"); +// +// This template shows a dashboard filled only from the widget parameter: fields +// separated by "|". Try changing the sample text below or the colors. + +// $getenv("widget-param") is the parameter text set for this widget. An empty parameter +// uses the sample, and a missing field falls back to its own default. +const parts = ( + $getenv("widget-param") || + "SW 218|SFO|SEA|10:40 AM|B12|58° · Light rain|Passport,Headphones,Charger" +).split("|"); const flight = parts[0] || "SW 218"; const origin = parts[1] || "SFO"; const destination = parts[2] || "SEA"; const departure = parts[3] || "10:40 AM"; const gate = parts[4] || "B12"; const weather = parts[5] || "58° · Light rain"; +// The last field is a list separated by commas; at most three items are shown. const essentials = (parts[6] || "Passport,Headphones,Charger").split(",").slice(0, 3); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); if (size === "small") { // Small: the route, the departure time and the gate. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - - {origin} → {destination} - GATE {gate}{departure} - + + + + + + + {origin} → {destination} + + {/* A card. frame="max,52,leading": as wide as possible, 52 points high, content kept */} + {/* to the leading side. corner rounds the background. */} + + + + GATE {gate} + + + + + {departure} + + + , ); } else if (size === "medium") { // Medium: the route above the departure, the gate and the weather. $render( + {/* The route: origin, flight number, destination. */} - {origin}DEPART - - {destination}ARRIVE + + + {origin} + + + DEPART + + + + + + + + + + + {destination} + + + ARRIVE + + + {/* Three cards of equal width. */} - DEPARTURE{departure} - GATE{gate} - DESTINATION{weather} + + + DEPARTURE + + + {departure} + + + + + GATE + + + {gate} + + + + + + DESTINATION + + + + + {weather} + + - + , ); } else { + // Large and extra large: a title, the route, the three cards and the packing list. $render( - Travel DayEverything before boarding + + + + Travel Day + + + Everything before boarding + + + + + - {origin}DEPART - - {destination}ARRIVE + + + {origin} + + + DEPART + + + + + + + + + + + {destination} + + + ARRIVE + + - DEPARTURE{departure} - GATE{gate} - DESTINATION{weather} + + + DEPARTURE + + + {departure} + + + + + GATE + + + {gate} + + + + + + DESTINATION + + + + + {weather} + + + {/* One row for each item of the packing list. */} - BEFORE YOU GO - {essentials.map(item => {item.trim()}PACKED?)} + + + BEFORE YOU GO + + + + + {essentials.map((item) => ( + + + + {item.trim()} + + + + PACKED? + + + ))} - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/lib/configuration.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/lib/configuration.js index 26de913d..3d1d2d8b 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/lib/configuration.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/lib/configuration.js @@ -1,39 +1,100 @@ // Package-relative native background selections; rendering never imports images or changes settings. +// +// Settings for Wallpaper Match. main.jsx loads this file and calls +// wallpaperConfiguration.load(). var wallpaperConfiguration = (() => { - const defaults = {title: "My space", caption: "", content: "none", ink: "adaptive", backgrounds: []}; + // Used when nothing has been saved. content is "none", "text" or "date"; ink is the + // text color: "adaptive" (follows dark mode), "light" or "dark". + const defaults = { + title: "My space", + caption: "", + content: "none", + ink: "adaptive", + backgrounds: [], + }; + // The widget sizes that can have a background. const families = ["small", "medium", "large", "extraLarge", "extraLargePortrait"]; const text = (value, length) => typeof value === "string" && value.length <= length; - const validImage = (value) => typeof value === "string" && /^background-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value); + // An image name has the form background-; its file is image/.png. + const validImage = (value) => + typeof value === "string" && + /^background-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(value); + // True when the settings have exactly the expected keys and every value is in range. function validate(value) { - if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== "backgrounds,caption,content,ink,title" || - !text(value.title, 40) || !text(value.caption, 80) || !["none", "text", "date"].includes(value.content) || !["adaptive", "light", "dark"].includes(value.ink) || - !Array.isArray(value.backgrounds) || value.backgrounds.length > 10) return false; + if ( + !value || + typeof value !== "object" || + Array.isArray(value) || + Object.keys(value).sort().join(",") !== "backgrounds,caption,content,ink,title" || + !text(value.title, 40) || + !text(value.caption, 80) || + !["none", "text", "date"].includes(value.content) || + !["adaptive", "light", "dark"].includes(value.ink) || + !Array.isArray(value.backgrounds) || + value.backgrounds.length > 10 + ) + return false; + // Each background is one image for one size and one appearance; a pair may appear once. const seen = new Set(); return value.backgrounds.every((asset) => { - if (!asset || typeof asset !== "object" || Array.isArray(asset) || Object.keys(asset).sort().join(",") !== "appearance,family,image,label" || - !families.includes(asset.family) || !["light", "dark"].includes(asset.appearance) || !validImage(asset.image) || - !text(asset.label, 30) || !asset.label.trim() || /[\p{Cc}\p{Cf}]/u.test(asset.label)) return false; + if ( + !asset || + typeof asset !== "object" || + Array.isArray(asset) || + Object.keys(asset).sort().join(",") !== "appearance,family,image,label" || + !families.includes(asset.family) || + !["light", "dark"].includes(asset.appearance) || + !validImage(asset.image) || + !text(asset.label, 30) || + !asset.label.trim() || + /[\p{Cc}\p{Cf}]/u.test(asset.label) + ) + return false; const key = asset.family + "." + asset.appearance; if (seen.has(key)) return false; - seen.add(key); return true; + seen.add(key); + return true; }); } + // Parses a settings string of the form { version: 1, kind: "wallpaper", values }. + // Damaged settings throw an error instead of being replaced by the defaults. function read(raw) { if (raw === "") return defaults; let state; - try { if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096) throw new Error(); state = JSON.parse(raw); } - catch (_) { throw new Error("Saved background settings are invalid. Open Records & Configuration to repair them."); } - if (!state || Object.keys(state).sort().join(",") !== "kind,values,version" || state.version !== 1 || state.kind !== "wallpaper" || !validate(state.values)) - throw new Error("Saved background settings are invalid. Open Records & Configuration to repair them."); + try { + // At most 4096 bytes of UTF-8. + if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096) + throw new Error(); + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved background settings are invalid. Open Records & Configuration to repair them.", + ); + } + if ( + !state || + Object.keys(state).sort().join(",") !== "kind,values,version" || + state.version !== 1 || + state.kind !== "wallpaper" || + !validate(state.values) + ) + throw new Error( + "Saved background settings are invalid. Open Records & Configuration to repair them.", + ); return state.values; } + // The settings saved in $storage come first; without them the optional file + // wallpaper.json of the package is used, and without that the defaults. function load() { const saved = $storage.getString("recordTemplate.config.v1"); if (saved !== "") return read(saved); if (!$file.exists("wallpaper.json")) return defaults; const portable = $file.read("wallpaper.json"); - if (portable === "") throw new Error("wallpaper.json is empty or unavailable. Restore or repair the package settings."); + if (portable === "") + throw new Error( + "wallpaper.json is empty or unavailable. Restore or repair the package settings.", + ); return read(portable); } - return {read, validate, load}; + return { read, validate, load }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/main.jsx index aa76aafc..67db1db5 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wallpaper Match/main.jsx @@ -1,33 +1,122 @@ // Import and calibrate your own background in Records & Configuration. // Crops match one Home Screen size, position and light/dark appearance. -if (!$import("lib/configuration.js")) throw new Error("Install the complete Wallpaper Match template."); +// +// This template shows a full-size image behind text, chosen by widget size and by light +// or dark mode. Try changing the fonts, or the texts shown while no image is set. + +// $import runs lib/configuration.js from this package and returns false when that fails. +// The file defines wallpaperConfiguration. +if (!$import("lib/configuration.js")) + throw new Error("Install the complete Wallpaper Match template."); +// The saved settings: title, caption, what to show, text color and the list of crops. const options = wallpaperConfiguration.load(); -const family = $getenv("widget-size"), appearance = $device.isdarkmode() ? "dark" : "light"; -const color = options.ink === "light" || (options.ink === "adaptive" && appearance === "dark") ? "#ffffff" : "#111827"; +// The size being drawn ("small", "medium", …) and the current appearance. +const family = $getenv("widget-size"), + appearance = $device.isdarkmode() ? "dark" : "light"; +// Text color: white or near-black, as set in the settings or following dark mode. +const color = + options.ink === "light" || (options.ink === "adaptive" && appearance === "dark") + ? "#ffffff" + : "#111827"; +// "timeline-date" is the moment this entry is drawn for, which is later than now when the +// system prepares the widget in advance. const referenceDate = new Date($getenv("timeline-date") || Date.now()); if (family === "accessoryInline") { - $render(options.content === "date" ? : {options.title || "Wallpaper Match"}); + // Lock Screen sizes (iPhone and iPad only) have no background image: a text or the date. + $render( + options.content === "date" ? ( + + ) : ( + {options.title || "Wallpaper Match"} + ), + ); } else if (family === "accessoryCircular") { - $render({options.content === "date" ? String(referenceDate.getDate()) : "Match"}); + $render( + + + + {options.content === "date" ? String(referenceDate.getDate()) : "Match"} + + , + ); } else if (family === "accessoryRectangular") { - $render({options.title || "Wallpaper Match"}{options.content === "date" ? : {options.caption || "Backgrounds apply on the Home Screen"}}); + $render( + + {options.title || "Wallpaper Match"} + {options.content === "date" ? ( + + ) : ( + {options.caption || "Backgrounds apply on the Home Screen"} + )} + , + ); } else { - const asset = options.backgrounds.find((item) => item.family === family && item.appearance === appearance); + // Home Screen sizes: find the crop saved for this size and appearance. + const asset = options.backgrounds.find( + (item) => item.family === family && item.appearance === appearance, + ); + // $file.exists checks for a file inside this package; a crop is stored as image/.png. const available = asset && $file.exists("image/" + asset.image + ".png"); if (!available) { - $render( - - {asset ? "Restore this crop" : "Match your wallpaper"} - {asset ? "The selected image file is unavailable." : `Add a ${appearance} crop for this size in Records & Configuration.`} - ); + // No crop, or its file is gone: say what to do. frame="max" fills the widget; padding + // is the space around the content, in points. + $render( + + + {asset ? "Restore this crop" : "Match your wallpaper"} + + {asset + ? "The selected image file is unavailable." + : `Add a ${appearance} crop for this size in Records & Configuration.`} + + , + ); } else { - $render( - - {options.content !== "none" && - {options.content === "date" && } - {options.title && {family === "small" ? Array.from(options.title.replace(/\s+/g, " ")).slice(0, 16).join("") : options.title}} - {options.caption && {family === "small" ? Array.from(options.caption.replace(/\s+/g, " ")).slice(0, 24).join("") : options.caption}} - } - ); + // The image fills the widget and the text lies over it in a . + $render( + + {/* mode="fill" covers the whole frame and clip="rect" cuts off what sticks out. */} + {/* accentedRenderingMode="fullColor" keeps the colors in tinted widget appearances. */} + + {options.content !== "none" && ( + + {options.content === "date" && ( + + )} + {/* The small widget cuts long texts: 16 characters of title, 24 of caption. */} + {options.title && ( + + {family === "small" + ? Array.from(options.title.replace(/\s+/g, " ")).slice(0, 16).join("") + : options.title} + + )} + {options.caption && ( + + {family === "small" + ? Array.from(options.caption.replace(/\s+/g, " ")).slice(0, 24).join("") + : options.caption} + + )} + + )} + , + ); } } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Display/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Display/main.jsx index b7473540..b7b0ded2 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Display/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Display/main.jsx @@ -1,23 +1,56 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// +// // Weather Template -// +// // Description: Display weather today -// +// +// Shows how to call a web service that answers in JSON: open-meteo.com, for Beijing. +// Try other coordinates and another title. +// -const result = await fetch("https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074¤t=temperature_2m,apparent_temperature,weather_code&timezone=auto"); +// fetch returns the response body as a string. A package with a widget.json must declare +// the "network" permission and the host in networkDomains for this call to work. +// latitude and longitude choose the place; current= lists the values wanted. +const result = await fetch( + "https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074¤t=temperature_2m,apparent_temperature,weather_code&timezone=auto", +); +// "|| {}" keeps the lines below from failing when the answer has no `current` part. const data = JSON.parse(result).current || {}; -const conditions = {0:"Clear",1:"Mostly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",61:"Rain",71:"Snow",95:"Thunderstorm"}; +// The service describes the sky with a number (a WMO weather code). Only a few are +// named here; any other code is shown as "Mixed skies". +const conditions = { + 0: "Clear", + 1: "Mostly clear", + 2: "Partly cloudy", + 3: "Overcast", + 45: "Fog", + 61: "Rain", + 71: "Snow", + 95: "Thunderstorm", +}; const condition = conditions[data.weather_code] || "Mixed skies"; +// frame="max" fills the widget; padding is the space around the content, in points. $render( - BEIJING - - {Math.round(data.temperature_2m)}° - {condition} - Feels like {Math.round(data.apparent_temperature)}° - + + + BEIJING + + + + + + + {Math.round(data.temperature_2m)}° + + + {condition} + + + Feels like {Math.round(data.apparent_temperature)}° + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Glance/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Glance/main.jsx index ac292f5b..f2672611 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Glance/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Glance/main.jsx @@ -7,36 +7,82 @@ // weather service (declare the domain in widget.json). // +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); +// Sample data. hours: [label, SF Symbol name, temperature]. days: [label, symbol, low, high]. const weather = { - city: "Cupertino", temp: 24, condition: "Mostly Sunny", icon: "sun.max.fill", high: 27, low: 15, - hours: [["Now", "sun.max.fill", 24], ["1PM", "sun.max.fill", 25], ["2PM", "cloud.sun.fill", 26], ["3PM", "cloud.sun.fill", 26], ["4PM", "cloud.fill", 24], ["5PM", "cloud.fill", 22]], - days: [["Today", "sun.max.fill", 15, 27], ["Mon", "cloud.sun.fill", 14, 25], ["Tue", "cloud.rain.fill", 12, 19], ["Wed", "cloud.fill", 13, 21], ["Thu", "sun.max.fill", 16, 28]], + city: "Cupertino", + temp: 24, + condition: "Mostly Sunny", + icon: "sun.max.fill", + high: 27, + low: 15, + hours: [ + ["Now", "sun.max.fill", 24], + ["1PM", "sun.max.fill", 25], + ["2PM", "cloud.sun.fill", 26], + ["3PM", "cloud.sun.fill", 26], + ["4PM", "cloud.fill", 24], + ["5PM", "cloud.fill", 22], + ], + days: [ + ["Today", "sun.max.fill", 15, 27], + ["Mon", "cloud.sun.fill", 14, 25], + ["Tue", "cloud.rain.fill", 12, 19], + ["Wed", "cloud.fill", 13, 21], + ["Thu", "sun.max.fill", 16, 28], + ], }; -const sky = $gradient({ type: "linear", colors: ["#2F80ED", "#56CCF2"], startPoint: "top", endPoint: "bottom" }); +// $gradient makes a value that fades from one color to another. It is used like a +// color: here as the background, further down as the color of a bar. +const sky = $gradient({ + type: "linear", + colors: ["#2F80ED", "#56CCF2"], + startPoint: "top", + endPoint: "bottom", +}); +// Sun icons are yellow, all others white. const iconColor = (name) => (name.startsWith("sun") ? "#FFD60A" : "white"); const soft = "#E3F2FD"; +// The city and the temperature now. const Header = ({ big }) => ( - {weather.city} - {weather.temp}° + + + {weather.city} + + + + + {weather.temp}° + ); +// The icon, the condition and the day's high and low. const Summary = () => ( - {weather.condition} - H:{weather.high}° L:{weather.low}° + + {weather.condition} + + + H:{weather.high}° L:{weather.low}° + ); +// The next `count` hours in columns of equal width (each has frame="max"). const Hours = ({ count }) => ( {weather.hours.slice(0, count).map(([label, icon, temp], index) => ( - {label} + + {label} + - {temp}° + + {temp}° + ))} @@ -47,63 +93,110 @@ const highest = Math.max(...weather.days.map((day) => day[3])); const Days = ({ barWidth }) => ( {weather.days.map(([label, icon, low, high]) => { + // Points of bar width per degree. const scale = barWidth / (highest - lowest); return ( - {label} + + {label} + - {low}° + + {low}° + + {/* A faint track; over it, an invisible rect pushes the colored range into place. */} - + - {high}° + + {high}° + ); })} ); +// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets +// (iPhone and iPad only). if (size === "accessoryCircular") { - $render({weather.temp}°); + $render( + + + + {weather.temp}° + + , + ); } else if (size === "accessoryRectangular") { $render( - {weather.temp}° {weather.city} + + + + {weather.temp}° {weather.city} + + {weather.condition} - H:{weather.high}° L:{weather.low}° - + + H:{weather.high}° L:{weather.low}° + + , ); } else if (size === "accessoryInline") { - $render({weather.city} {weather.temp}° · {weather.condition}); + $render( + + {weather.city} {weather.temp}° · {weather.condition} + , + ); } else if (size === "small") { + // Small: city and temperature at the top, the summary at the bottom. $render(
- + , ); } else if (size === "medium") { + // Medium: header and summary side by side, then six hours. $render( -
+ +
+ + + - + , ); } else { + // Large and extra large add the five days; the bars are wider in the extra large size. const wide = size === "extraLarge"; $render( -
+ +
+ + + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/lib/weather.js b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/lib/weather.js index 397b0829..bd6e6cdb 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/lib/weather.js +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/lib/weather.js @@ -1,204 +1,527 @@ // MET Norway Locationforecast 2.0. Forecasts are model data, not observations. // https://api.met.no/doc/TermsOfService · https://api.met.no/doc/License +// main.jsx imports this file ("lib/weather.js") and then uses `localWeather`. +// It chooses the place, asks MET Norway for its forecast and keeps a copy in $storage. var localWeather = (() => { - const cacheKey = "weather.met.v1", hour = 3600000; - const defaults = {city:"",latitude:0,longitude:0,useLocation:true,unit:"c"}; - const numeric = (value,min,max) => typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; - const keys = object => object && typeof object === "object" && !Array.isArray(object) ? Object.keys(object).sort().join(",") : ""; + // The storage key of the saved forecasts, and one hour in milliseconds. + const cacheKey = "weather.met.v1", + hour = 3600000; + // The settings. `unit` is "c" or "f"; `city` with its coordinates is the saved city. + const defaults = { city: "", latitude: 0, longitude: 0, useLocation: true, unit: "c" }; + // True for a real number between min and max. + const numeric = (value, min, max) => + typeof value === "number" && Number.isFinite(value) && value >= min && value <= max; + // The keys of a plain object, sorted and joined ("a,b,c"); "" for anything else. + const keys = (object) => + object && typeof object === "object" && !Array.isArray(object) + ? Object.keys(object).sort().join(",") + : ""; function validOptions(value) { - return keys(value) === "city,latitude,longitude,unit,useLocation" && typeof value.city === "string" && value.city.length <= 60 && - numeric(value.latitude,-90,90) && numeric(value.longitude,-180,180) && typeof value.useLocation === "boolean" && ["c","f"].includes(value.unit); + return ( + keys(value) === "city,latitude,longitude,unit,useLocation" && + typeof value.city === "string" && + value.city.length <= 60 && + numeric(value.latitude, -90, 90) && + numeric(value.longitude, -180, 180) && + typeof value.useLocation === "boolean" && + ["c", "f"].includes(value.unit) + ); } - function options(raw,parameter) { - let value = {...defaults}; + // Work out the settings: the defaults, then the configuration saved by Records & + // Configuration (`raw`), then the widget parameter: JSON, or latitude,longitude,City. + function options(raw, parameter) { + let value = { ...defaults }; if (raw !== "") { let state; - try { state = JSON.parse(raw); } catch (_) { throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); } - if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 4096 || keys(state) !== "kind,values,version" || state.version !== 1 || state.kind !== "weather" || !validOptions(state.values)) throw new Error("Saved weather settings are invalid. Open Records & Configuration to repair them."); + try { + state = JSON.parse(raw); + } catch (_) { + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); + } + if ( + typeof raw !== "string" || + // unescape(encodeURIComponent(text)).length is the size of the text in UTF-8 bytes. + unescape(encodeURIComponent(raw)).length > 4096 || + keys(state) !== "kind,values,version" || + state.version !== 1 || + state.kind !== "weather" || + !validOptions(state.values) + ) + throw new Error( + "Saved weather settings are invalid. Open Records & Configuration to repair them.", + ); value = state.values; } parameter = (parameter || "").trim(); if (parameter) { if (parameter[0] === "{") { let custom; - try { custom = JSON.parse(parameter); } catch (_) { throw new Error("Weather parameters must be valid JSON."); } - if (!custom || Array.isArray(custom) || Object.keys(custom).some(key => !Object.prototype.hasOwnProperty.call(defaults,key))) throw new Error("Weather settings accept city, latitude, longitude, useLocation and unit only."); - value = {...value,...custom}; + try { + custom = JSON.parse(parameter); + } catch (_) { + throw new Error("Weather parameters must be valid JSON."); + } + if ( + !custom || + Array.isArray(custom) || + Object.keys(custom).some((key) => !Object.prototype.hasOwnProperty.call(defaults, key)) + ) + throw new Error( + "Weather settings accept city, latitude, longitude, useLocation and unit only.", + ); + value = { ...value, ...custom }; } else { - const parts = parameter.split(",").map(value => value.trim()); - if (parts.length < 2 || parts.length > 3 || parts.slice(0,2).some(value => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value))) throw new Error("Use latitude,longitude or JSON weather settings."); - value = {...value,city:parts[2] || "Selected city",latitude:Number(parts[0]),longitude:Number(parts[1]),useLocation:false}; + // latitude,longitude with an optional city name. A fixed place turns location off. + const parts = parameter.split(",").map((value) => value.trim()); + if ( + parts.length < 2 || + parts.length > 3 || + parts.slice(0, 2).some((value) => !/^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$/.test(value)) + ) + throw new Error("Use latitude,longitude or JSON weather settings."); + value = { + ...value, + city: parts[2] || "Selected city", + latitude: Number(parts[0]), + longitude: Number(parts[1]), + useLocation: false, + }; } } - if (!validOptions(value)) throw new Error("Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit."); + if (!validOptions(value)) + throw new Error( + "Choose valid coordinates, a city label up to 60 characters and Celsius or Fahrenheit.", + ); return value; } - const rounded = value => Number(value.toFixed(2)); - const placeKey = (source,latitude,longitude) => `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; - const validHTTPDate = value => typeof value === "string" && /^[A-Za-z0-9,: -]{1,128}$/.test(value) && Number.isFinite(Date.parse(value)); + // Coordinates are rounded to 2 decimals, roughly a kilometre, before use. + const rounded = (value) => Number(value.toFixed(2)); + // The name of a place in the saved copy, such as "manual:59.91,10.75". + const placeKey = (source, latitude, longitude) => + `${source}:${rounded(latitude).toFixed(2)},${rounded(longitude).toFixed(2)}`; + const validHTTPDate = (value) => + typeof value === "string" && + /^[A-Za-z0-9,: -]{1,128}$/.test(value) && + Number.isFinite(Date.parse(value)); + // One forecast point: time (ms), temperature (°C), humidity (%), wind (m/s), symbol code. function validPoint(point) { - return keys(point) === "humidity,symbol,temperature,time,wind" && Number.isSafeInteger(point.time) && point.time > 0 && - numeric(point.temperature,-100,70) && (point.humidity === null || numeric(point.humidity,0,100)) && - (point.wind === null || numeric(point.wind,0,160)) && typeof point.symbol === "string" && /^[a-z_]{1,64}$/.test(point.symbol); + return ( + keys(point) === "humidity,symbol,temperature,time,wind" && + Number.isSafeInteger(point.time) && + point.time > 0 && + numeric(point.temperature, -100, 70) && + (point.humidity === null || numeric(point.humidity, 0, 100)) && + (point.wind === null || numeric(point.wind, 0, 160)) && + typeof point.symbol === "string" && + /^[a-z_]{1,64}$/.test(point.symbol) + ); } - function validPlaceKey(key,source) { + function validPlaceKey(key, source) { if (typeof key !== "string") return false; const match = /^(manual|location):(-?\d{1,3}\.\d{2}),(-?\d{1,3}\.\d{2})$/.exec(key); - return !!match && match[1] === source && numeric(Number(match[2]),-90,90) && numeric(Number(match[3]),-180,180); + return ( + !!match && + match[1] === source && + numeric(Number(match[2]), -90, 90) && + numeric(Number(match[3]), -180, 180) + ); } - function packets(raw,now) { + // Read the saved copy: up to 4 places with up to 24 forecast points each. + // Anything unexpected gives an empty list, so a damaged copy is simply loaded again. + function packets(raw, now) { try { if (typeof raw !== "string" || unescape(encodeURIComponent(raw)).length > 64000) return []; const state = JSON.parse(raw); - if (keys(state) !== "entries,version" || state.version !== 1 || !Array.isArray(state.entries) || state.entries.length > 4) return []; + if ( + keys(state) !== "entries,version" || + state.version !== 1 || + !Array.isArray(state.entries) || + state.entries.length > 4 + ) + return []; const names = new Set(); for (const entry of state.entries) { - if (keys(entry) !== "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || - !["manual","location"].includes(entry.source) || !validPlaceKey(entry.key,entry.source) || names.has(entry.key) || - !Number.isSafeInteger(entry.checkedAt) || entry.checkedAt < 0 || entry.checkedAt > now+300000 || - !Number.isSafeInteger(entry.nextRequestAt) || entry.nextRequestAt < entry.checkedAt || entry.nextRequestAt > entry.checkedAt+7*24*hour || - !Number.isSafeInteger(entry.updatedAt) || entry.updatedAt < 0 || entry.updatedAt > now+300000 || - typeof entry.failed !== "boolean" || typeof entry.deprecated !== "boolean" || - (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || !Array.isArray(entry.points) || entry.points.length > 24 || - !entry.points.every(validPoint) || entry.points.some((point,index) => index > 0 && point.time <= entry.points[index-1].time) || - (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0)) return []; + if ( + keys(entry) !== + "checkedAt,deprecated,failed,key,lastModified,nextRequestAt,points,source,updatedAt" || + !["manual", "location"].includes(entry.source) || + !validPlaceKey(entry.key, entry.source) || + names.has(entry.key) || + !Number.isSafeInteger(entry.checkedAt) || + entry.checkedAt < 0 || + entry.checkedAt > now + 300000 || + !Number.isSafeInteger(entry.nextRequestAt) || + entry.nextRequestAt < entry.checkedAt || + entry.nextRequestAt > entry.checkedAt + 7 * 24 * hour || + !Number.isSafeInteger(entry.updatedAt) || + entry.updatedAt < 0 || + entry.updatedAt > now + 300000 || + typeof entry.failed !== "boolean" || + typeof entry.deprecated !== "boolean" || + (entry.lastModified !== "" && !validHTTPDate(entry.lastModified)) || + !Array.isArray(entry.points) || + entry.points.length > 24 || + !entry.points.every(validPoint) || + entry.points.some( + (point, index) => index > 0 && point.time <= entry.points[index - 1].time, + ) || + (entry.points.length === 0 ? entry.updatedAt !== 0 : entry.updatedAt === 0) + ) + return []; names.add(entry.key); } return state.entries; - } catch (_) { return []; } + } catch (_) { + return []; + } } - function publish(packet,now,projection) { + // Save the forecast of one place next to the others; only one place found by location + // is kept. compareAndSetString writes only if the stored text is still `raw`; if + // something else saved in between, read again and retry. + function publish(packet, now, projection) { if (projection) return false; - for (let attempt=0;attempt<4;attempt++) { - const raw = $storage.getString(cacheKey), entries = packets(raw,now); - const previous = entries.find(entry => entry.key === packet.key); - if (previous && (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt)) return true; - const next = [packet,...entries.filter(entry => entry.key !== packet.key && (packet.source !== "location" || entry.source !== "location"))].sort((a,b) => b.checkedAt-a.checkedAt).slice(0,4); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:next}))) return true; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + entries = packets(raw, now); + const previous = entries.find((entry) => entry.key === packet.key); + if ( + previous && + (previous.updatedAt > packet.updatedAt || previous.checkedAt > packet.checkedAt) + ) + return true; + const next = [ + packet, + ...entries.filter( + (entry) => + entry.key !== packet.key && + (packet.source !== "location" || entry.source !== "location"), + ), + ] + .sort((a, b) => b.checkedAt - a.checkedAt) + .slice(0, 4); + if ( + $storage.compareAndSetString(cacheKey, raw, JSON.stringify({ version: 1, entries: next })) + ) + return true; } return false; } - function expires(headers,now) { + // When to ask again: when the response expires (Expires, else Cache-Control max-age), + // or in one hour without a usable time. Never sooner than 15 minutes, plus up to 5 + // random minutes. + function expires(headers, now) { let until = Date.parse(headers.expires || ""); const maxAge = /(?:^|,)\s*max-age=(\d+)/i.exec(headers["cache-control"] || ""); - if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]),604800)*1000; - if (!Number.isFinite(until) || until > now+7*24*hour) until = now+hour; - return Math.round(Math.max(now+900000,until)+Math.random()*300000); + if (!Number.isFinite(until) && maxAge) until = now + Math.min(Number(maxAge[1]), 604800) * 1000; + if (!Number.isFinite(until) || until > now + 7 * 24 * hour) until = now + hour; + return Math.round(Math.max(now + 900000, until) + Math.random() * 300000); } - function parseResponse(body,place,now,headers,status) { - if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) throw new Error("Invalid forecast"); - const data = JSON.parse(body), meta = data?.properties?.meta, times = data?.properties?.timeseries; + // Check the answer of MET Norway and keep up to 24 points, starting 2 hours ago. + function parseResponse(body, place, now, headers, status) { + if (typeof body !== "string" || unescape(encodeURIComponent(body)).length > 2097152) + throw new Error("Invalid forecast"); + const data = JSON.parse(body), + meta = data?.properties?.meta, + times = data?.properties?.timeseries; const updatedAt = Date.parse(meta?.updated_at || ""); - if (!Number.isFinite(updatedAt) || updatedAt > now+300000 || now-updatedAt > 24*hour || meta?.units?.air_temperature !== "celsius" || meta?.units?.wind_speed !== "m/s" || !Array.isArray(times) || times.length < 1 || times.length > 250) throw new Error("Invalid forecast"); + if ( + !Number.isFinite(updatedAt) || + updatedAt > now + 300000 || + now - updatedAt > 24 * hour || + meta?.units?.air_temperature !== "celsius" || + meta?.units?.wind_speed !== "m/s" || + !Array.isArray(times) || + times.length < 1 || + times.length > 250 + ) + throw new Error("Invalid forecast"); const points = []; for (const item of times) { const time = Date.parse(item?.time || ""); if (!Number.isFinite(time)) throw new Error("Invalid forecast time"); - if (time < now-2*hour || points.length >= 24) continue; - const details = item?.data?.instant?.details, summary = item?.data?.next_1_hours?.summary || item?.data?.next_6_hours?.summary || item?.data?.next_12_hours?.summary; - const point = {time,temperature:details?.air_temperature,humidity:meta.units.relative_humidity === "%" && numeric(details?.relative_humidity,0,100) ? details.relative_humidity : null, - wind:numeric(details?.wind_speed,0,160) ? details.wind_speed : null,symbol:summary?.symbol_code || "unknown"}; - if (!validPoint(point) || (points.length && time <= points[points.length-1].time)) throw new Error("Invalid forecast point"); + if (time < now - 2 * hour || points.length >= 24) continue; + const details = item?.data?.instant?.details, + summary = + item?.data?.next_1_hours?.summary || + item?.data?.next_6_hours?.summary || + item?.data?.next_12_hours?.summary; + const point = { + time, + temperature: details?.air_temperature, + humidity: + meta.units.relative_humidity === "%" && numeric(details?.relative_humidity, 0, 100) + ? details.relative_humidity + : null, + wind: numeric(details?.wind_speed, 0, 160) ? details.wind_speed : null, + symbol: summary?.symbol_code || "unknown", + }; + if (!validPoint(point) || (points.length && time <= points[points.length - 1].time)) + throw new Error("Invalid forecast point"); points.push(point); } - if (!points.some(point=>Math.abs(point.time-now)<=90*60000)) throw new Error("Forecast is unavailable"); - return {key:place.key,source:place.source,updatedAt,checkedAt:now,nextRequestAt:expires(headers,now), - lastModified:validHTTPDate(headers["last-modified"]) && Date.parse(headers["last-modified"]) <= now+300000 ? headers["last-modified"] : "",points,failed:false,deprecated:status===203}; + // One of the points must lie within 90 minutes of now. + if (!points.some((point) => Math.abs(point.time - now) <= 90 * 60000)) + throw new Error("Forecast is unavailable"); + // Status 203 is how MET Norway announces that this version of the service will end. + return { + key: place.key, + source: place.source, + updatedAt, + checkedAt: now, + nextRequestAt: expires(headers, now), + lastModified: + validHTTPDate(headers["last-modified"]) && + Date.parse(headers["last-modified"]) <= now + 300000 + ? headers["last-modified"] + : "", + points, + failed: false, + deprecated: status === 203, + }; } - function pointAt(packet,now) { - if (!packet || !packet.points.length || now-packet.updatedAt > 24*hour || packet.updatedAt > now+300000) return null; - const earlier = packet.points.filter(point => point.time <= now); - const point = earlier[earlier.length-1] || packet.points[0]; - return Math.abs(point.time-now) <= 90*60000 ? point : null; + // The forecast point for now: the latest one that is not in the future, provided it is + // within 90 minutes of now and the forecast is less than a day old. + function pointAt(packet, now) { + if ( + !packet || + !packet.points.length || + now - packet.updatedAt > 24 * hour || + packet.updatedAt > now + 300000 + ) + return null; + const earlier = packet.points.filter((point) => point.time <= now); + const point = earlier[earlier.length - 1] || packet.points[0]; + return Math.abs(point.time - now) <= 90 * 60000 ? point : null; } + // Turn a symbol code such as "partlycloudy_night" into a title and an SF Symbol name. function condition(symbol) { const night = symbol.endsWith("_night"); - if (symbol.includes("thunder")) return {title:"Thunderstorms",icon:"cloud.bolt.rain.fill"}; - if (symbol.includes("snow") || symbol.includes("sleet")) return {title:"Snow or sleet",icon:"cloud.snow.fill"}; - if (symbol.includes("rain")) return {title:"Rain",icon:"cloud.rain.fill"}; - if (symbol.includes("fog")) return {title:"Fog",icon:"cloud.fog.fill"}; - if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) return {title:"Partly cloudy",icon:night ? "cloud.moon.fill" : "cloud.sun.fill"}; - if (symbol.startsWith("clearsky")) return {title:"Clear",icon:night ? "moon.stars.fill" : "sun.max.fill"}; - if (symbol.startsWith("cloudy")) return {title:"Cloudy",icon:"cloud.fill"}; - return {title:"Forecast",icon:"cloud.fill"}; + if (symbol.includes("thunder")) return { title: "Thunderstorms", icon: "cloud.bolt.rain.fill" }; + if (symbol.includes("snow") || symbol.includes("sleet")) + return { title: "Snow or sleet", icon: "cloud.snow.fill" }; + if (symbol.includes("rain")) return { title: "Rain", icon: "cloud.rain.fill" }; + if (symbol.includes("fog")) return { title: "Fog", icon: "cloud.fog.fill" }; + if (symbol.includes("partlycloudy") || symbol.startsWith("fair")) + return { title: "Partly cloudy", icon: night ? "cloud.moon.fill" : "cloud.sun.fill" }; + if (symbol.startsWith("clearsky")) + return { title: "Clear", icon: night ? "moon.stars.fill" : "sun.max.fill" }; + if (symbol.startsWith("cloudy")) return { title: "Cloudy", icon: "cloud.fill" }; + return { title: "Forecast", icon: "cloud.fill" }; } - const locationAllowed = () => $location.isAvailable() && ["authorizedWhenInUse","authorizedAlways"].includes($location.authorizationStatus()) && $location.isAuthorizedForWidgetUpdates(); - function clearLocationCache(now,projection) { + // True when location exists here, the app may use it and widgets may use it too. + const locationAllowed = () => + $location.isAvailable() && + ["authorizedWhenInUse", "authorizedAlways"].includes($location.authorizationStatus()) && + $location.isAuthorizedForWidgetUpdates(); + // Forget the forecast saved for a location once location is no longer allowed. + function clearLocationCache(now, projection) { if (projection) return; - for (let attempt=0;attempt<4;attempt++) { - const raw=$storage.getString(cacheKey), filtered=packets(raw,now).filter(entry=>entry.source!=="location"); - if ($storage.compareAndSetString(cacheKey,raw,JSON.stringify({version:1,entries:filtered}))) return; + for (let attempt = 0; attempt < 4; attempt++) { + const raw = $storage.getString(cacheKey), + filtered = packets(raw, now).filter((entry) => entry.source !== "location"); + if ( + $storage.compareAndSetString( + cacheKey, + raw, + JSON.stringify({ version: 1, entries: filtered }), + ) + ) + return; } } - async function revoked(config,now,projection) { - clearLocationCache(now,projection); - return config.city.trim() ? await load({...config,useLocation:false},now,projection) : {available:false,title:"Location access changed",hint:"Choose a saved city to continue."}; + // Location was allowed and no longer is: use the saved city, if there is one. + async function revoked(config, now, projection) { + clearLocationCache(now, projection); + return config.city.trim() + ? await load({ ...config, useLocation: false }, now, projection) + : { + available: false, + title: "Location access changed", + hint: "Choose a saved city to continue.", + }; } - async function load(config,now,projection) { - let entries = packets($storage.getString(cacheKey),now); + // load(config, now, projection) returns what the widget shows. `now` is in milliseconds. + // `projection` is true for a future timeline entry, which asks neither for the position + // nor for a new forecast. + async function load(config, now, projection) { + let entries = packets($storage.getString(cacheKey), now); const authorized = locationAllowed(); - if (!authorized && entries.some(entry => entry.source === "location")) { - entries = entries.filter(entry => entry.source !== "location"); - clearLocationCache(now,projection); + if (!authorized && entries.some((entry) => entry.source === "location")) { + entries = entries.filter((entry) => entry.source !== "location"); + clearLocationCache(now, projection); } + // Choose the place: the current position, else the last saved one, else the city. let place = null; if (config.useLocation && authorized) { if (!projection) { try { - const location = await $location.current({maxAge:3600}); - const stale = location.isStale === true || (typeof location.age === "number" && location.age > 3600); - if (!stale && numeric(location.latitude,-90,90) && numeric(location.longitude,-180,180)) place = {source:"location",name:location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area",latitude:rounded(location.latitude),longitude:rounded(location.longitude)}; + // maxAge: 3600 accepts a position up to one hour old; `age` is in seconds. + const location = await $location.current({ maxAge: 3600 }); + const stale = + location.isStale === true || (typeof location.age === "number" && location.age > 3600); + if ( + !stale && + numeric(location.latitude, -90, 90) && + numeric(location.longitude, -180, 180) + ) + place = { + source: "location", + name: + location.accuracyAuthorization === "reduced" ? "Approximate area" : "Current area", + latitude: rounded(location.latitude), + longitude: rounded(location.longitude), + }; } catch (_) {} } if (!place && (!config.city.trim() || projection)) { - const saved = entries.find(entry => entry.source === "location" && pointAt(entry,now)); - if (saved) place = {source:"location",name:"Last location",key:saved.key,skipNetwork:true}; + const saved = entries.find((entry) => entry.source === "location" && pointAt(entry, now)); + if (saved) + place = { source: "location", name: "Last location", key: saved.key, skipNetwork: true }; } } - if (!place && config.city.trim()) place = {source:"manual",name:config.city,latitude:rounded(config.latitude),longitude:rounded(config.longitude)}; - if (!place) return {available:false,title:"Choose a saved city",hint:"Open Records & Configuration. Location is optional."}; - place.key ??= placeKey(place.source,place.latitude,place.longitude); + if (!place && config.city.trim()) + place = { + source: "manual", + name: config.city, + latitude: rounded(config.latitude), + longitude: rounded(config.longitude), + }; + if (!place) + return { + available: false, + title: "Choose a saved city", + hint: "Open Records & Configuration. Location is optional.", + }; + place.key ??= placeKey(place.source, place.latitude, place.longitude); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } - let packet = entries.find(entry => entry.key === place.key), saved = true, fromCache = true; + let packet = entries.find((entry) => entry.key === place.key), + saved = true, + fromCache = true; + // Ask MET Norway only when there is no saved forecast for the place or it is due. if (!projection && !place.skipNetwork && (!packet || now >= packet.nextRequestAt)) { try { - const headers = {"User-Agent":"ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)","Accept":"application/json"}; + const headers = { + "User-Agent": "ScriptWidget/1.3 (https://github.com/everettjf/scriptwidget)", + Accept: "application/json", + }; if (packet?.lastModified) headers["If-Modified-Since"] = packet.lastModified; - const response = await $http.getResponse(`https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`,{headers,timeoutInterval:4}); + // The call resolves to { status, body, headers }, also for statuses such as 304. + const response = await $http.getResponse( + `https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${place.latitude.toFixed(2)}&lon=${place.longitude.toFixed(2)}`, + { headers, timeoutInterval: 4 }, + ); if (place.source === "location" && !locationAllowed()) { - return await revoked(config,now,projection); + return await revoked(config, now, projection); } const responseHeaders = response.headers || {}; - if (response.status === 304 && pointAt(packet,now)) packet = {...packet,checkedAt:now,nextRequestAt:expires(responseHeaders,now),failed:false}; - else if (response.status === 200 || response.status === 203) { packet = parseResponse(response.body,place,now,responseHeaders,response.status);fromCache=false; } - else { + // 304: not changed since the last request, so the saved points stay. + if (response.status === 304 && pointAt(packet, now)) + packet = { + ...packet, + checkedAt: now, + nextRequestAt: expires(responseHeaders, now), + failed: false, + }; + else if (response.status === 200 || response.status === 203) { + packet = parseResponse(response.body, place, now, responseHeaders, response.status); + fromCache = false; + } else { + // Another status: retry at the Retry-After time, 15 minutes to 24 hours from now. const retry = responseHeaders["retry-after"] || ""; - let until = /^\d+$/.test(retry) ? now+Number(retry)*1000 : Date.parse(retry); - if (!Number.isFinite(until)) until = now+900000; - const error = new Error("Refresh unavailable");error.retryAt=Math.min(now+24*hour,Math.max(now+900000,until));throw error; + let until = /^\d+$/.test(retry) ? now + Number(retry) * 1000 : Date.parse(retry); + if (!Number.isFinite(until)) until = now + 900000; + const error = new Error("Refresh unavailable"); + error.retryAt = Math.min(now + 24 * hour, Math.max(now + 900000, until)); + throw error; } - saved = publish(packet,now,projection); + saved = publish(packet, now, projection); } catch (error) { - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const retryAt = numeric(error?.retryAt,now,now+24*hour) ? error.retryAt : now+900000; - packet = packet || {key:place.key,source:place.source,updatedAt:0,lastModified:"",points:[],deprecated:false}; - packet = {...packet,checkedAt:now,nextRequestAt:Math.round(retryAt),failed:true}; - saved = publish(packet,now,projection); + // No usable answer: keep the saved points and note the failure. + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const retryAt = numeric(error?.retryAt, now, now + 24 * hour) + ? error.retryAt + : now + 900000; + packet = packet || { + key: place.key, + source: place.source, + updatedAt: 0, + lastModified: "", + points: [], + deprecated: false, + }; + packet = { ...packet, checkedAt: now, nextRequestAt: Math.round(retryAt), failed: true }; + saved = publish(packet, now, projection); } } - if (place.source === "location" && !locationAllowed()) return await revoked(config,now,projection); - const point = pointAt(packet,now); - if (!point) return {available:false,title:"Forecast unavailable",hint:"Check your connection or saved city, then refresh."}; - const celsius = config.unit === "c", temperature = value => Math.round(celsius ? value : value*9/5+32) + (celsius ? "°C" : "°F"); - const age = Math.max(0,Math.floor((now-packet.updatedAt)/60000)); - const statusText = packet.deprecated ? "Service update needed" : !saved ? "Cache unavailable" : packet.failed ? "Saved forecast · refresh unavailable" : place.skipNetwork ? "Saved forecast · last location" : fromCache ? "Saved forecast" : "Forecast"; - const statusShort = packet.deprecated ? "Service update" : !saved ? "No cache" : packet.failed ? "Saved · refresh failed" : place.skipNetwork ? "Last location" : fromCache ? "Saved forecast" : "Forecast"; - return {available:true,statusShort,name:place.name,source:place.source,condition:condition(point.symbol),temperature:temperature(point.temperature), - humidity:point.humidity === null ? "—" : Math.round(point.humidity)+"%",wind:point.wind === null ? "—" : (point.wind*3.6).toFixed(1)+" km/h", - updated:age < 1 ? "Updated just now" : age < 60 ? `Updated ${age}m ago` : `Updated ${Math.floor(age/60)}h ago`,status:statusText, - upcoming:packet.points.filter(value => value.time > point.time).slice(0,4).map(value => ({label:"+"+Math.max(1,Math.round((value.time-now)/hour))+"h",temperature:temperature(value.temperature),condition:condition(value.symbol)}))}; + if (place.source === "location" && !locationAllowed()) + return await revoked(config, now, projection); + const point = pointAt(packet, now); + if (!point) + return { + available: false, + title: "Forecast unavailable", + hint: "Check your connection or saved city, then refresh.", + }; + // Temperatures are saved in °C and converted for display. + const celsius = config.unit === "c", + temperature = (value) => + Math.round(celsius ? value : (value * 9) / 5 + 32) + (celsius ? "°C" : "°F"); + // Minutes since MET Norway updated the forecast. + const age = Math.max(0, Math.floor((now - packet.updatedAt) / 60000)); + const statusText = packet.deprecated + ? "Service update needed" + : !saved + ? "Cache unavailable" + : packet.failed + ? "Saved forecast · refresh unavailable" + : place.skipNetwork + ? "Saved forecast · last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + const statusShort = packet.deprecated + ? "Service update" + : !saved + ? "No cache" + : packet.failed + ? "Saved · refresh failed" + : place.skipNetwork + ? "Last location" + : fromCache + ? "Saved forecast" + : "Forecast"; + // The result for main.jsx. Wind is converted from m/s to km/h (× 3.6). + // `upcoming` holds the next 4 points, with labels such as "+3h". + return { + available: true, + statusShort, + name: place.name, + source: place.source, + condition: condition(point.symbol), + temperature: temperature(point.temperature), + humidity: point.humidity === null ? "—" : Math.round(point.humidity) + "%", + wind: point.wind === null ? "—" : (point.wind * 3.6).toFixed(1) + " km/h", + updated: + age < 1 + ? "Updated just now" + : age < 60 + ? `Updated ${age}m ago` + : `Updated ${Math.floor(age / 60)}h ago`, + status: statusText, + upcoming: packet.points + .filter((value) => value.time > point.time) + .slice(0, 4) + .map((value) => ({ + label: "+" + Math.max(1, Math.round((value.time - now) / hour)) + "h", + temperature: temperature(value.temperature), + condition: condition(value.symbol), + })), + }; } - return {options,load}; + return { options, load }; })(); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/main.jsx index eefd33f5..883547ca 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather Now (MET Norway)/main.jsx @@ -2,25 +2,189 @@ // Optional instance parameter: latitude,longitude,City or JSON weather settings. // Forecast data: MET Norway (CC BY 4.0). No API key; Expires/conditional requests // and a bounded four-place cache reduce traffic. No exact refresh guarantee. -if (!$import("lib/weather.js")) throw new Error("Install the complete weather template, including lib/weather.js."); -const config = localWeather.options($storage.getString("recordTemplate.config.v1"), $getenv("widget-param")); -const weather = await localWeather.load(config,Date.now(),$getenv("timeline-is-projection") === "true"); -const size = $getenv("widget-size"), compact = size === "small"; +// +// The location API runs on iPhone and iPad, and on Android, where widgets see the position +// saved while the app was open. It does not run on Mac, Windows or Linux; there the saved +// city is used. +// This template shows a widget that downloads data, keeps a cache and explains every +// failure. That work is in lib/weather.js; try changing the layouts and colors here. +// widget.json declares the "location", "network" and "storage" permissions, and the host +// api.met.no in networkDomains. + +// $import runs lib/weather.js from this package and returns false when that fails. +// The file defines localWeather. +if (!$import("lib/weather.js")) + throw new Error("Install the complete weather template, including lib/weather.js."); +// The settings: those saved in $storage, changed by the widget parameter (the parameter +// text set for this widget) when there is one. +const config = localWeather.options( + $storage.getString("recordTemplate.config.v1"), + $getenv("widget-param"), +); +// Load the forecast. The third argument is true when the system draws a future timeline +// entry in advance; such an entry only reads the cache. +const weather = await localWeather.load( + config, + Date.now(), + $getenv("timeline-is-projection") === "true", +); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … +const size = $getenv("widget-size"), + compact = size === "small"; +// No forecast to show: a title and a hint, in a form that fits each size. if (!weather.available) { if (size === "accessoryInline") $render({weather.title}); - else if (size === "accessoryCircular") $render(); - else if (size === "accessoryRectangular") $render({weather.title}Open ScriptWidget to configure weather.); - else $render({weather.title}{weather.hint}); + else if (size === "accessoryCircular") $render(); + else if (size === "accessoryRectangular") + $render( + + {weather.title} + Open ScriptWidget to configure weather. + , + ); + else + $render( + + + + {weather.title} + + + {weather.hint} + + , + ); } else if (size === "accessoryInline") { + // Lock Screen sizes (iPhone and iPad only). $render({weather.temperature + " · " + weather.condition.title}); } else if (size === "accessoryCircular") { - $render({weather.temperature}); + $render( + + + + {weather.temperature} + + , + ); } else if (size === "accessoryRectangular") { - $render({weather.name + " · " + weather.temperature}{weather.condition.title}); + $render( + + + + {weather.name + " · " + weather.temperature} + {weather.condition.title} + + , + ); } else if (compact) { - $render({Array.from(weather.name).slice(0,12).join("")}{weather.temperature}{weather.condition.title}{weather.statusShort}{weather.updated}MET Norway); + // Small: place, temperature, condition and how fresh the data is. The forecast is + // licensed CC BY 4.0, so the Home Screen layouts name the source. + $render( + + + {Array.from(weather.name).slice(0, 12).join("")} + + + + {weather.temperature} + + + + + + {weather.condition.title} + + + {weather.statusShort} + + + {weather.updated} + + + MET Norway + + , + ); } else if (size === "medium") { - $render({weather.name}{weather.condition.title}{weather.temperature}{weather.updated}MET Norway{weather.status}); + // Medium: icon, place and temperature in one row. + $render( + + + + + + {weather.name} + + + {weather.condition.title} + + + + + {weather.temperature} + + + + + {weather.updated} + + + + MET Norway + + + + {weather.status} + + , + ); } else { - $render({weather.name}{weather.condition.title}{weather.temperature}{"Wind " + weather.wind}{"Humidity " + weather.humidity}{weather.upcoming.map(point => {point.label}{point.temperature})}{weather.status + " · " + weather.updated}MET Norway · CC BY 4.0); + // Large and extra large add wind, humidity and the next forecast points. + $render( + + + + + {weather.name} + + + {weather.condition.title} + + + + + + + {weather.temperature} + + + + {"Wind " + weather.wind} + + + + {"Humidity " + weather.humidity} + + + + {weather.upcoming.map((point) => ( + + + {point.label} + + + + {point.temperature} + + + ))} + + + {weather.status + " · " + weather.updated} + + + MET Norway · CC BY 4.0 + + , + ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather/main.jsx index 32c77856..314fc331 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weather/main.jsx @@ -1,19 +1,53 @@ -// -// ScriptWidget +// +// ScriptWidget // https://atomsprout.com/scriptwidget -// -// +// +// +// Weather: the temperature, sky and wind in Beijing now, from open-meteo.com. +// Shows how to call a web service that answers in JSON. Try other coordinates and +// another title. +// -const result = await fetch("https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074¤t=temperature_2m,wind_speed_10m,weather_code&timezone=auto"); +// fetch returns the response body as a string. A package with a widget.json must declare +// the "network" permission and the host in networkDomains for this call to work. +// latitude and longitude choose the place; current= lists the values wanted. +const result = await fetch( + "https://api.open-meteo.com/v1/forecast?latitude=39.9042&longitude=116.4074¤t=temperature_2m,wind_speed_10m,weather_code&timezone=auto", +); +// "|| {}" keeps the lines below from failing when the answer has no `current` part. const data = JSON.parse(result).current || {}; -const conditions = {0:"Clear",1:"Mostly clear",2:"Partly cloudy",3:"Overcast",45:"Fog",61:"Rain",71:"Snow",95:"Thunderstorm"}; +// The service describes the sky with a number (a WMO weather code). Only a few are +// named here; any other code is shown as "Mixed skies". +const conditions = { + 0: "Clear", + 1: "Mostly clear", + 2: "Partly cloudy", + 3: "Overcast", + 45: "Fog", + 61: "Rain", + 71: "Snow", + 95: "Thunderstorm", +}; +// frame="max" fills the widget; padding is the space around the content, in points. $render( - BEIJING NOW - - {Math.round(data.temperature_2m)}° - {conditions[data.weather_code] || "Mixed skies"} - Wind {Math.round(data.wind_speed_10m)} km/h - + + + BEIJING NOW + + + + + + + {Math.round(data.temperature_2m)}° + + + {conditions[data.weather_code] || "Mixed skies"} + + + Wind {Math.round(data.wind_speed_10m)} km/h + + , ); diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weekly Planner/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weekly Planner/main.jsx index b6023d2b..eeb23aee 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weekly Planner/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Weekly Planner/main.jsx @@ -1,51 +1,80 @@ // Weekly Planner — highlights today without network access. +// Shows how to repeat a small component, with a shorter layout for the small widget. +// Try changing `names` to your language. +// getDay() gives 0 for Sunday up to 6 for Saturday: today's position in `names`. const now = new Date(); const day = now.getDay(); const names = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"]; +// One day: its name above a dot. Today is drawn brighter. const Day = ({ index }) => ( - {names[index]} + + {names[index]} + ); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … if ($getenv("widget-size") === "small") { // Small: one letter for each day, so that the seven fit. const Letter = ({ index }) => ( - {names[index][0]} + + {names[index][0]} + ); + // frame="max" fills the widget; padding is the space around the content, in points. $render( - This Week - {now.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} + + This Week + + + {now.toLocaleDateString("en-US", { weekday: "short", month: "short", day: "numeric" })} + - - + + + + + + + - + , ); } else { + // Medium and larger: the three-letter names, and today's date from the element. $render( - This Week - Make today count + + This Week + + + Make today count + - - + + + + + + + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wellness Dashboard/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wellness Dashboard/main.jsx index c6a2b7e3..cea5cf7d 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wellness Dashboard/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Wellness Dashboard/main.jsx @@ -1,65 +1,206 @@ // Designed for the large widget; the small and medium sizes show the essentials. widget-param: sleepHours,waterGlasses,steps,mood +// +// This template shows a score computed from the widget parameter, with a ring, progress +// bars and cards. Try changing the sample numbers or the weights of the score. + +// $getenv("widget-param") is the parameter text set for this widget, split at the commas. const values = ($getenv("widget-param") || "7.5,6,6840,Calm").split(","); +// A missing or non-numeric number counts as 0; the mood falls back to "Steady". const sleep = Number(values[0]) || 0; const water = Number(values[1]) || 0; const steps = Number(values[2]) || 0; const mood = (values[3] || "Steady").trim(); -const score = Math.round(Math.min(100, sleep / 8 * 35 + water / 8 * 25 + steps / 10000 * 40)); +// A score of at most 100: sleep gives 35 points at 8 hours, water 25 at 8 glasses and +// steps 40 at 10,000 steps. +const score = Math.round(Math.min(100, (sleep / 8) * 35 + (water / 8) * 25 + (steps / 10000) * 40)); +// A card with an icon, a title, a value and a progress bar, used in the large layout. const Metric = ({ icon, title, value, detail, color, progress, total }) => ( - - {title} - {value}{detail} - + + + + + + {title} + + + + + {value} + + + + {detail} + + + ); +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); if (size === "small") { // Small: the balance score. + // frame="max" fills the widget; padding is the space around the content, in points. $render( - DAILY BALANCE - {score} - - + + DAILY BALANCE + + {/* A puts the number on top of the ring. takes a value from 0 to 1. */} + + + + {score} + + + + , ); } else if (size === "medium") { // Medium: the balance score above the three numbers. + // A smaller card without a bar, defined here because only this layout uses it. const Figure = ({ icon, title, value, color }) => ( - - {title} - {value} + + + + + {title} + + + + + {value} + ); $render( - {score} - DAILY BALANCE· {mood}Good momentum - + + + + {score} + + + + + + DAILY BALANCE + + + · {mood} + + + + Good momentum + + + -
-
-
+
+
+
- + , ); } else { + // Large and extra large: a title, the score, and the three cards with their bars. $render( - Wellness TodaySmall choices, steady energy + + + + Wellness Today + + + Small choices, steady energy + + + + + - - DAILY BALANCEGood momentumAdd one glass and a short walk. - + {/* is a ring with a label; value is out of total. */} + + + + DAILY BALANCE + + + Good momentum + + + Add one glass and a short walk. + + + - - + + - - + + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/World Clock Faces/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/World Clock Faces/main.jsx index ed3d9185..3cb2e211 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/World Clock Faces/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/World Clock Faces/main.jsx @@ -6,23 +6,60 @@ // with IANA time zone names. // +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); +// Each city: [the name to show, its IANA time zone]. const cities = [ - ["Cupertino", "America/Los_Angeles"], ["New York", "America/New_York"], ["London", "Europe/London"], - ["Beijing", "Asia/Shanghai"], ["Tokyo", "Asia/Tokyo"], ["Sydney", "Australia/Sydney"], + ["Cupertino", "America/Los_Angeles"], + ["New York", "America/New_York"], + ["London", "Europe/London"], + ["Beijing", "Asia/Shanghai"], + ["Tokyo", "Asia/Tokyo"], + ["Sydney", "Australia/Sydney"], ]; const now = new Date(); // Wall-clock time in a zone, and its offset from here in hours. const timeIn = (zone) => { - const parts = new Intl.DateTimeFormat("en-US", { timeZone: zone, year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit", hourCycle: "h23" }).formatToParts(now); + // Intl.DateTimeFormat gives the date and time as a clock in that zone shows them. + const parts = new Intl.DateTimeFormat("en-US", { + timeZone: zone, + year: "numeric", + month: "numeric", + day: "numeric", + hour: "numeric", + minute: "2-digit", + hourCycle: "h23", + }).formatToParts(now); const value = (type) => Number(parts.find((part) => part.type === type)?.value ?? 0); - const wall = Date.UTC(value("year"), value("month") - 1, value("day"), value("hour"), value("minute")); - const here = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes()); - return { hour: value("hour"), minute: value("minute"), hours: Math.round((wall - here) / 360000) / 10 }; + // Put both clock readings on the same scale; their difference is the offset. + const wall = Date.UTC( + value("year"), + value("month") - 1, + value("day"), + value("hour"), + value("minute"), + ); + const here = Date.UTC( + now.getFullYear(), + now.getMonth(), + now.getDate(), + now.getHours(), + now.getMinutes(), + ); + return { + hour: value("hour"), + minute: value("minute"), + // 360000 ms is a tenth of an hour, so this is the offset in hours with one decimal. + hours: Math.round((wall - here) / 360000) / 10, + }; }; +// The time here, for the Lock Screen face. const local = timeIn(Intl.DateTimeFormat().resolvedOptions().timeZone); -const offset = (time) => (time.hours === 0 ? "Local" : `${time.hours > 0 ? "+" : ""}${time.hours}H`); -const label = (time) => `${((time.hour + 11) % 12) + 1}:${String(time.minute).padStart(2, "0")} ${time.hour < 12 ? "AM" : "PM"}`; +// offset: "Local", "+8H" or "-3H". label: a 12-hour time such as "9:05 PM". +const offset = (time) => + time.hours === 0 ? "Local" : `${time.hours > 0 ? "+" : ""}${time.hours}H`; +const label = (time) => + `${((time.hour + 11) % 12) + 1}:${String(time.minute).padStart(2, "0")} ${time.hour < 12 ? "AM" : "PM"}`; // A hand is a capsule in the top half of a square that rotates about its center. const Hand = ({ side, length, width, angle, color }) => ( @@ -32,6 +69,8 @@ const Hand = ({ side, length, width, angle, color }) => ( ); +// A clock face: a disc, twelve tick marks and two hands. It is light from 6:00 to 18:00 +// in that city and dark at night. `side` is its width and height in points. const Face = ({ time, side }) => { const day = time.hour >= 6 && time.hour < 18; const face = day ? "#F2F2F7" : "#1C1C1E"; @@ -39,58 +78,124 @@ const Face = ({ time, side }) => { return ( + {/* Twelve ticks, 30 degrees apart; every third one is longer and darker. */} {Array.from({ length: 12 }, (_, index) => ( - + ))} - - + {/* Hour hand: 30 degrees for each hour and half a degree for each minute. */} + + {/* Minute hand: 6 degrees for each minute. */} + ); }; +// A face with the city's name, the digital time if wanted, and the offset. const City = ({ city, side, digital }) => { const time = timeIn(city[1]); return ( - {city[0]} - {digital ? {label(time)} : null} - {offset(time)} + + {city[0]} + + {digital ? ( + + {label(time)} + + ) : null} + + {offset(time)} + ); }; +// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets +// (iPhone and iPad only). if (size === "accessoryCircular") { $render(); } else if (size === "accessoryRectangular") { $render( - {cities.slice(1, 4).map((city) => {city[0]}{label(timeIn(city[1]))})} - + {cities.slice(1, 4).map((city) => ( + + + {city[0]} + + + {label(timeIn(city[1]))} + + ))} + , ); } else if (size === "accessoryInline") { - $render({cities[4][0]} {label(timeIn(cities[4][1]))}); + $render( + + {cities[4][0]} {label(timeIn(cities[4][1]))} + , + ); } else if (size === "small") { + // Small: the first city. padding is the space around the content, in points. const time = timeIn(cities[0][1]); $render( - {cities[0][0]}{label(time)} - + + + {cities[0][0]} + + + + {label(time)} + + + , ); } else if (size === "medium") { - $render({cities.slice(0, 4).map((city) => )}); + // Medium: the first four cities in a row. + $render( + + {cities.slice(0, 4).map((city) => ( + + ))} + , + ); } else { + // Large and extra large: all six cities in a grid of three columns. takes its + // columns as a JSON string. const wide = size === "extraLarge"; const grid = JSON.stringify(Array.from({ length: 3 }, () => ({ type: "flexible" }))); $render( - World Clock - {cities.map((city) => )} + + World Clock + + + {cities.map((city) => ( + + ))} + - + , ); } diff --git a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Year in Dots/main.jsx b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Year in Dots/main.jsx index 72f6a602..cf99df66 100644 --- a/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Year in Dots/main.jsx +++ b/Shared/ScriptWidgetRuntime/Resource/Script.bundle/template/Year in Dots/main.jsx @@ -4,12 +4,18 @@ // // Year in Dots: one dot per day of the year. // +// Shows how to build a grid from rows of shapes. Try changing the three colors below. +// +// $getenv("widget-size") is the size being drawn: "small", "medium", "large", … const size = $getenv("widget-size"); const now = new Date(); +// 86400000 is the number of milliseconds in a day. +// total: the days in this year, 365 or 366. today: the day of the year, starting at 1. const start = new Date(now.getFullYear(), 0, 1); const total = (new Date(now.getFullYear() + 1, 0, 1) - start) / 86400000; const today = Math.floor((now - start) / 86400000) + 1; +// How much of the year has passed, in percent. const percent = Math.round((100 * today) / total); const paper = "#F5F1E8"; const ink = "#2B2A28"; @@ -17,53 +23,89 @@ const accent = "#E4572E"; // Rows of stacks rather than a grid, so spacing is the same in both // directions. A plain function: component props cannot carry functions. +// cell(index) returns the element for one position, counted from 0. const field = (count, columns, spacing, cell) => ( {Array.from({ length: Math.ceil(count / columns) }, (_, row) => ( - {Array.from({ length: Math.min(columns, count - row * columns) }, (_, column) => cell(row * columns + column))} + {Array.from({ length: Math.min(columns, count - row * columns) }, (_, column) => + cell(row * columns + column), + )} ))} ); +// Today in the accent color, past days dark, days to come pale. const dotColor = (day) => (day === today ? accent : day < today ? ink : "#D9D2C3"); -const Dots = ({ count, first, columns, dot, spacing }) => field(count, columns, spacing, (index) => ); +// Dots for `count` days; `first` is the day of the year of the first dot. +const Dots = ({ count, first, columns, dot, spacing }) => + field(count, columns, spacing, (index) => ( + + )); +// The year on the left and the percentage on the right. const Title = ({ font }) => ( - {now.getFullYear()} + + {now.getFullYear()} + - {percent}% + + {percent}% + ); +// Choose a layout for the widget size. The "accessory" sizes are Lock Screen widgets +// (iPhone and iPad only). if (size === "accessoryCircular") { - $render({percent}%); + $render( + + + + {percent}% + + , + ); } else if (size === "accessoryRectangular") { $render( - Day {today} of {total} + + Day {today} of {total} + {total - today} days left - + , ); } else if (size === "accessoryInline") { - $render({now.getFullYear()} · {percent}% · {total - today} days left); + $render( + + {now.getFullYear()} · {percent}% · {total - today} days left + , + ); } else if (size === "small") { // This month, one dot per day. + // first: the day of the year of the 1st of this month. days: the length of this month. const first = today - now.getDate() + 1; const days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate(); const monthName = now.toLocaleString("en-US", { month: "long" }); $render( + // padding is the space around the content, in points. - {monthName} + + {monthName} + - {percent}% + + {percent}% + - {total - today} days left in {now.getFullYear()} - + + {total - today} days left in {now.getFullYear()} + + , ); } else if (size === "medium") { // The year as weeks. @@ -72,20 +114,37 @@ if (size === "accessoryCircular") { $render( - {field(weeks, 18, 5, (index) => <rect frame="11,11" corner="3" color={index + 1 === week ? accent : index + 1 < week ? ink : "#D9D2C3"} />)} + {field(weeks, 18, 5, (index) => ( + <rect + frame="11,11" + corner="3" + color={index + 1 === week ? accent : index + 1 < week ? ink : "#D9D2C3"} + /> + ))} <spacer /> - <text font="caption2" color="#8A8273">Week {week} of {weeks} · {total - today} days left</text> - </vstack> + <text font="caption2" color="#8A8273"> + Week {week} of {weeks} · {total - today} days left + </text> + </vstack>, ); } else { + // Large and extra large: the whole year, one dot per day. const wide = size === "extraLarge"; $render( <vstack alignment="leading" spacing="12" padding={wide ? "24" : "16"} background={paper}> <Title font={wide ? "largeTitle" : "title"} /> <spacer /> - <Dots count={total} first={1} columns={wide ? 31 : 21} dot={wide ? 12 : 6} spacing={wide ? 6 : 5} /> + <Dots + count={total} + first={1} + columns={wide ? 31 : 21} + dot={wide ? 12 : 6} + spacing={wide ? 6 : 5} + /> <spacer /> - <text font="caption" color="#8A8273">Day {today} · {total - today} days left</text> - </vstack> + <text font="caption" color="#8A8273"> + Day {today} · {total - today} days left + </text> + </vstack>, ); } diff --git a/Skills/scriptwidget-creator/references/platform-support.md b/Skills/scriptwidget-creator/references/platform-support.md index d28b837e..d0efca4c 100644 --- a/Skills/scriptwidget-creator/references/platform-support.md +++ b/Skills/scriptwidget-creator/references/platform-support.md @@ -29,6 +29,28 @@ The browser preview in [Web Studio](https://github.com/everettjf/scriptwidget/bl | Wallpaper colors (`material.<role>`) | No, the color is ignored | No | Yes | No | No | | Automation entry point for other apps | No | No | Yes | No | No | +## Components + +What a script draws with. Android, Windows and Linux use one shared renderer, so a component is on all three or on none; the rows say what a system draws differently. Each component's properties are in the [runtime API reference](https://github.com/everettjf/scriptwidget/blob/main/docs/scriptwidget-runtime-api.md). + +<!-- components:start --> +| Component | iPhone and iPad | Mac | Android | Windows | Linux | +| --- | --- | --- | --- | --- | --- | +| Layout: `<vstack>`, `<hstack>`, `<zstack>`, `<vgrid>`, `<hgrid>`, `<spacer>`, `<divider>` | Yes | Yes | Yes | Yes | Yes | +| Text: `<text>`, `<label>`, `<badge>`, `<chip>`, `<stat>` | Yes | Yes | Yes, in Inter, which is wider than the Apple system font | Yes, in Inter | Yes, in Inter | +| Shapes: `<rect>`, `<roundedrect>`, `<capsule>`, `<ellipse>`, `<circle>`, `<line>` | Yes | Yes | Yes | Yes | Yes | +| Values: `<gauge>`, `<progress>`, `<ring>`, `<chart>` | Yes | Yes | Yes | Yes | Yes | +| `<image>` | Yes | Yes | Yes | Yes | Yes | +| `<icon>` and `systemName` images | Yes | Yes | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | +| `<date>` | Yes | Yes | `timer` and a `time` of now tick by themselves; `relative`, `offset` and `date` are redrawn at each refresh | A timer is redrawn every second and a clock time every minute | A timer is redrawn every second and a clock time every minute | +| `<gif>` | Animated in the app's preview; in a widget the system decides and may hold one frame | The first frame | Up to 24 sampled frames | The first frame | Animated on the desktop, at most 60 frames | +| The `animation` property (clock hands, swing) | Moves in the app's preview; in a widget the system schedules it and may hold one frame | Standard clock hands show the time without moving; the others stay at rest | Standard clock hands are a system clock; swing and custom intervals play as frames | The first frame | The first frame | +| `<button>`, `<toggle>` | Yes, from iOS 17 | Yes, from macOS 14 | Yes | Yes | Yes | +| `<link>` | Yes | Yes | Yes | `http`, `https` and `mailto` only | `http`, `https` and `mailto` only | +| The `backgroundMaterial` property | Yes | Yes | The opaque `background` fallback | The opaque `background` fallback | The opaque `background` fallback | +| Scrolling `<list>` | No | No | Yes | No | No | +<!-- components:end --> + ## Data APIs <!-- platforms:start --> diff --git a/Skills/scriptwidget-creator/references/runtime-api.md b/Skills/scriptwidget-creator/references/runtime-api.md index 8056457e..17b0f1a7 100644 --- a/Skills/scriptwidget-creator/references/runtime-api.md +++ b/Skills/scriptwidget-creator/references/runtime-api.md @@ -2,6 +2,26 @@ > Generated from Studio's static API metadata (schema v1, runtime 1.6). The native runtime switch is authoritative. Do not edit by hand. +## Which systems each component runs on + +Every component below exists on iPhone, iPad, Mac, Android, Windows and Linux, except the scrolling `<list>`, which only Android has and which is not in this reference (see [ScriptWidget for Android](https://github.com/everettjf/scriptwidget/blob/main/docs/android/README.md)). What a system draws differently is in this table; [Platform support](https://github.com/everettjf/scriptwidget/blob/main/docs/platform-support.md) has the same table beside the APIs and the widget features. + +| Component | iPhone and iPad | Mac | Android | Windows | Linux | +| --- | --- | --- | --- | --- | --- | +| Layout: `<vstack>`, `<hstack>`, `<zstack>`, `<vgrid>`, `<hgrid>`, `<spacer>`, `<divider>` | Yes | Yes | Yes | Yes | Yes | +| Text: `<text>`, `<label>`, `<badge>`, `<chip>`, `<stat>` | Yes | Yes | Yes, in Inter, which is wider than the Apple system font | Yes, in Inter | Yes, in Inter | +| Shapes: `<rect>`, `<roundedrect>`, `<capsule>`, `<ellipse>`, `<circle>`, `<line>` | Yes | Yes | Yes | Yes | Yes | +| Values: `<gauge>`, `<progress>`, `<ring>`, `<chart>` | Yes | Yes | Yes | Yes | Yes | +| `<image>` | Yes | Yes | Yes | Yes | Yes | +| `<icon>` and `systemName` images | Yes | Yes | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | +| `<date>` | Yes | Yes | `timer` and a `time` of now tick by themselves; `relative`, `offset` and `date` are redrawn at each refresh | A timer is redrawn every second and a clock time every minute | A timer is redrawn every second and a clock time every minute | +| `<gif>` | Animated in the app's preview; in a widget the system decides and may hold one frame | The first frame | Up to 24 sampled frames | The first frame | Animated on the desktop, at most 60 frames | +| The `animation` property (clock hands, swing) | Moves in the app's preview; in a widget the system schedules it and may hold one frame | Standard clock hands show the time without moving; the others stay at rest | Standard clock hands are a system clock; swing and custom intervals play as frames | The first frame | The first frame | +| `<button>`, `<toggle>` | Yes, from iOS 17 | Yes, from macOS 14 | Yes | Yes | Yes | +| `<link>` | Yes | Yes | Yes | `http`, `https` and `mailto` only | `http`, `https` and `mailto` only | +| The `backgroundMaterial` property | Yes | Yes | The opaque `background` fallback | The opaque `background` fallback | The opaque `background` fallback | +| Scrolling `<list>` | No | No | Yes | No | No | + ## Components ### `<VStack>` diff --git a/Web/preview-engine/test/parity/layout-edit-trees.json b/Web/preview-engine/test/parity/layout-edit-trees.json index 2acae2bc..9bae9b84 100644 --- a/Web/preview-engine/test/parity/layout-edit-trees.json +++ b/Web/preview-engine/test/parity/layout-edit-trees.json @@ -1,11 +1,11 @@ { "examples" : { "after" : { - "source" : "\/\/ Open Layout in the editor to select, edit, add and move these layers.\n\/\/ Code remains the source of truth. This template needs no permissions.\n$render(\n <vstack frame=\"max\" alignment={\"trailing\"} spacing=\"8\" padding=\"16\" background=\"#f1f6fb\">\n <hstack spacing=\"6\">\n <icon systemName=\"sparkles\" size=\"18\" color=\"#526f9e\"\/>\n <text font=\"caption\" color=\"#657b96\">A fresh start<\/text>\n <\/hstack>\n <spacer\/>\n <text font=\"headline\" fontWeight=\"semibold\" color=\"#263e60\">{\"A calmer day\"}<\/text>\n <text font=\"caption\" color=\"#657b96\">A little space for your ideas.<\/text>\n <\/vstack>\n);\n", + "source" : "\/\/ Open Layout in the editor to select, edit, add and move these layers.\n\/\/ Code remains the source of truth. This template needs no permissions.\n\/\/ A plain card: an icon and a short line at the top, two lines of text at the bottom.\n\/\/ Try changing the texts and the colors.\n\n\/\/ $render draws the widget. frame=\"max\" fills the whole widget, alignment=\"leading\"\n\/\/ lines the children up on the left, and padding is the space in points around them.\n$render(\n <vstack frame=\"max\" alignment={\"trailing\"} spacing=\"8\" padding=\"16\" background=\"#f1f6fb\">\n {\/* <hstack> places its children side by side, <vstack> one below the other. *\/}\n <hstack spacing=\"6\">\n <icon systemName=\"sparkles\" size=\"18\" color=\"#526f9e\" \/>\n <text font=\"caption\" color=\"#657b96\">\n A fresh start\n <\/text>\n <\/hstack>\n {\/* <spacer \/> takes all free space, which pushes the two texts to the bottom. *\/}\n <spacer \/>\n <text font=\"headline\" fontWeight=\"semibold\" color=\"#263e60\">{\"A calmer day\"}<\/text>\n <text font=\"caption\" color=\"#657b96\">\n A little space for your ideas.\n <\/text>\n <\/vstack>,\n);\n", "tree" : "{\"$element\":\"vstack\",\"props\":{\"alignment\":\"trailing\",\"background\":\"#f1f6fb\",\"frame\":\"max\",\"padding\":\"16\",\"spacing\":\"8\"},\"children\":[{\"$element\":\"hstack\",\"props\":{\"spacing\":\"6\"},\"children\":[{\"$element\":\"icon\",\"props\":{\"color\":\"#526f9e\",\"size\":\"18\",\"systemName\":\"sparkles\"},\"children\":[]},{\"$element\":\"text\",\"props\":{\"color\":\"#657b96\",\"font\":\"caption\"},\"children\":[\"A fresh start\"]}]},{\"$element\":\"spacer\",\"props\":null,\"children\":[]},{\"$element\":\"text\",\"props\":{\"color\":\"#263e60\",\"font\":\"headline\",\"fontWeight\":\"semibold\"},\"children\":[\"A calmer day\"]},{\"$element\":\"text\",\"props\":{\"color\":\"#657b96\",\"font\":\"caption\"},\"children\":[\"A little space for your ideas.\"]}]}" }, "before" : { - "source" : "\/\/ Open Layout in the editor to select, edit, add and move these layers.\n\/\/ Code remains the source of truth. This template needs no permissions.\n$render(\n <vstack frame=\"max\" alignment=\"leading\" spacing=\"8\" padding=\"16\" background=\"#f1f6fb\">\n <hstack spacing=\"6\">\n <icon systemName=\"sparkles\" size=\"18\" color=\"#526f9e\"\/>\n <text font=\"caption\" color=\"#657b96\">A fresh start<\/text>\n <\/hstack>\n <spacer\/>\n <text font=\"headline\" fontWeight=\"semibold\" color=\"#263e60\">Make today yours<\/text>\n <text font=\"caption\" color=\"#657b96\">A little space for your ideas.<\/text>\n <\/vstack>\n);\n", + "source" : "\/\/ Open Layout in the editor to select, edit, add and move these layers.\n\/\/ Code remains the source of truth. This template needs no permissions.\n\/\/ A plain card: an icon and a short line at the top, two lines of text at the bottom.\n\/\/ Try changing the texts and the colors.\n\n\/\/ $render draws the widget. frame=\"max\" fills the whole widget, alignment=\"leading\"\n\/\/ lines the children up on the left, and padding is the space in points around them.\n$render(\n <vstack frame=\"max\" alignment=\"leading\" spacing=\"8\" padding=\"16\" background=\"#f1f6fb\">\n {\/* <hstack> places its children side by side, <vstack> one below the other. *\/}\n <hstack spacing=\"6\">\n <icon systemName=\"sparkles\" size=\"18\" color=\"#526f9e\" \/>\n <text font=\"caption\" color=\"#657b96\">\n A fresh start\n <\/text>\n <\/hstack>\n {\/* <spacer \/> takes all free space, which pushes the two texts to the bottom. *\/}\n <spacer \/>\n <text font=\"headline\" fontWeight=\"semibold\" color=\"#263e60\">\n Make today yours\n <\/text>\n <text font=\"caption\" color=\"#657b96\">\n A little space for your ideas.\n <\/text>\n <\/vstack>,\n);\n", "tree" : "{\"$element\":\"vstack\",\"props\":{\"alignment\":\"leading\",\"background\":\"#f1f6fb\",\"frame\":\"max\",\"padding\":\"16\",\"spacing\":\"8\"},\"children\":[{\"$element\":\"hstack\",\"props\":{\"spacing\":\"6\"},\"children\":[{\"$element\":\"icon\",\"props\":{\"color\":\"#526f9e\",\"size\":\"18\",\"systemName\":\"sparkles\"},\"children\":[]},{\"$element\":\"text\",\"props\":{\"color\":\"#657b96\",\"font\":\"caption\"},\"children\":[\"A fresh start\"]}]},{\"$element\":\"spacer\",\"props\":null,\"children\":[]},{\"$element\":\"text\",\"props\":{\"color\":\"#263e60\",\"font\":\"headline\",\"fontWeight\":\"semibold\"},\"children\":[\"Make today yours\"]},{\"$element\":\"text\",\"props\":{\"color\":\"#657b96\",\"font\":\"caption\"},\"children\":[\"A little space for your ideas.\"]}]}" } }, diff --git a/Web/preview-engine/test/parity/material-study-trees.json b/Web/preview-engine/test/parity/material-study-trees.json index 927b9e05..97f07c22 100644 --- a/Web/preview-engine/test/parity/material-study-trees.json +++ b/Web/preview-engine/test/parity/material-study-trees.json @@ -146,5 +146,5 @@ } }, "formatVersion" : 1, - "source" : "\/\/ Public SwiftUI material blurs these shapes inside the widget, not the wallpaper.\n\/\/ The system supplies Clear\/Tinted backgrounds. No timer or private animation.\nconst dark = $device.isdarkmode();\nconst family = $getenv(\"widget-size\");\nconst fullColor = ($getenv(\"widget-rendering-mode\") || \"fullColor\") === \"fullColor\";\nconst ink = dark ? \"#EFFAF5\" : \"#1C4C39\";\nconst muted = dark ? \"#C2DCD0\" : \"#4E7764\";\nif (family.startsWith(\"accessory\")) {\n $render(<text font={family === \"accessoryCircular\" ? \"caption\" : \"headline\"}>{family === \"accessoryCircular\" ? \"Calm\" : \"A little calm\"}<\/text>);\n} else {\n $render(\n <zstack frame=\"max\" background={dark ? \"#142C24\" : \"#E7F6EE\"}>\n <hstack spacing=\"4\" opacity={fullColor ? 0.7 : 0} rotation3d=\"12,0,1,0\">\n <circle frame=\"80\" color=\"#41B982\"\/>\n <ellipse frame=\"48,92\" rotation=\"28\" color=\"#F1C486\"\/>\n <\/hstack>\n <vstack spacing=\"7\" padding=\"18\" corner=\"20\"\n backgroundMaterial=\"thin\" background={dark ? \"#203E31\" : \"#FAFFFC\"}>\n <text font=\"headline\" fontDesign=\"rounded\" color={ink}>A little calm<\/text>\n <text font=\"caption\" color={muted}>Your own quiet corner.<\/text>\n <\/vstack>\n <\/zstack>\n );\n}\n" + "source" : "\/\/ Public SwiftUI material blurs these shapes inside the widget, not the wallpaper.\n\/\/ The system supplies Clear\/Tinted backgrounds. No timer or private animation.\n\/\/ Shows a frosted card over two colored shapes. Try another backgroundMaterial:\n\/\/ ultraThin, thin, regular, thick or ultraThick.\n\n\/\/ $device.isdarkmode() is true when the system uses the dark appearance.\nconst dark = $device.isdarkmode();\n\/\/ The size being drawn. The Lock Screen sizes start with \"accessory\".\nconst family = $getenv(\"widget-size\");\n\/\/ \"fullColor\", \"accented\" or \"vibrant\". The colored shapes are hidden unless it is fullColor.\nconst fullColor = ($getenv(\"widget-rendering-mode\") || \"fullColor\") === \"fullColor\";\nconst ink = dark ? \"#EFFAF5\" : \"#1C4C39\";\nconst muted = dark ? \"#C2DCD0\" : \"#4E7764\";\nif (family.startsWith(\"accessory\")) {\n \/\/ Lock Screen: text only.\n $render(\n <text font={family === \"accessoryCircular\" ? \"caption\" : \"headline\"}>\n {family === \"accessoryCircular\" ? \"Calm\" : \"A little calm\"}\n <\/text>,\n );\n} else {\n $render(\n <zstack frame=\"max\" background={dark ? \"#142C24\" : \"#E7F6EE\"}>\n {\/* The shapes behind the card. rotation3d=\"12,0,1,0\" tilts them 12 degrees on the y axis. *\/}\n <hstack spacing=\"4\" opacity={fullColor ? 0.7 : 0} rotation3d=\"12,0,1,0\">\n <circle frame=\"80\" color=\"#41B982\" \/>\n <ellipse frame=\"48,92\" rotation=\"28\" color=\"#F1C486\" \/>\n <\/hstack>\n {\/* The card. `background` is what shows when Reduce Transparency is turned on. *\/}\n <vstack\n spacing=\"7\"\n padding=\"18\"\n corner=\"20\"\n backgroundMaterial=\"thin\"\n background={dark ? \"#203E31\" : \"#FAFFFC\"}\n >\n <text font=\"headline\" fontDesign=\"rounded\" color={ink}>\n A little calm\n <\/text>\n <text font=\"caption\" color={muted}>\n Your own quiet corner.\n <\/text>\n <\/vstack>\n <\/zstack>,\n );\n}\n" } \ No newline at end of file diff --git a/docs/linux/README.md b/docs/linux/README.md index fb20d40d..0d7dc805 100644 --- a/docs/linux/README.md +++ b/docs/linux/README.md @@ -13,7 +13,7 @@ On other desktops the command line and the management window work, but nothing i | Part | What it does | | --- | --- | | `scriptwidget` | The command line, and the background service (`scriptwidget host run`): it runs the scripts on a schedule, draws the pictures and handles clicks. It opens no window | -| `scriptwidget-studio` | The management window: your widgets, the templates, the code editor with a live preview, the settings. Closing it frees its memory; the widgets keep running | +| `scriptwidget-studio` | The management window: your widgets, the templates, the component examples, the API examples, the code editor with a live preview, the settings. Closing it frees its memory; the widgets keep running | | Omarchy plugin `com.atomsprout.scriptwidget` | Shows the pictures on the desktop layer and adds an entry to the bar. It only shows pictures and forwards numbers and coordinates | ## Pictures @@ -23,6 +23,7 @@ The management window on Omarchy 4.5 (screenshots of the real window in the test | | | | --- | --- | | ![My widgets](images/studio-library.png) | ![Templates](images/studio-templates.png) | +| ![Components](images/studio-components.png) | ![APIs](images/studio-apis.png) | | ![A template opened](images/studio-template.png) | ![Editor with live preview](images/studio-editor.png) | | ![Settings](images/studio-settings.png) | ![My widgets in Chinese](images/studio-library-zh.png) | | ![Typing Chinese with pinyin in the editor](images/studio-pinyin.png) | | diff --git a/docs/linux/images/studio-apis.png b/docs/linux/images/studio-apis.png new file mode 100644 index 00000000..cd18c51c Binary files /dev/null and b/docs/linux/images/studio-apis.png differ diff --git a/docs/linux/images/studio-components.png b/docs/linux/images/studio-components.png new file mode 100644 index 00000000..b8b4d55d Binary files /dev/null and b/docs/linux/images/studio-components.png differ diff --git a/docs/linux/images/studio-templates.png b/docs/linux/images/studio-templates.png index 7519b8fe..506ebddc 100644 Binary files a/docs/linux/images/studio-templates.png and b/docs/linux/images/studio-templates.png differ diff --git a/docs/linux/protocol.md b/docs/linux/protocol.md index 811a265e..77884312 100644 --- a/docs/linux/protocol.md +++ b/docs/linux/protocol.md @@ -42,7 +42,7 @@ One JSON object a line, UTF-8, each with a string member `event`. A display igno Examples, exactly as printed: ``` -{"event":"hello","protocol":1,"dark":false,"arrange":false,"peek":false,"service":"0.1.3"} +{"event":"hello","protocol":1,"dark":false,"arrange":false,"peek":false,"service":"0.1.4"} {"event":"widget","id":"5ef2d5c170089ecf","screen":"eDP-1","x":40,"y":40,"width":329,"height":170,"image":"/run/user/1000/scriptwidget/frames/5ef2d5c170089ecf-1d639a55-3.png","version":3,"regions":[{"n":0,"x":16,"y":120,"width":96,"height":34}],"family":"medium","families":["small","medium","large"]} {"event":"widget","id":"c45467fe6c9c2b4a","screen":"","x":68,"y":68,"width":170,"height":170,"image":"/run/user/1000/scriptwidget/frames/c45467fe6c9c2b4a-1d639a55-1-0.png","version":1,"regions":[],"frames":[{"image":"/run/user/1000/scriptwidget/frames/c45467fe6c9c2b4a-1d639a55-1-0.png","ms":200},{"image":"/run/user/1000/scriptwidget/frames/c45467fe6c9c2b4a-1d639a55-1-1.png","ms":300}],"family":"small","families":["small","medium","large","extraLarge"]} {"event":"remove","id":"5ef2d5c170089ecf"} diff --git a/docs/linux/testing.md b/docs/linux/testing.md index c8bc7b09..b45c74ba 100644 --- a/docs/linux/testing.md +++ b/docs/linux/testing.md @@ -546,6 +546,120 @@ swift Tools/ScriptWidgetPreview/Scripts/contact-sheets.swift Resource/WidgetDemo 仍然没做的:苹果上只画了每个模板设计的那个尺寸,新加的小尺寸、中等尺寸排法没有在苹果上画图。这台 Mac 没有签名、没有授权,所以日历、健康、照片、提醒事项、GitHub、iCloud 这些模板画出来的是"未连接"的样子。Countdown 没设置时的小尺寸标题"Your next mome…"是模板有意把标题截到 14 个字,没改。 +## 2026-11-18,示例排版、加注释之后的参考文件 + +`Script.bundle` 和 `Script.android` 下的 191 个 `.js`、`.jsx` 示例用 Prettier 排了版,又加了给新手看的注释,`Gallery/` 里的副本也同步了。这一节记的是之后的检查:哪些随仓库保存的参考文件依赖示例的原文,重新生成了哪些,以及发现的一个问题(排版面板读不了排过版的代码,后来在面板里修了)。都是在同一台 Mac 上跑的(macOS 27.2,Apple 芯片)。 + +### "只动了注释和排版"是怎么查的 + +- 画出来的树一个字节都没变:`cd Web/preview-engine && npm test` 用现在的示例重新算出每棵树,和排版之前在苹果上录的 `native-trees.json` 逐字节比较,199 个测试都通过。这个文件这次没有重新生成。 +- 加注释的几次提交,合并之前逐行核对过只多了注释和空行(这是提交的人做的,这一节没有重做)。 +- 两个坑,改示例时要记住: + - 各个运行时是在脚本的文字里找 `$render`、`moment(`、`moment.` 的,注释里不能出现这几个写法。 + - Prettier 会把 JSX 文字里连着的两个空格并成一个,所以三个动画示例的标题("LISSAJOUS 7×11"、"ORBITAL 2:3:5"、"PHASE WAVE Δφ=40°")现在写成花括号里的字符串。 + +### 依赖示例原文的参考文件 + +在 `Tests/ScriptWidgetRuntimeTests`、`Web/preview-engine/test`、`Web/studio/test`、`Editor/editorfe/test`、`Scripts/tests`、`Android/core/src/test`、`Linux/crates/*/tests`、`Windows/tests` 里找了带 `source` 字段、哈希、字节数、行列号或者示例代码片段的地方: + +| 文件 | 存了什么 | 结果 | +| --- | --- | --- | +| `Web/preview-engine/test/parity/material-study-trees.json` | Material Study 的原文和 48 棵树 | 重新生成了。48 棵树和原来逐字相同,只有 `source` 变了(1207 个字符变成 1902 个) | +| `Web/preview-engine/test/parity/layout-edit-trees.json` | Layout Starter 的原文、在排版面板里改过之后的原文,以及两棵树 | 面板修好之后重新生成了。两棵树(改之前、改之后)和原来逐字相同,只有两段 `source` 变了 | +| `theme-edit-trees.json`、`asset-edit-trees.json` | 也有 `source`,但那是测试里自己写的一段代码,不是示例 | 不受影响,没动 | +| `Gallery/index.json` 里的字节数和 SHA-256 | Gallery 副本的 | 同步时已经更新,`sync-gallery-templates.mjs` 通过 | +| 其余的 `*-trees.json`、`native-trees.json` | 只有树 | 不受影响,没动 | + +`material-study-trees.json` 是在 iOS 27.2 模拟器(iPhone 18 Pro Max)上用 `TEST_RUNNER_SCRIPTWIDGET_EXPORT_MATERIAL_TREES=1` 只跑 `testMaterialStudyCanonicalTreesAndStaticAccessibilityCaptures` 生成的;`layout-edit-trees.json` 是用 `TEST_RUNNER_SCRIPTWIDGET_EXPORT_LAYOUT_TREES=1` 只跑 `testLayoutStarterEditsRenderWithNativeJavaScriptCore` 生成的,改动是真的编辑器(WKWebView 里的排版面板)做的。面板修好之后 Material Study 的原文没有再变,`material-study-trees.json` 不用再生成。 + +`layout-edit-trees.json` 里改之后的原文和模板只差两处,都是面板写的:`alignment="leading"` 变成 `alignment={"trailing"}`;占三行的 `<text …>`、`Make today yours`、`</text>` 变成一行 `<text …>{"A calmer day"}</text>`。注释都还在。 + +### 发现的问题:排版面板打不开排过版的示例(已在面板里修好) + +这不是参考文件过期,是行为变了,所以当时没有去改测试的期望值,而是报了出来。 + +编辑器的排版面板(`Editor/editorfe/src/visualLayout.js`)当时读不了排过版的示例,原因有两个,各自单独就够: + +- Prettier 在 `$render(` 的元素后面加了一个逗号(`</vstack>,` 换行 `);`)。面板把它当成"不是直接的 `$render(<元素>)`",只让在代码里改。 +- 注释写成了 JSX 里的 `{/* … */}`。面板把它当成语法错误,提示"Fix the JavaScript/JSX syntax before using Layout"。 + +用 `parseVisualLayout` 把 140 个 `main.jsx` 各读一遍: + +| 时候 | 面板能打开 | 只能在代码里改 | 报语法错误 | +| --- | --- | --- | --- | +| 排版之前 | 136 | 4 | 0 | +| 只排了版 | 20 | 120 | 0 | +| 排了版、加了注释,面板修之前 | 8 | 61 | 71 | +| 面板修好之后 | 136 | 4 | 0 | + +修之前 Layout Starter 和 Material Study 都读不了,两个 `VisualLayoutEditorTests`(`testLayoutStarterEditsRenderWithNativeJavaScriptCore`、`testNativeMaterialPropertyEditingPreservesSourceAndHistory`)和 `Web/studio` 的两个测试因此失败,`layout-edit-trees.json` 也生成不出来。 + +修的是面板,不是示例(提交"Layout panel: read code as a formatter writes it"):`$render(` 的元素后面的逗号和旁边的注释不再算作参数;`{/* … */}` 这样的注释子节点在解析用的副本里换成等长的 `{0 }`,位置不变,显示和修改读的还是原文;单独占一行的文字和写在一行里的一样可以改。两个平台的 `StudioEditor.bundle` 重新构建了。面板现在能打开的示例是 136 个,和排版之前一样,一个都没少。 + +### 面板的改动复查 + +担心的是:解析用的是换过注释的副本,改动却要落在原文上。用现在的 Layout Starter 和 Material Study 各试了改文字、改属性、加图层、删第一个和最后一个子图层、把最后一个移到最前、把第一个移到最后,共 14 次(Material Study 的改属性那一次被面板拒绝,因为那个容器没有这个属性可改,其余 13 次都做了): + +- 每个图层的位置都指在原文的 `<标签` 上、结束在 `>` 上;13 次改出来的代码都能再被面板读出来,都能运行,注释一条没少。没有发现改错位置的情况。 +- 排得不好看的地方,都不影响运行,原因是面板只插入和删除文字、不重新排版:加的和移过去的图层紧贴在前一个图层后面或者收尾标签前面,不另起一行;删掉或移走的地方留下一个只有缩进的空行。 +- 注释不跟着图层走:删掉或移走一个图层,原来写在它上面的注释留在原处,会变成在说下一个图层。 +- 文字图层里如果夹着注释(`<text>{/* 说明 */}Hi</text>`),改文字会把这条注释一起换掉。 +- 还读不了的两种写法,面板会拒绝并保留原文:注释子节点里用的是 `//`(`{` 换行 `// 说明` 换行 `}`);前面的字符串里有 `{/*`、后面又有注释子节点时,副本会把中间一段当成注释,报语法错误。示例里没有这两种写法。 + +这些都没有改,只记在这里。 + +### 结果 + +面板修好、两个参考文件都重新生成之后: + +| 检查 | 结果 | +| --- | --- | +| 整个 `ScriptWidgetRuntimeTests`,和 `release-readiness.sh` 一样的写法(`xcodebuild -quiet -project macOS/ScriptWidgetMac.xcodeproj -scheme ScriptWidgetRuntimeTests -destination 'platform=macOS' -derivedDataPath … CODE_SIGNING_ALLOWED=NO test`) | 809 个:777 个通过,32 个跳过,没有失败 | +| `cd Web/preview-engine && npm test` | 199 个通过 | +| `cd Web/studio && npm test` | 114 个通过 | +| `cd Editor/editorfe && npm test` | 59 个通过 | +| `node Scripts/validate-release.mjs`、`sync-gallery-templates.mjs`、`validate-doc-links.mjs`、`node --test Scripts/tests/*.mjs` | 都通过(最后一个是 7 个测试) | +| `./Scripts/release-readiness.sh`(`SCRIPTWIDGET_IOS_DESTINATION='platform=iOS Simulator,name=iPhone 18 Pro Max'`,这台机器没有装脚本默认的 iPhone 17) | 跑到最后一行,通过。里面包括:编辑器重新构建后两个 `StudioEditor.bundle` 和仓库里的一样;Web Studio 的浏览器冒烟测试都跑了(没有跳过);macOS 的测试 809 个里 777 个通过、32 个跳过;macOS 和 iOS 的应用都能构建;iOS 模拟器上整个 `ScriptWidgetRuntimeTests` 820 个里 789 个通过、31 个跳过,没有失败 | + +面板修之前的数,留着对照:同一条 macOS 命令是 809 个里 775 个通过、32 个跳过、2 个失败(上面两个 `VisualLayoutEditorTests`);`Web/studio` 是 114 个里 2 个失败;`Editor/editorfe` 是 55 个通过;`cargo test --locked --workspace` 是 506 个通过、1 个忽略。不加 `CODE_SIGNING_ALLOWED=NO`(签了名的构建)时还多一个失败,`LegacyCutoverProcessTests.testIndependentLegacyWriterStopsBeforeMigrationAndCannotRestartAfterReady`:它不读任何示例(它把应用当子进程启动),只在签了名的构建里失败,为什么没有查。 + +### 没跑的 + +- Android 的测试(`:core:testDebugUnitTest`)、Windows 的测试这一节没跑;面板修好之后也没有再跑 `cargo test`(面板的改动不进 Linux 的程序)。 +- 没有用手在真的编辑器里点开排版面板看。原生的两个测试是在 WKWebView 里真的点了面板的按钮;上面"复查"里的 14 次是直接调面板的函数。 + +### 之后补上的:布局面板改代码时的三处毛糙 + +上面的复核里列了三处没改的地方,这里改了(`Editor/editorfe/src/visualLayout.js`,两个平台的编辑器包重新生成): + +- 在一层一行的代码里增加或移动图层,新图层自己占一行,缩进和它的新邻居一样;删除或移走图层时连同它占的整行一起去掉,不再留下只有空格的行。写在一行里的代码还是原样拼在一行里。 +- 紧挨在图层上面的注释(中间没有空行)跟着图层一起移动、一起删除。 +- 文字里面带注释时,改文字只替换文字本身,注释留着。 + +| 检查(Mac) | 结果 | +| --- | --- | +| `cd Editor/editorfe && npm test` | 63 个通过;新增 3 个测试,原有 2 个测试里写死的旧结果(留下一行空格、新图层贴在结束标签前)改成了新的结果 | +| `cd Web/studio && npm test` | 114 个通过,`layout-edit-trees.json` 不用重新生成(面板对 Layout Starter 做的那两处修改结果没有变) | + +没做的:没有在真正的面板里用手点;Apple 平台的测试由这个 PR 的 CI 来跑。 + +## 2026-11-18,第二台测试虚拟机:0.1.4(侧边栏分成四项) + +机器同上(Omarchy 4.5,aarch64 虚拟机),真实会话。 + +管理窗口的"Templates"页原来把模板、组件示例、API 示例三组排在一页里。0.1.4 和 Windows 版一样分成侧边栏的四项:My widgets、Templates、Components、APIs;`--page` 多了 `components` 和 `apis`。 + +| 检查 | 结果 | +| --- | --- | +| `cargo test --locked --workspace`(虚拟机里) | 512 个通过,1 个忽略 | +| `sh install.sh` 覆盖安装 0.1.4,`scriptwidget doctor` | 通过;外壳重启后桌面上四个小组件都在,没有新的崩溃报告 | +| `scriptwidget-studio --page components` | 侧边栏四项,Components 高亮,页面只列组件示例;截图在 `images/studio-components.png` | +| `--page apis`、`--page templates` | 各自只列自己那一组;截图在 `images/studio-apis.png`、`images/studio-templates.png` | +| `--page template:component/gauge` | 打开的是组件示例,侧边栏高亮的是 Components;代码是排版并加了注释之后的样子 | +| 虚拟机里的共享脚本(`Linux/assets`) | 虚拟机里没有 esbuild,`build-shared-js.mjs` 在那里跑不了;用的是从 Mac 拷过去的那一份,和 Mac 上这次重新生成的逐个文件比过,校验值相同 | + +没做的:四个页面是用 `--page` 直接打开后截图看的,没有用虚拟指针去点侧边栏的四项,也没有点返回键。中文界面没有截图。APIs 页里 console、device、file、scheme 四张卡片画的是"#UI Not Found#":这四个示例只调用接口、不画界面,这次没改。 + ## 没跑的(汇总) - 真实的 Linux 电脑、真实的 x86_64 处理器、真实显卡、Omarchy 以外的桌面。 diff --git a/docs/platform-support.md b/docs/platform-support.md index 2d20cd66..d6d65140 100644 --- a/docs/platform-support.md +++ b/docs/platform-support.md @@ -29,6 +29,28 @@ The browser preview in [Web Studio](web-studio-browser.md) is a design tool, not | Wallpaper colors (`material.<role>`) | No, the color is ignored | No | Yes | No | No | | Automation entry point for other apps | No | No | Yes | No | No | +## Components + +What a script draws with. Android, Windows and Linux use one shared renderer, so a component is on all three or on none; the rows say what a system draws differently. Each component's properties are in the [runtime API reference](scriptwidget-runtime-api.md). + +<!-- components:start --> +| Component | iPhone and iPad | Mac | Android | Windows | Linux | +| --- | --- | --- | --- | --- | --- | +| Layout: `<vstack>`, `<hstack>`, `<zstack>`, `<vgrid>`, `<hgrid>`, `<spacer>`, `<divider>` | Yes | Yes | Yes | Yes | Yes | +| Text: `<text>`, `<label>`, `<badge>`, `<chip>`, `<stat>` | Yes | Yes | Yes, in Inter, which is wider than the Apple system font | Yes, in Inter | Yes, in Inter | +| Shapes: `<rect>`, `<roundedrect>`, `<capsule>`, `<ellipse>`, `<circle>`, `<line>` | Yes | Yes | Yes | Yes | Yes | +| Values: `<gauge>`, `<progress>`, `<ring>`, `<chart>` | Yes | Yes | Yes | Yes | Yes | +| `<image>` | Yes | Yes | Yes | Yes | Yes | +| `<icon>` and `systemName` images | Yes | Yes | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | +| `<date>` | Yes | Yes | `timer` and a `time` of now tick by themselves; `relative`, `offset` and `date` are redrawn at each refresh | A timer is redrawn every second and a clock time every minute | A timer is redrawn every second and a clock time every minute | +| `<gif>` | Animated in the app's preview; in a widget the system decides and may hold one frame | The first frame | Up to 24 sampled frames | The first frame | Animated on the desktop, at most 60 frames | +| The `animation` property (clock hands, swing) | Moves in the app's preview; in a widget the system schedules it and may hold one frame | Standard clock hands show the time without moving; the others stay at rest | Standard clock hands are a system clock; swing and custom intervals play as frames | The first frame | The first frame | +| `<button>`, `<toggle>` | Yes, from iOS 17 | Yes, from macOS 14 | Yes | Yes | Yes | +| `<link>` | Yes | Yes | Yes | `http`, `https` and `mailto` only | `http`, `https` and `mailto` only | +| The `backgroundMaterial` property | Yes | Yes | The opaque `background` fallback | The opaque `background` fallback | The opaque `background` fallback | +| Scrolling `<list>` | No | No | Yes | No | No | +<!-- components:end --> + ## Data APIs <!-- platforms:start --> diff --git a/docs/runtime-api.md b/docs/runtime-api.md index 17d1eed8..8fa92fab 100644 --- a/docs/runtime-api.md +++ b/docs/runtime-api.md @@ -16,7 +16,7 @@ Removing or changing the meaning of a 1.0 global requires a new major API versio ### Which systems each API runs on -A widget package installs on every system, but not every API has something behind it everywhere. An API a system lacks answers `false` from `isAvailable()` and rejects its calls with `[unsupported_platform]`; `$system.platform()` tells a script where it runs. [Platform support](platform-support.md) explains each limit and lists the widget features by system; each API's own page repeats its line of this table. +A widget package installs on every system, but not every API has something behind it everywhere. An API a system lacks answers `false` from `isAvailable()` and rejects its calls with `[unsupported_platform]`; `$system.platform()` tells a script where it runs. [Platform support](platform-support.md) explains each limit and lists the widget features by system; each API's own page repeats its line of this table. The same for the JSX components is at the top of the [component reference](scriptwidget-runtime-api.md). <!-- platforms:start --> | API | iPhone and iPad | Mac | Android | Windows | Linux | diff --git a/docs/scriptwidget-runtime-api.md b/docs/scriptwidget-runtime-api.md index 8056457e..85eeae26 100644 --- a/docs/scriptwidget-runtime-api.md +++ b/docs/scriptwidget-runtime-api.md @@ -2,6 +2,26 @@ > Generated from Studio's static API metadata (schema v1, runtime 1.6). The native runtime switch is authoritative. Do not edit by hand. +## Which systems each component runs on + +Every component below exists on iPhone, iPad, Mac, Android, Windows and Linux, except the scrolling `<list>`, which only Android has and which is not in this reference (see [ScriptWidget for Android](android/README.md)). What a system draws differently is in this table; [Platform support](platform-support.md) has the same table beside the APIs and the widget features. + +| Component | iPhone and iPad | Mac | Android | Windows | Linux | +| --- | --- | --- | --- | --- | --- | +| Layout: `<vstack>`, `<hstack>`, `<zstack>`, `<vgrid>`, `<hgrid>`, `<spacer>`, `<divider>` | Yes | Yes | Yes | Yes | Yes | +| Text: `<text>`, `<label>`, `<badge>`, `<chip>`, `<stat>` | Yes | Yes | Yes, in Inter, which is wider than the Apple system font | Yes, in Inter | Yes, in Inter | +| Shapes: `<rect>`, `<roundedrect>`, `<capsule>`, `<ellipse>`, `<circle>`, `<line>` | Yes | Yes | Yes | Yes | Yes | +| Values: `<gauge>`, `<progress>`, `<ring>`, `<chart>` | Yes | Yes | Yes | Yes | Yes | +| `<image>` | Yes | Yes | Yes | Yes | Yes | +| `<icon>` and `systemName` images | Yes | Yes | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | Yes; SF Symbols are drawn with look-alike icons, and a name without one shows a placeholder | +| `<date>` | Yes | Yes | `timer` and a `time` of now tick by themselves; `relative`, `offset` and `date` are redrawn at each refresh | A timer is redrawn every second and a clock time every minute | A timer is redrawn every second and a clock time every minute | +| `<gif>` | Animated in the app's preview; in a widget the system decides and may hold one frame | The first frame | Up to 24 sampled frames | The first frame | Animated on the desktop, at most 60 frames | +| The `animation` property (clock hands, swing) | Moves in the app's preview; in a widget the system schedules it and may hold one frame | Standard clock hands show the time without moving; the others stay at rest | Standard clock hands are a system clock; swing and custom intervals play as frames | The first frame | The first frame | +| `<button>`, `<toggle>` | Yes, from iOS 17 | Yes, from macOS 14 | Yes | Yes | Yes | +| `<link>` | Yes | Yes | Yes | `http`, `https` and `mailto` only | `http`, `https` and `mailto` only | +| The `backgroundMaterial` property | Yes | Yes | The opaque `background` fallback | The opaque `background` fallback | The opaque `background` fallback | +| Scrolling `<list>` | No | No | Yes | No | No | + ## Components ### `<VStack>` diff --git a/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/assets/index-5y-iWtKj.js b/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/assets/index-Bc_zNuTW.js similarity index 72% rename from iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/assets/index-5y-iWtKj.js rename to iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/assets/index-Bc_zNuTW.js index 9a73af91..594c1da9 100644 --- a/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/assets/index-5y-iWtKj.js +++ b/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/assets/index-Bc_zNuTW.js @@ -1,14 +1,14 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();const Yd="modulepreload",Nd=function(n,e){return new URL(n,e).href},al={},Cr=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let c=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=c(t.map(h=>{if(h=Nd(h,i),h in al)return;al[h]=!0;const u=h.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(i)for(let p=o.length-1;p>=0;p--){const m=o[p];if(m.href===h&&(!u||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${f}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Yd,u||(d.as="script"),d.crossOrigin="",d.href=h,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((p,m)=>{d.addEventListener("load",p),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};let po=[],mh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4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)(e%2?mh:po).push(t=t+n[e])})();function Hd(n){if(n<768)return!1;for(let e=0,t=po.length;;){let i=e+t>>1;if(n<po[i])t=i;else if(n>=mh[i])e=i+1;else return!0;if(e==t)return!1}}function ll(n){return n>=127462&&n<=127487}const cl=8205;function Gd(n,e,t=!0,i=!0){return(t?gh:_d)(n,e,i)}function gh(n,e,t){if(e==n.length)return e;e&&Oh(n.charCodeAt(e))&&yh(n.charCodeAt(e-1))&&e--;let i=Tr(n,e);for(e+=hl(i);e<n.length;){let s=Tr(n,e);if(i==cl||s==cl||t&&Hd(s))e+=hl(s),i=s;else if(ll(s)){let r=0,o=e-2;for(;o>=0&&ll(Tr(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function _d(n,e,t){for(;e>1;){let i=gh(n,e-2,t);if(i<e)return i;e--}return 0}function Tr(n,e){let t=n.charCodeAt(e);if(!yh(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return Oh(i)?(t-55296<<10)+(i-56320)+65536:t}function Oh(n){return n>=56320&&n<57344}function yh(n){return n>=55296&&n<56320}function hl(n){return n<65536?1:2}class se{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Bi(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),kt.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Bi(this,e,t);let i=[];return this.decompose(e,t,i,0),kt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new pn(this),r=new pn(e);for(let o=t,a=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(a+=s.value.length,s.done||a>=i)return!0}}iter(e=1){return new pn(this,e)}iterRange(e,t=this.length){return new Ah(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new bh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?se.empty:e.length<=32?new we(e):kt.from(we.split(e,[]))}}class we extends se{constructor(e,t=Jd(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],a=s+o.length;if((t?i:a)>=e)return new ep(s,a,i,o);s=a+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new we(ul(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),a=gs(r.text,o.text.slice(),0,r.length);if(a.length<=32)i.push(new we(a,o.length+r.length));else{let l=a.length>>1;i.push(new we(a.slice(0,l)),new we(a.slice(l)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof we))return super.replace(e,t,i);[e,t]=Bi(this,e,t);let s=gs(this.text,gs(i.text,ul(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new we(s,r):kt.from(we.split(s,[]),r)}sliceString(e,t=this.length,i=` +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();const Jd="modulepreload",ep=function(n,e){return new URL(n,e).href},hl={},Rr=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let c=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=c(t.map(h=>{if(h=ep(h,i),h in hl)return;hl[h]=!0;const u=h.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(i)for(let p=o.length-1;p>=0;p--){const m=o[p];if(m.href===h&&(!u||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${f}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Jd,u||(d.as="script"),d.crossOrigin="",d.href=h,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((p,m)=>{d.addEventListener("load",p),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};let go=[],Ah=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,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(let e=0,t=0;e<n.length;e++)(e%2?Ah:go).push(t=t+n[e])})();function tp(n){if(n<768)return!1;for(let e=0,t=go.length;;){let i=e+t>>1;if(n<go[i])t=i;else if(n>=Ah[i])e=i+1;else return!0;if(e==t)return!1}}function ul(n){return n>=127462&&n<=127487}const fl=8205;function ip(n,e,t=!0,i=!0){return(t?bh:np)(n,e,i)}function bh(n,e,t){if(e==n.length)return e;e&&Sh(n.charCodeAt(e))&&xh(n.charCodeAt(e-1))&&e--;let i=$r(n,e);for(e+=dl(i);e<n.length;){let s=$r(n,e);if(i==fl||s==fl||t&&tp(s))e+=dl(s),i=s;else if(ul(s)){let r=0,o=e-2;for(;o>=0&&ul($r(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function np(n,e,t){for(;e>1;){let i=bh(n,e-2,t);if(i<e)return i;e--}return 0}function $r(n,e){let t=n.charCodeAt(e);if(!xh(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return Sh(i)?(t-55296<<10)+(i-56320)+65536:t}function Sh(n){return n>=56320&&n<57344}function xh(n){return n>=55296&&n<56320}function dl(n){return n<65536?1:2}class se{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Bi(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),kt.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Bi(this,e,t);let i=[];return this.decompose(e,t,i,0),kt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new pn(this),r=new pn(e);for(let o=t,a=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(a+=s.value.length,s.done||a>=i)return!0}}iter(e=1){return new pn(this,e)}iterRange(e,t=this.length){return new vh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new wh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?se.empty:e.length<=32?new we(e):kt.from(we.split(e,[]))}}class we extends se{constructor(e,t=sp(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],a=s+o.length;if((t?i:a)>=e)return new rp(s,a,i,o);s=a+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new we(pl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),a=ys(r.text,o.text.slice(),0,r.length);if(a.length<=32)i.push(new we(a,o.length+r.length));else{let l=a.length>>1;i.push(new we(a.slice(0,l)),new we(a.slice(l)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof we))return super.replace(e,t,i);[e,t]=Bi(this,e,t);let s=ys(this.text,ys(i.text,pl(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new we(s,r):kt.from(we.split(s,[]),r)}sliceString(e,t=this.length,i=` `){[e,t]=Bi(this,e,t);let s="";for(let r=0,o=0;r<=t&&o<this.text.length;o++){let a=this.text[o],l=r+a.length;r>e&&o&&(s+=i),e<l&&t>r&&(s+=a.slice(Math.max(0,e-r),t-r)),r=l+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new we(i,s)),i=[],s=-1);return s>-1&&t.push(new we(i,s)),t}}class kt extends se{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],a=s+o.length,l=i+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,i,s);s=a+1,i=l+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r<this.children.length;r++){let a=this.children[r],l=o+a.length;if(e<=l&&t>=o){let c=s&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!c?i.push(a):a.decompose(e-o,t-o,i,c)}o=l+1}}replace(e,t,i){if([e,t]=Bi(this,e,t),i.lines<this.lines)for(let s=0,r=0;s<this.children.length;s++){let o=this.children[s],a=r+o.length;if(e>=r&&t<=a){let l=o.replace(e-r,t-r,i),c=this.lines-o.lines+l.lines;if(l.lines<c>>4&&l.lines>c>>6){let h=this.children.slice();return h[s]=l,new kt(h,this.length-(t-e)+i.length)}return super.replace(r,a,l)}r=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` -`){[e,t]=Bi(this,e,t);let s="";for(let r=0,o=0;r<this.children.length&&o<=t;r++){let a=this.children[r],l=o+a.length;o>e&&r&&(s+=i),e<l&&t>o&&(s+=a.sliceString(e-o,t-o,i)),o=l+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof kt))return 0;let i=0,[s,r,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==a)return i;let l=this.children[s],c=e.children[r];if(l!=c)return i+l.scanIdentical(c,t);i+=l.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new we(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,a=[],l=0,c=-1,h=[];function u(d){let p;if(d.lines>r&&d instanceof kt)for(let m of d.children)u(m);else d.lines>o&&(l>o||!l)?(f(),a.push(d)):d instanceof we&&l&&(p=h[h.length-1])instanceof we&&d.lines+p.lines<=32?(l+=d.lines,c+=d.length+1,h[h.length-1]=new we(p.text.concat(d.text),p.length+1+d.length)):(l+d.lines>s&&f(),l+=d.lines,c+=d.length+1,h.push(d))}function f(){l!=0&&(a.push(h.length==1?h[0]:kt.from(h,c)),c=-1,l=h.length=0)}for(let d of e)u(d);return f(),a.length==1?a[0]:new kt(a,t)}}se.empty=new we([""],0);function Jd(n){let e=-1;for(let t of n)e+=t.length+1;return e}function gs(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r<n.length&&s<=i;r++){let a=n[r],l=s+a.length;l>=t&&(l>i&&(a=a.slice(0,i-s)),s<t&&(a=a.slice(t-s)),o?(e[e.length-1]+=a,o=!1):e.push(a)),s=l+1}return e}function ul(n,e,t){return gs(n,[""],e,t)}class pn{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof we?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,a=s instanceof we?s.text.length:s.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` -`,this;e--}else if(s instanceof we){let l=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=s.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof we?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Ah{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new pn(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class bh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(se.prototype[Symbol.iterator]=function(){return this.iter()},pn.prototype[Symbol.iterator]=Ah.prototype[Symbol.iterator]=bh.prototype[Symbol.iterator]=function(){return this});class ep{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}}function Bi(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function Ze(n,e,t=!0,i=!0){return Gd(n,e,t,i)}function tp(n){return n>=56320&&n<57344}function ip(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!ip(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return tp(i)?(t-55296<<10)+(i-56320)+65536:t}function fa(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Qt(n){return n<65536?1:2}const mo=/\r\n?|\n/;var De=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(De||(De={}));class Zt{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,s=0;t<this.sections.length;){let r=this.sections[t++],o=this.sections[t++];o<0?(e(i,s,r),s+=r):s+=o,i+=r}}iterChangedRanges(e,t=!1){go(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let i=this.sections[t++],s=this.sections[t++];s<0?e.push(i,s):e.push(s,i)}return new Zt(e)}composeDesc(e){return this.empty?e:e.empty?this:Sh(this,e)}mapDesc(e,t=!1){return e.empty?this:Oo(this,e,t)}mapPos(e,t=-1,i=De.Simple){let s=0,r=0;for(let o=0;o<this.sections.length;){let a=this.sections[o++],l=this.sections[o++],c=s+a;if(l<0){if(c>e)return r+(e-s);r+=a}else{if(i!=De.Simple&&c>=e&&(i==De.TrackDel&&s<e&&c>e||i==De.TrackBefore&&s<e||i==De.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!a)return e==s||t<0?r:r+l;r+=l}s=c}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i<this.sections.length&&s<=t;){let r=this.sections[i++],o=this.sections[i++],a=s+r;if(o>=0&&s<=t&&a>=e)return s<e&&a>t?"cover":!0;s=a}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let i=this.sections[t++],s=this.sections[t++];e+=(e?" ":"")+i+(s>=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Zt(e)}static create(e){return new Zt(e)}}class Re extends Zt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return go(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Oo(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s<t.length;s+=2){let o=t[s],a=t[s+1];if(a>=0){t[s]=a,t[s+1]=o;let l=s>>1;for(;i.length<l;)i.push(se.empty);i.push(o?e.slice(r,r+o):se.empty)}r+=o}return new Re(t,i)}compose(e){return this.empty?e:e.empty?this:Sh(this,e,!0)}map(e,t=!1){return e.empty?this:Oo(this,e,t,!0)}iterChanges(e,t=!1){go(this,e,t)}get desc(){return Zt.create(this.sections)}filter(e){let t=[],i=[],s=[],r=new Sn(this);e:for(let o=0,a=0;;){let l=o==e.length?1e9:e[o++];for(;a<l||a==l&&r.len==0;){if(r.done)break e;let h=Math.min(r.len,l-a);Xe(s,h,-1);let u=r.ins==-1?-1:r.off==0?r.ins:0;Xe(t,h,u),u>0&&Ht(i,t,r.text),r.forward(h),a+=h}let c=e[o++];for(;a<c;){if(r.done)break e;let h=Math.min(r.len,c-a);Xe(t,h,-1),Xe(s,h,r.ins==-1?-1:r.off==0?r.ins:0),r.forward(h),a+=h}}return{changes:new Re(t,i),filtered:Zt.create(s)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t],s=this.sections[t+1];s<0?e.push(i):s==0?e.push([i]):e.push([i].concat(this.inserted[t>>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,a=null;function l(h=!1){if(!h&&!s.length)return;o<t&&Xe(s,t-o,-1);let u=new Re(s,r);a=a?a.compose(u.map(a)):u,s=[],r=[],o=0}function c(h){if(Array.isArray(h))for(let u of h)c(u);else if(h instanceof Re){if(h.length!=t)throw new RangeError(`Mismatched change set length (got ${h.length}, expected ${t})`);l(),a=a?a.compose(h.map(a)):h}else{let{from:u,to:f=u,insert:d}=h;if(u>f||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let p=d?typeof d=="string"?se.of(d.split(i||mo)):d:se.empty,m=p.length;if(u==f&&m==0)return;u<o&&l(),u>o&&Xe(s,u-o,-1),Xe(s,f-u,m),Ht(r,s,p),o=f}}return c(e),l(!a),a}static empty(e){return new Re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;s<e.length;s++){let r=e[s];if(typeof r=="number")t.push(r,-1);else{if(!Array.isArray(r)||typeof r[0]!="number"||r.some((o,a)=>a&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length<s;)i.push(se.empty);i[s]=se.of(r.slice(1)),t.push(r[0],i[s].length)}}}return new Re(t,i)}static createSet(e,t){return new Re(e,t)}}function Xe(n,e,t,i=!1){if(e==0&&t<=0)return;let s=n.length-2;s>=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function Ht(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i<n.length)n[n.length-1]=n[n.length-1].append(t);else{for(;n.length<i;)n.push(se.empty);n.push(t)}}function go(n,e,t){let i=n.inserted;for(let s=0,r=0,o=0;o<n.sections.length;){let a=n.sections[o++],l=n.sections[o++];if(l<0)s+=a,r+=a;else{let c=s,h=r,u=se.empty;for(;c+=a,h+=l,l&&i&&(u=u.append(i[o-2>>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(s,c,r,h,u),s=c,r=h}}}function Oo(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Sn(n),a=new Sn(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);Xe(s,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len<o.len||a.len==o.len&&!t))){let c=a.len;for(Xe(s,a.ins,-1);c;){let h=Math.min(o.len,c);o.ins>=0&&l<o.i&&o.len<=h&&(Xe(s,0,o.ins),r&&Ht(r,s,o.text),l=o.i),o.forward(h),c-=h}a.next()}else if(o.ins>=0){let c=0,h=o.len;for(;h;)if(a.ins==-1){let u=Math.min(h,a.len);c+=u,h-=u,a.forward(u)}else if(a.ins==0&&a.len<h)h-=a.len,a.next();else break;Xe(s,c,l<o.i?o.ins:0),r&&l<o.i&&Ht(r,s,o.text),l=o.i,o.forward(o.len-h)}else{if(o.done&&a.done)return r?Re.createSet(s,r):Zt.create(s);throw new Error("Mismatched change set lengths")}}}function Sh(n,e,t=!1){let i=[],s=t?[]:null,r=new Sn(n),o=new Sn(e);for(let a=!1;;){if(r.done&&o.done)return s?Re.createSet(i,s):Zt.create(i);if(r.ins==0)Xe(i,r.len,0,a),r.next();else if(o.len==0&&!o.done)Xe(i,0,o.ins,a),s&&Ht(s,i,o.text),o.next();else{if(r.done||o.done)throw new Error("Mismatched change set lengths");{let l=Math.min(r.len2,o.len),c=i.length;if(r.ins==-1){let h=o.ins==-1?-1:o.off?0:o.ins;Xe(i,l,h,a),s&&h&&Ht(s,i,o.text)}else o.ins==-1?(Xe(i,r.off?0:r.len,l,a),s&&Ht(s,i,r.textBit(l))):(Xe(i,r.off?0:r.len,o.off?0:o.ins,a),s&&!o.off&&Ht(s,i,o.text));a=(r.ins>l||o.ins>=0&&o.len>l)&&(a||i.length>c),r.forward2(l),o.forward(l)}}}}class Sn{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?se.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?se.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Yt{constructor(e,t,i,s){this.from=e,this.to=t,this.flags=i,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new Yt(i,s,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return A.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return A.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return A.range(e.anchor,e.head)}static create(e,t,i,s){return new Yt(e,t,i,s)}}class A{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:A.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;i<this.ranges.length;i++)if(!this.ranges[i].eq(e.ranges[i],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new A([this.main],0)}addRange(e,t=!0){return A.create([e].concat(this.ranges),t?0:this.mainIndex+1)}replaceRange(e,t=this.mainIndex){let i=this.ranges.slice();return i[t]=e,A.create(i,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new A(e.ranges.map(t=>Yt.fromJSON(t)),e.main)}static single(e,t=e){return new A([A.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;s<e.length;s++){let r=e[s];if(r.empty?r.from<=i:r.from<i)return A.normalized(e.slice(),t);i=r.to}return new A(e,t)}static cursor(e,t=0,i,s){return Yt.create(e,e,(t==0?0:t<0?8:16)|(i==null?7:Math.min(6,i)),s)}static range(e,t,i,s,r){let o=s==null?7:Math.min(6,s);return!r&&e!=t&&(r=t<e?1:-1),r&&(o|=r<0?8:16),t<e?Yt.create(t,e,o|32,i):Yt.create(e,t,o,i)}static undirectionalRange(e,t){return Yt.create(e,t,64,void 0)}static normalized(e,t=0){let i=e[t];e.sort((s,r)=>s.from-r.from),t=e.indexOf(i);for(let s=1;s<e.length;s++){let r=e[s],o=e[s-1];if(r.empty?r.from<=o.to:r.from<o.to){let a=o.from,l=Math.max(r.to,o.to);s<=t&&t--,e.splice(--s,2,r.anchor>r.head?A.range(l,a):A.range(a,l))}}return new A(e,t)}}function xh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let da=0;class K{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=da++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new K(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:pa),!!e.static,e.enables)}of(e){return new Os([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Os(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Os(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function pa(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Os{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=da++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,a=this.type==2,l=!1,c=!1,h=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?c=!0:(((t=e[u.id])!==null&&t!==void 0?t:1)&1)==0&&h.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||c&&(f.docChanged||f.selection)||yo(u,h)){let d=i(u);if(a?!fl(d,u.values[o],s):!s(d,u.values[o]))return u.values[o]=d,1}return 0},reconfigure:(u,f)=>{let d,p=f.config.address[r];if(p!=null){let m=Cs(f,p);if(this.dependencies.every(g=>g instanceof K?f.facet(g)===u.facet(g):g instanceof Te?f.field(g,!1)==u.field(g,!1):!0)||(a?fl(d=i(u),m,s):s(d=i(u),m)))return u.values[o]=m,0}else d=i(u);return u.values[o]=d,1}}}get extension(){return this}}function fl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;i<n.length;i++)if(!t(n[i],e[i]))return!1;return!0}function yo(n,e){let t=!1;for(let i of e)mn(n,i)&1&&(t=!0);return t}function np(n,e,t){let i=t.map(l=>n[l.id]),s=t.map(l=>l.type),r=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let c=[];for(let h=0;h<i.length;h++){let u=Cs(l,i[h]);if(s[h]==2)for(let f of u)c.push(f);else c.push(u)}return e.combine(c)}return{create(l){for(let c of i)mn(l,c);return l.values[o]=a(l),1},update(l,c){if(!yo(l,r))return 0;let h=a(l);return e.compare(h,l.values[o])?0:(l.values[o]=h,1)},reconfigure(l,c){let h=yo(l,i),u=c.config.facets[e.id],f=c.facet(e);if(u&&!h&&pa(t,u))return l.values[o]=f,0;let d=a(l);return e.compare(d,f)?(l.values[o]=f,0):(l.values[o]=d,1)}}}const Vn=K.define({static:!0});class Te{constructor(e,t,i,s,r){this.id=e,this.createF=t,this.updateF=i,this.compareF=s,this.spec=r,this.provides=void 0}static define(e){let t=new Te(da++,e.create,e.update,e.compare||((i,s)=>i===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(Vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(Vn),o=s.facet(Vn),a;return(a=r.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(i.values[t]=a.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,Vn.of({field:this,create:e})]}get extension(){return this}}const fi={lowest:4,low:3,default:2,high:1,highest:0};function sn(n){return e=>new vh(e,n)}const ri={highest:sn(fi.highest),high:sn(fi.high),default:sn(fi.default),low:sn(fi.low),lowest:sn(fi.lowest)};class vh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class Gi{of(e){return new Ao(this,e)}reconfigure(e){return Gi.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Ao{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class Ps{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length<i.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let f of sp(e,t,o))f instanceof Te?s.push(f):(r[f.facet.id]||(r[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],c=[];for(let f of s)a[f.id]=c.length<<1,c.push(d=>f.slot(d));let h=i?.config.facets;for(let f in r){let d=r[f],p=d[0].facet,m=h&&h[f]||[];if(d.every(g=>g.type==0))if(a[p.id]=l.length<<1|1,pa(m,d))l.push(i.facet(p));else{let g=p.combine(d.map(y=>y.value));l.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(a[g.id]=l.length<<1|1,l.push(g.value)):(a[g.id]=c.length<<1,c.push(y=>g.dynamicSlot(y)));a[p.id]=c.length<<1,c.push(g=>np(g,p,d))}}let u=c.map(f=>f(a));return new Ps(e,o,u,a,l,r)}}function sp(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,a){let l=s.get(o);if(l!=null){if(l<=a)return;let c=i[l].indexOf(o);c>-1&&i[l].splice(c,1),o instanceof Ao&&t.delete(o.compartment)}if(s.set(o,a),Array.isArray(o))for(let c of o)r(c,a);else if(o instanceof Ao){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;t.set(o.compartment,c),r(c,a)}else if(o instanceof vh)r(o.inner,o.prec);else if(o instanceof Te)i[a].push(o),o.provides&&r(o.provides,a);else if(o instanceof Os)i[a].push(o),o.facet.extensions&&r(o.facet.extensions,fi.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(c==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(c,a)}}return r(n,fi.default),i.reduce((o,a)=>o.concat(a))}function mn(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Cs(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const wh=K.define(),bo=K.define({combine:n=>n.some(e=>e),static:!0}),kh=K.define({combine:n=>n.length?n[0]:void 0,static:!0}),Qh=K.define(),Ph=K.define(),Ch=K.define(),Th=K.define({combine:n=>n.length?n[0]:!1});class qt{constructor(e,t){this.type=e,this.value=t}static define(){return new rp}}class rp{of(e){return new qt(this,e)}}class op{constructor(e){this.map=e}of(e){return new z(this,e)}}class z{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new z(this.type,t)}is(e){return this.type==e}static define(e={}){return new op(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}}z.reconfigure=z.define();z.appendConfig=z.define();class Pe{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&xh(i,t.newLength),r.some(a=>a.type==Pe.time)||(this.annotations=r.concat(Pe.time.of(Date.now())))}static create(e,t,i,s,r,o){return new Pe(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(Pe.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}Pe.time=qt.define();Pe.userEvent=qt.define();Pe.addToHistory=qt.define();Pe.remote=qt.define();function ap(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i<n.length&&(s==e.length||e[s]>=n[i]))r=n[i++],o=n[i++];else if(s<e.length)r=e[s++],o=e[s++];else return t;!t.length||t[t.length-1]<r?t.push(r,o):t[t.length-1]<o&&(t[t.length-1]=o)}}function Rh(n,e,t){var i;let s,r,o;return t?(s=e.changes,r=Re.empty(e.changes.length),o=n.changes.compose(e.changes)):(s=e.changes.map(n.changes),r=n.changes.mapDesc(e.changes,!0),o=n.changes.compose(s)),{changes:o,selection:e.selection?e.selection.map(r):(i=n.selection)===null||i===void 0?void 0:i.map(s),effects:z.mapEffects(n.effects,s).concat(z.mapEffects(e.effects,r)),annotations:n.annotations.length?n.annotations.concat(e.annotations):e.annotations,scrollIntoView:n.scrollIntoView||e.scrollIntoView}}function So(n,e,t){let i=e.selection,s=Zi(e.annotations);return e.userEvent&&(s=s.concat(Pe.userEvent.of(e.userEvent))),{changes:e.changes instanceof Re?e.changes:Re.of(e.changes||[],t,n.facet(kh)),selection:i&&(i instanceof A?i:A.single(i.anchor,i.head)),effects:Zi(e.effects),annotations:s,scrollIntoView:!!e.scrollIntoView}}function $h(n,e,t){let i=So(n,e.length?e[0]:{},n.doc.length);e.length&&e[0].filter===!1&&(t=!1);for(let r=1;r<e.length;r++){e[r].filter===!1&&(t=!1);let o=!!e[r].sequential;i=Rh(i,So(n,e[r],o?i.changes.newLength:n.doc.length),o)}let s=Pe.create(n,i.changes,i.selection,i.effects,i.annotations,i.scrollIntoView);return cp(t?lp(s):s)}function lp(n){let e=n.startState,t=!0;for(let s of e.facet(Qh)){let r=s(n);if(r===!1){t=!1;break}Array.isArray(r)&&(t=t===!0?r:ap(t,r))}if(t!==!0){let s,r;if(t===!1)r=n.changes.invertedDesc,s=Re.empty(e.doc.length);else{let o=n.changes.filter(t);s=o.changes,r=o.filtered.mapDesc(o.changes).invertedDesc}n=Pe.create(e,s,n.selection&&n.selection.map(r),z.mapEffects(n.effects,r),n.annotations,n.scrollIntoView)}let i=e.facet(Ph);for(let s=i.length-1;s>=0;s--){let r=i[s](n);r instanceof Pe?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof Pe?n=r[0]:n=$h(e,Zi(r),!1)}return n}function cp(n){let e=n.startState,t=e.facet(Ch),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=Rh(i,So(e,r,n.changes.newLength),!0))}return i==n?n:Pe.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const hp=[];function Zi(n){return n==null?hp:Array.isArray(n)?n:[n]}var ye=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(ye||(ye={}));const up=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let xo;try{xo=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function fp(n){if(xo)return xo.test(n);for(let e=0;e<n.length;e++){let t=n[e];if(/\w/.test(t)||t>"€"&&(t.toUpperCase()!=t.toLowerCase()||up.test(t)))return!0}return!1}function dp(n){return e=>{if(!/\S/.test(e))return ye.Space;if(fp(e))return ye.Word;for(let t=0;t<n.length;t++)if(e.indexOf(n[t])>-1)return ye.Word;return ye.Other}}class _{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let a=0;a<this.config.dynamicSlots.length;a++)mn(this,a<<1);this.computeSlot=null}field(e,t=!0){let i=this.config.address[e.id];if(i==null){if(t)throw new RangeError("Field is not present in this state");return}return mn(this,i),Cs(this,i)}update(...e){return $h(this,e,!0)}applyTransaction(e){let t=this.config,{base:i,compartments:s}=t;for(let a of e.effects)a.is(Gi.reconfigure)?(t&&(s=new Map,t.compartments.forEach((l,c)=>s.set(c,l)),t=null),s.set(a.value.compartment,a.value.extension)):a.is(z.reconfigure)?(t=null,i=a.value):a.is(z.appendConfig)&&(t=null,i=Zi(i).concat(a.value));let r;t?r=e.startState.values.slice():(t=Ps.resolve(i,s,this),r=new _(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(bo)?e.newSelection:e.newSelection.asSingle();new _(t,e.newDoc,o,r,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:A.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Zi(i.effects);for(let a=1;a<t.ranges.length;a++){let l=e(t.ranges[a]),c=this.changes(l.changes),h=c.map(s);for(let f=0;f<a;f++)r[f]=r[f].map(h);let u=s.mapDesc(c,!0);r.push(l.range.map(u)),s=s.compose(h),o=z.mapEffects(o,h).concat(z.mapEffects(Zi(l.effects),u))}return{changes:s,selection:A.create(r,t.mainIndex),effects:o}}changes(e=[]){return e instanceof Re?e:Re.of(e,this.doc.length,this.facet(_.lineSeparator))}toText(e){return se.of(e.split(this.facet(_.lineSeparator)||mo))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(mn(this,t),Cs(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let i in e){let s=e[i];s instanceof Te&&this.config.address[s.id]!=null&&(t[i]=s.spec.toJSON(this.field(e[i]),this))}return t}static fromJSON(e,t={},i){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let s=[];if(i){for(let r in i)if(Object.prototype.hasOwnProperty.call(e,r)){let o=i[r],a=e[r];s.push(o.init(l=>o.spec.fromJSON(a,l)))}}return _.create({doc:e.doc,selection:A.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=Ps.resolve(e.extensions||[],new Map),i=e.doc instanceof se?e.doc:se.of((e.doc||"").split(t.staticFacet(_.lineSeparator)||mo)),s=e.selection?e.selection instanceof A?e.selection:A.single(e.selection.anchor,e.selection.head):A.single(0);return xh(s,i.length),t.staticFacet(bo)||(s=s.asSingle()),new _(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(_.tabSize)}get lineBreak(){return this.facet(_.lineSeparator)||` -`}get readOnly(){return this.facet(Th)}phrase(e,...t){for(let i of this.facet(_.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(wh))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return dp(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,a=e-i;for(;o>0;){let l=Ze(t,o,!1);if(r(t.slice(l,o))!=ye.Word)break;o=l}for(;a<s;){let l=Ze(t,a);if(r(t.slice(a,l))!=ye.Word)break;a=l}return o==a?null:A.range(o+i,a+i)}}_.allowMultipleSelections=bo;_.tabSize=K.define({combine:n=>n.length?n[0]:4});_.lineSeparator=kh;_.readOnly=Th;_.phrases=K.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});_.languageData=wh;_.changeFilter=Qh;_.transactionFilter=Ph;_.transactionExtender=Ch;Gi.reconfigure=z.define();function yt(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],a=i[r];if(a===void 0)i[r]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](a,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}class Jt{eq(e){return this==e}range(e,t=e){return vo.create(e,t,this)}}Jt.prototype.startSide=Jt.prototype.endSide=0;Jt.prototype.point=!1;Jt.prototype.mapMode=De.TrackDel;function ma(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}let vo=class Kh{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new Kh(e,t,i)}};function wo(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class ga{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,a=r.length;;){if(o==a)return o;let l=o+a>>1,c=r[l]-e||(i?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);r<o;r++)if(s(this.from[r]+e,this.to[r]+e,this.value[r])===!1)return!1}map(e,t){let i=[],s=[],r=[],o=-1,a=-1;for(let l=0;l<this.value.length;l++){let c=this.value[l],h=this.from[l]+e,u=this.to[l]+e,f,d;if(h==u){let p=t.mapPos(h,c.startSide,c.mapMode);if(p==null||(f=d=p,c.startSide!=c.endSide&&(d=t.mapPos(h,c.endSide),d<f)))continue}else if(f=t.mapPos(h,c.startSide),d=t.mapPos(u,c.endSide),f>d||f==d&&c.startSide>0&&c.endSide<=0)continue;(d-f||c.endSide-c.startSide)<0||(o<0&&(o=f),c.point&&(a=Math.max(a,d-f)),i.push(c),s.push(f-o),r.push(d-o))}return{mapped:i.length?new ga(s,r,i,a):null,pos:o}}}class N{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new N(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(wo)),this.isEmpty)return t.length?N.of(t):this;let a=new Zh(this,null,-1).goto(0),l=0,c=[],h=new Bt;for(;a.value||l<t.length;)if(l<t.length&&(a.from-t[l].from||a.startSide-t[l].value.startSide)>=0){let u=t[l++];h.addInner(u.from,u.to,u.value)||c.push(u)}else a.rangeIndex==1&&a.chunkIndex<this.chunk.length&&(l==t.length||this.chunkEnd(a.chunkIndex)<t[l].from)&&(!o||s>this.chunkEnd(a.chunkIndex)||r<this.chunkPos[a.chunkIndex])&&h.addChunk(this.chunkPos[a.chunkIndex],this.chunk[a.chunkIndex])?a.nextChunk():((!o||s>a.to||r<a.from||o(a.from,a.to,a.value))&&(h.addInner(a.from,a.to,a.value)||c.push(vo.create(a.from,a.to,a.value))),a.next());return h.finishInner(this.nextLayer.isEmpty&&!c.length?N.empty:this.nextLayer.update({add:c,filter:o,filterFrom:s,filterTo:r}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],s=-1;for(let o=0;o<this.chunk.length;o++){let a=this.chunkPos[o],l=this.chunk[o],c=e.touchesRange(a,a+l.length);if(c===!1)s=Math.max(s,l.maxPoint),t.push(l),i.push(e.mapPos(a));else if(c===!0){let{mapped:h,pos:u}=l.map(a,e);h&&(s=Math.max(s,h.maxPoint),t.push(h),i.push(u))}}let r=this.nextLayer.map(e);return t.length==0?r:new N(i,t,r||N.empty,s)}between(e,t,i){if(!this.isEmpty){for(let s=0;s<this.chunk.length;s++){let r=this.chunkPos[s],o=this.chunk[s];if(t>=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return xn.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return xn.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),l=dl(o,a,i),c=new rn(o,l,r),h=new rn(a,l,r);i.iterGaps((u,f,d)=>pl(c,u,h,f,d,s)),i.empty&&i.length==0&&pl(c,0,h,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),o=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let a=dl(r,o),l=new rn(r,a,0).goto(i),c=new rn(o,a,0).goto(i);for(;;){if(l.to!=c.to||!ko(l.active,c.active)||l.point&&(!c.point||!ma(l.point,c.point)))return!1;if(l.to>s)return!0;l.next(),c.next()}}static spans(e,t,i,s,r=-1){let o=new rn(e,null,r).goto(t),a=t,l=o.openStart;for(;;){let c=Math.min(o.to,i);if(o.point){let h=o.activeForPoint(o.to),u=o.pointFrom<t?h.length+1:o.point.startSide<0?h.length:Math.min(h.length,l);s.point(a,c,o.point,h,u,o.pointRank),l=Math.min(o.openEnd(c),h.length)}else c>a&&(s.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>i)return l+(o.point&&o.to>i?1:0);a=o.to,o.next()}}static of(e,t=!1){let i=new Bt;for(let s of e instanceof vo?[e]:t?pp(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return N.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=N.empty;s=s.nextLayer)t=new N(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}}N.empty=new N([],[],null,-1);function pp(n){if(n.length>1)for(let e=n[0],t=1;t<n.length;t++){let i=n[t];if(wo(e,i)>0)return n.slice().sort(wo);e=i}return n}N.empty.nextLayer=N.empty;class Bt{finishChunk(e){this.chunks.push(new ga(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new Bt)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(N.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=N.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function dl(n,e,t){let i=new Map;for(let r of n)for(let o=0;o<r.chunk.length;o++)r.chunk[o].maxPoint<=0&&i.set(r.chunk[o],r.chunkPos[o]);let s=new Set;for(let r of e)for(let o=0;o<r.chunk.length;o++){let a=i.get(r.chunk[o]);a!=null&&(t?t.mapPos(a):a)==r.chunkPos[o]&&!t?.touchesRange(a,a+r.chunk[o].length)&&s.add(r.chunk[o])}return s}class Zh{constructor(e,t,i,s=0){this.layer=e,this.skip=t,this.minPoint=i,this.rank=s}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,i){for(;this.chunkIndex<this.layer.chunk.length;){let s=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(s)||this.layer.chunkEnd(this.chunkIndex)<e||s.maxPoint<this.minPoint))break;this.chunkIndex++,i=!1}if(this.chunkIndex<this.layer.chunk.length){let s=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!i||this.rangeIndex<s)&&this.setRangeIndex(s)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],i=e+t.from[this.rangeIndex];if(this.from=i,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}}class xn{constructor(e){this.heap=e}static from(e,t=null,i=-1){let s=[];for(let r=0;r<e.length;r++)for(let o=e[r];!o.isEmpty;o=o.nextLayer)o.maxPoint>=i&&s.push(new Zh(o,t,i,r));return s.length==1?s[0]:new xn(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Rr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Rr(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Rr(this.heap,0)}}}function Rr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1<n.length&&s.compare(n[i+1])>=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}class rn{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=xn.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){jn(this.active,e),jn(this.activeTo,e),jn(this.activeRank,e),this.minActive=ml(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t<this.activeRank.length&&(r-this.activeRank[t]||s-this.activeTo[t])>0;)t++;Yn(this.active,t,i),Yn(this.activeTo,t,s),Yn(this.activeRank,t,r),e&&Yn(e,t,this.cursor.from),this.minActive=ml(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&jn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=r,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=r.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(i){this.openStart=0;for(let s=i.length-1;s>=0&&i[s]<e;s--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let i=this.active.length-1;i>=0&&!(this.activeRank[i]<this.pointRank);i--)(this.activeTo[i]>e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function pl(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,a=i,l=i-e,c=!!r.boundChange;for(let h=!1;;){let u=n.to+l-t.to,f=u||n.endSide-t.endSide,d=f<0?n.to+l:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&ma(n.point,t.point)&&ko(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(a,p,n.point,t.point),h=!1):(h&&r.boundChange(a),p>a&&!ko(n.active,t.active)&&r.compareRange(a,p,n.active,t.active),c&&p<o&&(u||n.openEnd(d)!=t.openEnd(d))&&(h=!0)),d>o)break;a=d,f<=0&&n.next(),f>=0&&t.next()}}function ko(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!=e[t]&&!ma(n[t],e[t]))return!1;return!0}function jn(n,e){for(let t=e,i=n.length-1;t<i;t++)n[t]=n[t+1];n.pop()}function Yn(n,e,t){for(let i=n.length-1;i>=e;i--)n[i+1]=n[i];n[e]=t}function ml(n,e){let t=-1,i=1e9;for(let s=0;s<e.length;s++)(e[s]-i||n[s].endSide-n[t].endSide)<0&&(t=s,i=e[s]);return t}function _i(n,e,t=n.length){let i=0;for(let s=0;s<t&&s<n.length;)n.charCodeAt(s)==9?(i+=e-i%e,s++):(i++,s=Ze(n,s));return i}function Qo(n,e,t,i){for(let s=0,r=0;;){if(r>=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=Ze(n,s)}return i===!0?-1:n.length}const Po="ͼ",gl=typeof Symbol>"u"?"__"+Po:Symbol.for(Po),Co=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Ol=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class ei{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,a,l,c){let h=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let d in a){let p=a[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,l);else if(p&&typeof p=="object"){if(!u)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,h,f)}else p!=null&&h.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(h.length||f)&&l.push((i&&!u&&!c?o.map(i):o).join(", ")+" {"+h.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` -`)}static newName(){let e=Ol[gl]||1;return Ol[gl]=e+1,Po+e.toString(36)}static mount(e,t,i){let s=e[Co],r=i&&i.nonce;s?r&&s.setNonce(r):s=new mp(e,r),s.mount(Array.isArray(t)?t:[t],e)}}let yl=new Map;class mp{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=yl.get(i);if(r)return e[Co]=r;this.sheet=new s.CSSStyleSheet,yl.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Co]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o<e.length;o++){let a=e[o],l=this.modules.indexOf(a);if(l<r&&l>-1&&(this.modules.splice(l,1),r--,l=-1),l==-1){if(this.modules.splice(r++,0,a),i)for(let c=0;c<a.rules.length;c++)i.insertRule(a.rules[c],s++)}else{for(;r<l;)s+=this.modules[r++].rules.length;s+=a.rules.length,r++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let o="";for(let l=0;l<this.modules.length;l++)o+=this.modules[l].getRules()+` -`;this.styleTag.textContent=o;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}}var ti={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",229:"q"},vn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"',229:"Q"},Al=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),gp=typeof navigator<"u"&&/Apple Computer/.test(navigator.vendor),Op=typeof navigator<"u"&&/Gecko\/\d+/.test(navigator.userAgent),bl=typeof navigator<"u"&&/Mac/.test(navigator.platform),yp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Ap=Al&&(bl||+Al[1]<57)||Op&&bl;for(var Fe=0;Fe<10;Fe++)ti[48+Fe]=ti[96+Fe]=String(Fe);for(var Fe=1;Fe<=24;Fe++)ti[Fe+111]="F"+Fe;for(var Fe=65;Fe<=90;Fe++)ti[Fe]=String.fromCharCode(Fe+32),vn[Fe]=String.fromCharCode(Fe);for(var $r in ti)vn.hasOwnProperty($r)||(vn[$r]=ti[$r]);function bp(n){var e=Ap&&(n.ctrlKey||n.altKey||n.metaKey)||(gp||yp)&&n.shiftKey&&n.key&&n.key.length==1,t=!e&&n.key||(n.shiftKey?vn:ti)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function he(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e<arguments.length;e++)Mh(n,arguments[e]);return n}function Mh(n,e){if(typeof e=="string")n.appendChild(document.createTextNode(e));else if(e!=null)if(e.nodeType!=null)n.appendChild(e);else if(Array.isArray(e))for(var t=0;t<e.length;t++)Mh(n,e[t]);else throw new RangeError("Unsupported child node: "+e)}let qe=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},To=typeof document<"u"?document:{documentElement:{style:{}}};const Ro=/Edge\/(\d+)/.exec(qe.userAgent),Eh=/MSIE \d/.test(qe.userAgent),$o=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(qe.userAgent),hr=!!(Eh||$o||Ro),Sl=!hr&&/gecko\/(\d+)/i.test(qe.userAgent),Kr=!hr&&/Chrome\/(\d+)/.exec(qe.userAgent),xl="webkitFontSmoothing"in To.documentElement.style,Ko=!hr&&/Apple Computer/.test(qe.vendor),vl=Ko&&(/Mobile\/\w+/.test(qe.userAgent)||qe.maxTouchPoints>2);var R={mac:vl||/Mac/.test(qe.platform),windows:/Win/.test(qe.platform),linux:/Linux|X11/.test(qe.platform),ie:hr,ie_version:Eh?To.documentMode||6:$o?+$o[1]:Ro?+Ro[1]:0,gecko:Sl,gecko_version:Sl?+(/Firefox\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,chrome:!!Kr,chrome_version:Kr?+Kr[1]:0,ios:vl,android:/Android\b/.test(qe.userAgent),webkit:xl,webkit_version:xl?+(/\bAppleWebKit\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,safari:Ko,safari_version:Ko?+(/\bVersion\/(\d+(\.\d+)?)/.exec(qe.userAgent)||[0,0])[1]:0,tabSize:To.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Oa(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}const Ts=Object.create(null);function ya(n,e,t){if(n==e)return!0;n||(n=Ts),e||(e=Ts);let i=Object.keys(n),s=Object.keys(e);if(i.length-0!=s.length-0)return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function Sp(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function wl(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function xp(n){let e=Object.create(null);for(let t=0;t<n.attributes.length;t++){let i=n.attributes[t];e[i.name]=i.value}return e}class Ut{eq(e){return!1}updateDOM(e,t,i){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,i){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}}var Le=(function(n){return n[n.Text=0]="Text",n[n.WidgetBefore=1]="WidgetBefore",n[n.WidgetAfter=2]="WidgetAfter",n[n.WidgetRange=3]="WidgetRange",n})(Le||(Le={}));class B extends Jt{constructor(e,t,i,s){super(),this.startSide=e,this.endSide=t,this.widget=i,this.spec=s}get heightRelevant(){return!1}static mark(e){return new Un(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),i=!!e.block;return t+=i&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new Ai(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Uh(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Ai(e,i,s,t,e.widget||null,!0)}static line(e){return new Fn(e)}static set(e,t=!1){return N.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}B.none=N.empty;class Un extends B{constructor(e){let{start:t,end:i}=Uh(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Oa(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||Ts}eq(e){return this==e||e instanceof Un&&this.tagName==e.tagName&&ya(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Un.prototype.point=!1;class Fn extends B{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Fn&&this.spec.class==e.spec.class&&ya(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Fn.prototype.mapMode=De.TrackBefore;Fn.prototype.point=!0;class Ai extends B{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?De.TrackBefore:De.TrackAfter:De.TrackDel}get type(){return this.startSide!=this.endSide?Le.WidgetRange:this.startSide<=0?Le.WidgetBefore:Le.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof Ai&&vp(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Ai.prototype.point=!0;function Uh(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function vp(n,e){return n==e||!!(n&&e&&n.compare(e))}function Mi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}class wn extends Jt{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof wn&&this.tagName==e.tagName&&ya(this.attributes,e.attributes)}static create(e){return new wn(e.tagName,e.attributes||Ts,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return N.of(e,t)}}wn.prototype.startSide=wn.prototype.endSide=-1;function kn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Zo(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function gn(n,e){if(!e.anchorNode)return!1;try{return Zo(n,e.anchorNode)}catch{return!1}}function ys(n){return n.nodeType==3?Qn(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function On(n,e,t,i){return t?kl(n,e,t,i,-1)||kl(n,e,t,i,1):!1}function ii(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Rs(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function kl(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:It(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=ii(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?It(n):0}else return!1}}function It(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function $s(n,e){let{left:t,right:i}=n;if(t==i)return n;let s=e?t:i;return{left:s,right:s,top:n.top,bottom:n.bottom}}function wp(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Fh(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function kp(n,e,t,i,s,r,o,a){let l=n.ownerDocument,c=l.defaultView||window;for(let h=n,u=!1;h&&!u;)if(h.nodeType==1){let f,d=h==l.body,p=1,m=1;if(d)f=wp(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(h).position)&&(u=!0),h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let b=h.getBoundingClientRect();({scaleX:p,scaleY:m}=Fh(h,b)),f={left:b.left,right:b.left+h.clientWidth*p,top:b.top,bottom:b.top+h.clientHeight*m}}let g=0,y=0;if(s=="nearest")e.top<f.top+o?(y=e.top-(f.top+o),t>0&&e.bottom>f.bottom+y&&(y=e.bottom-f.bottom+o)):e.bottom>f.bottom-o&&(y=e.bottom-f.bottom+o,t<0&&e.top-y<f.top&&(y=e.top-(f.top+o)));else{let b=e.bottom-e.top,x=f.bottom-f.top;y=(s=="center"&&b<=x?e.top+b/2-x/2:s=="start"||s=="center"&&t<0?e.top-o:e.bottom-x+o)-f.top}if(i=="nearest"?e.left<f.left+r?(g=e.left-(f.left+r),t>0&&e.right>f.right+g&&(g=e.right-f.right+r)):e.right>f.right-r&&(g=e.right-f.right+r,t<0&&e.left<f.left+g&&(g=e.left-(f.left+r))):g=(i=="center"?e.left+(e.right-e.left)/2-(f.right-f.left)/2:i=="start"==a?e.left-r:e.right-(f.right-f.left)+r)-f.left,g||y)if(d)c.scrollBy(g,y);else{let b=0,x=0;if(y){let C=h.scrollTop;h.scrollTop+=y/m,x=(h.scrollTop-C)*m}if(g){let C=h.scrollLeft;h.scrollLeft+=g/p,b=(h.scrollLeft-C)*p}e={left:e.left-b,top:e.top-x,right:e.right-b,bottom:e.bottom-x},b&&Math.abs(b-g)<1&&(i="nearest"),x&&Math.abs(x-y)<1&&(s="nearest")}if(d)break;(e.top<f.top||e.bottom>f.bottom||e.left<f.left||e.right>f.right)&&(e={left:Math.max(e.left,f.left),right:Math.min(e.right,f.right),top:Math.max(e.top,f.top),bottom:Math.min(e.bottom,f.bottom)}),h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function Dh(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}class Qp{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?It(t):0),i,Math.min(e.focusOffset,i?It(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}}function Lh(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function Xh(n,e=!0){for(let{node:t,left:i,top:s}of n)e&&t.scrollTop!=s&&(t.scrollTop=s),t.scrollLeft!=i&&(t.scrollLeft=i)}let ui=null;R.safari&&R.safari_version>=26&&(ui=!1);function Bh(n){if(n.setActive)return n.setActive();if(ui)return n.focus(ui);let e=Lh(n);n.focus(ui==null?{get preventScroll(){return ui={preventScroll:!0},!0}}:void 0),ui||(ui=!1,Xh(e))}let Ql;function Qn(n,e,t=e){let i=Ql||(Ql=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function Ei(n,e,t,i){let s={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=i);let r=new KeyboardEvent("keydown",s);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function Pp(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function Cp(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,It(t));;)if(i){if(t.nodeType!=1)return!1;let s=t.childNodes[i-1];s.contentEditable=="false"?i--:(t=s,i=It(t))}else{if(t==n)return!0;i=ii(t),t=t.parentNode}}function Ih(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function Wh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=It(t)}else if(t.parentNode&&!Rs(t))i=ii(t),t=t.parentNode;else return null}}function qh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i<t.nodeValue.length)return{node:t,offset:i};if(t.nodeType==1&&i<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[i],i=0}else if(t.parentNode&&!Rs(t))i=ii(t)+1,t=t.parentNode;else return null}}class pt{constructor(e,t,i=!0){this.node=e,this.offset=t,this.precise=i}static before(e,t){return new pt(e.parentNode,ii(e),t)}static after(e,t){return new pt(e.parentNode,ii(e)+1,t)}}var fe=(function(n){return n[n.LTR=0]="LTR",n[n.RTL=1]="RTL",n})(fe||(fe={}));const bi=fe.LTR,Aa=fe.RTL;function zh(n){let e=[];for(let t=0;t<n.length;t++)e.push(1<<+n[t]);return e}const Tp=zh("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),Rp=zh("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),Mo=Object.create(null),St=[];for(let n of["()","[]","{}"]){let e=n.charCodeAt(0),t=n.charCodeAt(1);Mo[e]=t,Mo[t]=-e}function Vh(n){return n<=247?Tp[n]:1424<=n&&n<=1524?2:1536<=n&&n<=1785?Rp[n-1536]:1774<=n&&n<=2220?4:8192<=n&&n<=8204?256:64336<=n&&n<=65023?4:1}const $p=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;class Ct{get dir(){return this.level%2?Aa:bi}constructor(e,t,i){this.from=e,this.to=t,this.level=i}side(e,t){return this.dir==t==e?this.to:this.from}forward(e,t){return e==(this.dir==t)}static find(e,t,i,s){let r=-1;for(let o=0;o<e.length;o++){let a=e[o];if(a.from<=t&&a.to>=t){if(a.level==i)return o;(r<0||(s!=0?s<0?a.from<t:a.to>t:e[r].level>a.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}function jh(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++){let i=n[t],s=e[t];if(i.from!=s.from||i.to!=s.to||i.direction!=s.direction||!jh(i.inner,s.inner))return!1}return!0}const ue=[];function Kp(n,e,t,i,s){for(let r=0;r<=i.length;r++){let o=r?i[r-1].to:e,a=r<i.length?i[r].from:t,l=r?256:s;for(let c=o,h=l,u=l;c<a;c++){let f=Vh(n.charCodeAt(c));f==512?f=h:f==8&&u==4&&(f=16),ue[c]=f==4?2:f,f&7&&(u=f),h=f}for(let c=o,h=l,u=l;c<a;c++){let f=ue[c];if(f==128)c<a-1&&h==ue[c+1]&&h&24?f=ue[c]=h:ue[c]=256;else if(f==64){let d=c+1;for(;d<a&&ue[d]==64;)d++;let p=c&&h==8||d<t&&ue[d]==8?u==1?1:8:256;for(let m=c;m<d;m++)ue[m]=p;c=d-1}else f==8&&u==1&&(ue[c]=1);h=f,f&7&&(u=f)}}}function Zp(n,e,t,i,s){let r=s==1?2:1;for(let o=0,a=0,l=0;o<=i.length;o++){let c=o?i[o-1].to:e,h=o<i.length?i[o].from:t;for(let u=c,f,d,p;u<h;u++)if(d=Mo[f=n.charCodeAt(u)])if(d<0){for(let m=a-3;m>=0;m-=3)if(St[m+1]==-d){let g=St[m+2],y=g&2?s:g&4?g&1?r:s:0;y&&(ue[u]=ue[St[m]]=y),a=m;break}}else{if(St.length==189)break;St[a++]=u,St[a++]=f,St[a++]=l}else if((p=ue[u])==2||p==1){let m=p==s;l=m?0:1;for(let g=a-3;g>=0;g-=3){let y=St[g+2];if(y&2)break;if(m)St[g+2]|=2;else{if(y&4)break;St[g+2]|=4}}}}}function Mp(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,a=s<t.length?t[s].from:e;for(let l=o;l<a;){let c=ue[l];if(c==256){let h=l+1;for(;;)if(h==a){if(s==t.length)break;h=t[s++].to,a=s<t.length?t[s].from:e}else if(ue[h]==256)h++;else break;let u=r==1,f=(h<e?ue[h]:i)==1,d=u==f?u?1:2:i;for(let p=h,m=s,g=m?t[m-1].to:n;p>l;)p==g&&(p=t[--m].from,g=m?t[m-1].to:n),ue[--p]=d;l=h}else r=c,l++}}}function Eo(n,e,t,i,s,r,o){let a=i%2?2:1;if(i%2==s%2)for(let l=e,c=0;l<t;){let h=!0,u=!1;if(c==r.length||l<r[c].from){let m=ue[l];m!=a&&(h=!1,u=m==16)}let f=!h&&a==1?[]:null,d=h?i:i+1,p=l;e:for(;;)if(c<r.length&&p==r[c].from){if(u)break e;let m=r[c];if(!h)for(let g=m.to,y=c+1;;){if(g==t)break e;if(y<r.length&&r[y].from==g)g=r[y++].to;else{if(ue[g]==a)break e;break}}if(c++,f)f.push(m);else{m.from>l&&o.push(new Ct(l,m.from,d));let g=m.direction==bi!=!(d%2);Uo(n,g?i+1:i,s,m.inner,m.from,m.to,o),l=m.to}p=m.to}else{if(p==t||(h?ue[p]!=a:ue[p]==a))break;p++}f?Eo(n,l,p,i+1,s,f,o):l<p&&o.push(new Ct(l,p,d)),l=p}else for(let l=t,c=r.length;l>e;){let h=!0,u=!1;if(!c||l>r[c-1].to){let m=ue[l-1];m!=a&&(h=!1,u=m==16)}let f=!h&&a==1?[]:null,d=h?i:i+1,p=l;e:for(;;)if(c&&p==r[c-1].to){if(u)break e;let m=r[--c];if(!h)for(let g=m.from,y=c;;){if(g==e)break e;if(y&&r[y-1].to==g)g=r[--y].from;else{if(ue[g-1]==a)break e;break}}if(f)f.push(m);else{m.to<l&&o.push(new Ct(m.to,l,d));let g=m.direction==bi!=!(d%2);Uo(n,g?i+1:i,s,m.inner,m.from,m.to,o),l=m.from}p=m.from}else{if(p==e||(h?ue[p-1]!=a:ue[p-1]==a))break;p--}f?Eo(n,p,l,i+1,s,f,o):p<l&&o.push(new Ct(p,l,d)),l=p}}function Uo(n,e,t,i,s,r,o){let a=e%2?2:1;Kp(n,s,r,i,a),Zp(n,s,r,i,a),Mp(s,r,i,a),Eo(n,s,r,e,t,i,o)}function Ep(n,e,t){if(!n)return[new Ct(0,0,e==Aa?1:0)];if(e==bi&&!t.length&&!$p.test(n))return Yh(n.length);if(t.length)for(;n.length>ue.length;)ue[ue.length]=256;let i=[],s=e==bi?0:1;return Uo(n,s,s,t,0,n.length,i),i}function Yh(n){return[new Ct(0,n,0)]}let Nh="";function Up(n,e,t,i,s){var r;let o=i.head-n.from,a=Ct.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),l=e[a],c=l.side(s,t);if(o==c){let f=a+=s?1:-1;if(f<0||f>=e.length)return null;l=e[a=f],o=l.side(!s,t),c=l.side(s,t)}let h=Ze(n.text,o,l.forward(s,t));(h<l.from||h>l.to)&&(h=c),Nh=n.text.slice(Math.min(o,h),Math.max(o,h));let u=a==(s?e.length-1:0)?null:e[a+(s?1:-1)];return u&&h==c&&u.level+(s?0:1)<l.level?A.cursor(u.side(!s,t)+n.from,u.forward(s,t)?1:-1,u.level):A.cursor(h+n.from,l.forward(s,t)?-1:1,l.level)}function Fp(n,e,t){for(let i=e;i<t;i++){let s=Vh(n.charCodeAt(i));if(s==1)return bi;if(s==2||s==4)return Aa}return bi}const Hh=K.define(),Gh=K.define(),_h=K.define(),Jh=K.define(),Fo=K.define(),eu=K.define(),tu=K.define(),ba=K.define(),Sa=K.define(),iu=K.define({combine:n=>n.some(e=>e)}),nu=K.define({combine:n=>n.some(e=>e)}),su=K.define();class Ui{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new Ui(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Ui(A.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Nn=z.define({map:(n,e)=>n.map(e)}),ru=z.define();function ze(n,e,t){let i=n.facet(Jh);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const Dt=K.define({combine:n=>n.length?n[0]:!0});let Dp=0;const Ti=K.define({combine(n){return n.filter((e,t)=>{for(let i=0;i<t;i++)if(n[i].plugin==e.plugin)return!1;return!0})}});class xe{constructor(e,t,i,s,r){this.id=e,this.create=t,this.domEventHandlers=i,this.domEventObservers=s,this.baseExtensions=r(this),this.extension=this.baseExtensions.concat(Ti.of({plugin:this,arg:void 0}))}of(e){return this.baseExtensions.concat(Ti.of({plugin:this,arg:e}))}static define(e,t){const{eventHandlers:i,eventObservers:s,provide:r,decorations:o}=t||{};return new xe(Dp++,e,i,s,a=>{let l=[];return o&&l.push(ur.of(c=>{let h=c.plugin(a);return h?o(h):B.none})),r&&l.push(r(a)),l})}static fromClass(e,t){return xe.define((i,s)=>new e(i,s),t)}}class Zr{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ze(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ze(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ze(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const ou=K.define(),xa=K.define(),ur=K.define(),au=K.define(),va=K.define(),Dn=K.define(),lu=K.define();function Pl(n,e){let t=n.state.facet(lu);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return N.spans(i,e.from,e.to,{point(){},span(r,o,a,l){let c=r-e.from,h=o-e.from,u=s;for(let f=a.length-1;f>=0;f--,l--){let d=a[f].spec.bidiIsolate,p;if(d==null&&(d=Fp(e.text,c,h)),l>0&&u.length&&(p=u[u.length-1]).to==c&&p.direction==d)p.to=h,u=p.inner;else{let m={from:c,to:h,direction:d,inner:[]};u.push(m),u=m.inner}}}}),s}const cu=K.define();function wa(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(cu)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}const hn=K.define();class ct{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new ct(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toA<i.fromA)break;i=i.join(s),e.splice(t-1,1)}}return e.splice(t,0,i),e}static extendWithRanges(e,t){if(t.length==0)return e;let i=[];for(let s=0,r=0,o=0;;){let a=s<e.length?e[s].fromB:1e9,l=r<t.length?t[r]:1e9,c=Math.min(a,l);if(c==1e9)break;let h=c+o,u=c,f=h;for(;;)if(r<t.length&&t[r]<=u){let d=t[r+1];r+=2,u=Math.max(u,d);for(let p=s;p<e.length&&e[p].fromB<=u;p++)o=e[p].toA-e[p].toB;f=Math.max(f,d+o)}else if(s<e.length&&e[s].fromB<=u){let d=e[s++];u=Math.max(u,d.toB),f=Math.max(f,d.toA),o=d.toA-d.toB}else break;i.push(new ct(h,f,c,u))}return i}}class Ks{constructor(e,t,i){this.view=e,this.state=t,this.transactions=i,this.flags=0,this.startState=e.state,this.changes=Re.empty(this.startState.doc.length);for(let r of i)this.changes=this.changes.compose(r.changes);let s=[];this.changes.iterChangedRanges((r,o,a,l)=>s.push(new ct(r,o,a,l))),this.changedRanges=s}static create(e,t,i){return new Ks(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const Lp=[];class Se{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Lp}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Sp(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=ii(this.dom),s=this.length?e>0:t>0;return new pt(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof dr)return e;return null}static get(e){return e.cmTile}}class fr extends Se{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=a.dom&&(r.written=!0),a.dom.parentNode==t)for(;s&&s!=a.dom;)s=Cl(s);else t.insertBefore(a.dom,s);i=a.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=Cl(s);this.length=o}}function Cl(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class dr extends fr{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Se.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof Lt)t.push(s),i=o,s=0;else{let a=r+o.length,l=e(o,r);if(l!==void 0)return l;r=a+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&t>=-1&&t<=1){if(a.flags&32)return!0;a.flags&16&&(i=void 0)}(l<e||e==c&&(t<-1?a.length:a.covers(1)))&&(!i||!a.isWidget()&&i.isWidget())&&(i=a,s=e-l),(c>e||e==l&&(t>1?a.length:a.covers(-1)))&&(!r||!a.isWidget()&&r.isWidget())&&(r=a,o=e-l)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}}class Lt extends fr{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new Lt(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class Ii extends fr{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new Ii(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,a=-1;function l(h,u){for(let f=0,d=0;f<h.children.length&&d<=u;f++){let p=h.children[f],m=d+p.length;m>=u&&(p.isComposite()?l(p,u-d):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Bp(o,p)))&&(m>u||p.flags&32&&t<=1)?(o=p,a=u-d):(d<u||p.flags&16&&!p.isHidden&&t>=-1)&&(s=p,r=u-d)),d=m}}l(this,e);let c=(t<0?s:o)||s||o;return c?{tile:c,offset:c==s?r:a}:null}coordsIn(e,t,i){let s=this.resolveInline(e,t,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),t,i):Xp(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:s,offset:r}=i;if(this.dom.contains(s.dom))return s.isText()?new pt(s.dom,Math.min(s.dom.nodeValue.length,r)):s.domPosFor(r,s.flags&16?1:s.flags&32?-1:t);let o=i.tile.parent,a=!1;for(let l of o.children){if(a)return new pt(l.dom,0);l==i.tile&&(a=!0)}}return new pt(this.dom,0)}}function Xp(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=ys(e);return t[t.length-1]||null}function Bp(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.top<t.bottom}class Ge extends fr{constructor(e,t){super(e),this.mark=t}get domAttrs(){return this.mark.attrs}static of(e,t){let i=new Ge(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class pi extends Se{constructor(e,t){super(e,t.length),this.text=t}sync(e){this.flags&2||(super.sync(e),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text))}isText(){return!0}toString(){return JSON.stringify(this.text)}coordsIn(e,t,i){let s=this.dom.nodeValue.length;e>s&&(e=s);let r=e,o=e,a=0;e==0&&t<0||e==s&&t>=0?R.chrome||R.gecko||(e?(r--,a=1):o<s&&(o++,a=-1)):t<0?r--:o<s&&o++;let l=Qn(this.dom,r,o).getClientRects();if(!l.length)return null;let c=l[(a?a<0:t>=0)?0:l.length-1];return R.safari&&!a&&c.width==0&&(c=Array.prototype.find.call(l,h=>h.width)||c),i==null?c:$s(c,(a?a>0:t<0)==i)}static of(e,t){let i=new pi(t||document.createTextNode(e),e);return t||(i.flags|=2),i}}class Si extends Se{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return $s(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?r.length-1:0;o=r[l],!(e>0?l==0:l==r.length-1||o.top<o.bottom);l+=a?-1:1);return $s(o,!a)}}get overrideDOMText(){if(!this.length)return se.empty;let{root:e}=this;if(!e)return se.empty;let t=this.posAtStart;return e.view.state.doc.slice(t,t+this.length)}destroy(){super.destroy(),this.widget.destroy(this.dom)}static of(e,t,i,s,r){return r||(r=e.toDOM(t),e.editable||(r.contentEditable="false")),new Si(r,i,e,s)}}class Zs extends Se{constructor(e){let t=document.createElement("img");t.className="cm-widgetBuffer",t.setAttribute("aria-hidden","true"),super(t,0,e)}get isHidden(){return!0}get overrideDOMText(){return se.empty}coordsIn(e,t,i){let s=this.dom.getBoundingClientRect();return i==null?s:$s(s,t>0==i)}}class Ip{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:s,index:r,beforeBreak:o,parents:a}=this;for(;e||t>0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!a.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=a.pop(),r++}else{let l=s.children[r],c=l.breakAfter;(t>0?l.length<=e:l.length<e)&&(!i||i.skip(l,0,l.length)!==!1||!l.isComposite)?(o=!!c,r++,e-=l.length):(a.push({tile:s,index:r}),s=l,r=0,i&&l.isComposite()&&i.enter(l))}else{let l=s.length;if(r<l&&e){let c=Math.min(e,l-r);i&&i.skip(s,r,r+c),e-=c,r+=c}if(r==l)o=!!s.breakAfter,{tile:s,index:r}=a.pop(),r++;else if(!e)break}return this.tile=s,this.index=r,this.beforeBreak=o,this}get root(){return this.parents.length?this.parents[0].tile:this.tile}}class Wp{constructor(e,t,i,s){this.from=e,this.to=t,this.wrapper=i,this.rank=s}}class qp{constructor(e,t,i){this.cache=e,this.root=t,this.blockWrappers=i,this.curLine=null,this.lastBlock=null,this.afterWidget=null,this.pos=0,this.wrappers=[],this.wrapperPos=0}addText(e,t,i,s){var r;this.flushBuffer();let o=this.ensureMarks(t,i),a=o.lastChild;if(a&&a.isText()&&!(a.flags&8)&&a.length+e.length<512){this.cache.reused.set(a,2);let l=o.children[o.children.length-1]=new pi(a.dom,a.text+e);l.parent=o}else o.append(s||pi.of(e,(r=this.cache.find(pi))===null||r===void 0?void 0:r.dom));this.pos+=e.length,this.afterWidget=null}addComposition(e,t){let i=this.curLine;i.dom!=t.line.dom&&(i.setDOM(this.cache.reused.has(t.line)?Mr(t.line.dom):t.line.dom),this.cache.reused.set(t.line,2));let s=i;for(let a=t.marks.length-1;a>=0;a--){let l=t.marks[a],c=s.lastChild;if(c instanceof Ge&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(Mr(l.dom)),s=c;else{if(this.cache.reused.get(l)){let u=Se.get(l.dom);u&&u.setDOM(Mr(l.dom))}let h=Ge.of(l.mark,l.dom);s.append(h),s=h}this.cache.reused.set(l,2)}let r=Se.get(e.text);r&&this.cache.reused.set(r,2);let o=new pi(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=hu);let s=Ii.start(e,t||((i=this.cache.find(Ii))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],a;if(t>0&&(a=s.lastChild)&&a instanceof Ge&&a.mark.eq(o))s=a,t--;else{let l=Ge.of(o,(i=this.cache.find(Ge,c=>c.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(l),s=l,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Tl(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(R.ios&&Tl(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Er,0,32)||new Si(Er.toDOM(),0,Er,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to<this.pos&&this.wrappers.splice(e,1);for(let e=this.blockWrappers;e.value&&e.from<=this.pos;e.next())if(e.to>=this.pos){let t=e.rank*102+e.value.rank,i=new Wp(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.from<this.pos&&s instanceof Lt&&s.wrapper.eq(i.wrapper))t=s;else{let r=Lt.of(i.wrapper,(e=this.cache.find(Lt,o=>o.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(Zs,void 0,1);return i&&(i.flags=t),i||new Zs(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class zp{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let a=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,a)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}}const Ms=[Si,Ii,pi,Ge,Zs,Lt,dr];for(let n=0;n<Ms.length;n++)Ms[n].bucket=n;class Vp{constructor(e){this.view=e,this.buckets=Ms.map(()=>[]),this.index=Ms.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let a=0;a<r.length;a++){let l=(a+o)%r.length,c=r[l];if((!t||t(c))&&!this.reused.has(c))return r.splice(l,1),l<o&&this.index[s]--,this.reused.set(c,i),c}return null}findWidget(e,t,i){let s=this.buckets[0];if(s.length)for(let r=0,o=0;;r++){if(r==s.length){if(o)return null;o=1,r=0}let a=s[r];if(!this.reused.has(a)&&(o==0?a.widget.compare(e):a.widget.constructor==e.constructor&&e.updateDOM(a.dom,this.view,a.widget)))return s.splice(r,1),r<this.index[0]&&this.index[0]--,a.widget==e&&a.length==t&&(a.flags&497)==i?(this.reused.set(a,1),a):(this.reused.set(a,2),new Si(a.dom,t,e,a.flags&-498|i))}}reuse(e){return this.reused.set(e,1),e}maybeReuse(e,t=2){if(!this.reused.has(e))return this.reused.set(e,t),e.dom}clear(){for(let e=0;e<this.buckets.length;e++)this.buckets[e].length=this.index[e]=0}}class jp{constructor(e,t,i,s,r){this.view=e,this.decorations=s,this.disallowBlockEffectsFor=r,this.openWidget=!1,this.openMarks=0,this.cache=new Vp(e),this.text=new zp(e.state.doc),this.builder=new qp(this.cache,new dr(e,e.contentDOM),N.iter(i)),this.cache.reused.set(t,2),this.old=new Ip(t),this.reuseWalker={skip:(o,a,l)=>{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let a=o<e.length?e[o++]:null,l=a?a.fromA:this.old.root.length;if(l>s){let c=l-s;this.preserve(c,!o,!a),s=l,r+=c}if(!a)break;t&&a.fromA<=t.range.fromA&&a.toA>=t.range.toA?(this.forward(a.fromA,t.range.fromA,t.range.fromA<t.range.toA?1:-1),this.emit(r,t.range.fromB),this.builder.flushBuffer(),this.cache.clear(),this.builder.addComposition(t,i),this.text.skip(t.range.toB-t.range.fromB),this.forward(t.range.fromA,a.toA),this.emit(t.range.toB,a.toB)):(this.forward(a.fromA,a.toA),this.emit(r,a.toB)),r=a.toB,s=a.toA}return this.builder.curLine&&this.builder.endLine(),this.builder.root}preserve(e,t,i){let s=Hp(this.old),r=this.openMarks;this.old.advance(e,i?1:-1,{skip:(o,a,l)=>{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a<o.length?Si.of(o.widget,this.view,l-a,o.flags&496,this.cache.maybeReuse(o)):this.cache.reuse(o);c.flags&256?(c.flags&=-2,this.builder.addBlockWidget(c)):(this.builder.ensureLine(null),this.builder.addInlineWidget(c,s,r),r=s.length)}else if(o.isText())this.builder.ensureLine(null),!a&&l==o.length&&!this.cache.reused.has(o)?this.builder.addText(o.text,s,r,this.cache.reuse(o)):(this.cache.add(o),this.builder.addText(o.text.slice(a,l),s,r)),r=s.length;else if(o.isLine())o.flags&=-2,this.cache.reused.set(o,1),this.builder.addLine(o);else if(o instanceof Zs)this.cache.add(o);else if(o instanceof Ge)this.builder.ensureLine(null),this.builder.addMark(o,s,r),this.cache.reused.set(o,1),r=s.length;else return!1;this.openWidget=!1},enter:o=>{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Ge&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof Ge&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=-1,o=N.spans(this.decorations,e,t,{point:(a,l,c,h,u,f)=>{if(c instanceof Ai){if(this.disallowBlockEffectsFor[f]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=h.length,u>h.length)s.continueWidget(l-a);else{let d=c.widget||(c.block?Wi.block:Wi.inline),p=Yp(c),m=this.cache.findWidget(d,l-a,p)||Si.of(d,this.view,l-a,p);c.block?(c.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,h,u))}i=null}else i=Np(i,c);l>a&&this.text.skip(l-a)},span:(a,l,c,h)=>{for(let u=a;u<l;){let f=this.text.next(Math.min(512,l-u));f==null?(s.addLineStartIfNotCovered(i),s.addBreak(),u++):(s.ensureLine(i),s.addText(f,c,u==a?h:c.length),u+=f.length),i=null}r=c.length}});r>-1&&(this.openWidget=o>r),this.openWidget||s.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=Se.get(s);if(s==this.view.contentDOM)break;r instanceof Ge?t.push(r):r?.isLine()?i=r:r instanceof Lt||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new Ii(s,hu):i||t.push(Ge.of(new Un({tagName:s.nodeName.toLowerCase(),attributes:xp(s)}),s)))}return{line:i,marks:t}}}function Tl(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Yp(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}const hu={class:"cm-line"};function Np(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Oa(t,n),i&&(n.class+=" "+i)),n}function Hp(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof Ge&&e.push(i.mark)}return e}function Mr(n){let e=Se.get(n);return e&&e.setDOM(n.cloneNode()),n}class Wi extends Ut{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}Wi.inline=new Wi("span");Wi.block=new Wi("div");const Er=new class extends Ut{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class Rl{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=B.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new dr(e,e.contentDOM),this.updateInner([new ct(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:h,toA:u})=>u<this.minWidthFrom||h>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!rm(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?_p(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:h,to:u}=this.hasComposition;i=new ct(h,u,e.changes.mapPos(h,-1),e.changes.mapPos(u,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(R.ie||R.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=tm(o,this.decorations,e.changes);l.length&&(i=ct.extendWithRanges(i,l));let c=nm(a,this.blockWrappers,e.changes);return c.length&&(i=ct.extendWithRanges(i,c)),r&&!i.some(h=>h.fromA<=r.range.fromA&&h.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,a=new jp(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Se.get(t.text)&&a.cache.reused.set(Se.get(t.text),2),this.tile=a.run(e,t),Do(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=R.chrome||R.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let r of this.tile.children)r.isWidget()&&r.widget instanceof Ur&&s.push(r.dom);i.updateGaps(s)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let t of e.transactions)for(let i of t.effects)i.is(ru)&&(this.editContextFormatting=i.value)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let{dom:i}=this.tile,s=this.view.root.activeElement,r=s==i,o=!r&&!(this.view.state.facet(Dt)||i.tabIndex>-1)&&gn(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,h;if(l.empty?h=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(h=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),R.gecko&&l.empty&&!this.hasComposition&&Gp(c)){let f=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(f,c.node.childNodes[c.offset]||null)),c=h=new pt(f,0),a=!0}let u=this.view.observer.selectionRange;(a||!u.focusNode||(!On(c.node,c.offset,u.anchorNode,u.anchorOffset)||!On(h.node,h.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,l))&&(this.view.observer.ignore(()=>{R.android&&R.chrome&&i.contains(u.focusNode)&&sm(u.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let f=kn(this.view.root);if(f)if(l.empty){if(R.gecko){let d=Jp(c.node,c.offset);if(d&&d!=3){let p=(d==1?Wh:qh)(c.node,c.offset);p&&(c=new pt(p.node,p.offset))}}f.collapse(c.node,c.offset),l.bidiLevel!=null&&f.caretBidiLevel!==void 0&&(f.caretBidiLevel=l.bidiLevel)}else if(f.extend){f.collapse(c.node,c.offset);try{f.extend(h.node,h.offset)}catch{}}else{let d=document.createRange();l.anchor>l.head&&([c,h]=[h,c]),d.setEnd(h.node,h.offset),d.setStart(c.node,c.offset),f.removeAllRanges(),f.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(c,h)),this.impreciseAnchor=c.precise?null:new pt(u.anchorNode,u.anchorOffset),this.impreciseHead=h.precise?null:new pt(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&On(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=kn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!l||!c||l.bottom>c.top)return;let h=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(h.node,h.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=It(e)==0?0:t==0?-1:1;for(;;){let a=e.parentNode;if(a==i.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!Se.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,a=s;;o++){let l=i.children[o];if(l.dom==r)return a;a+=l.length+l.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(s,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,h)=>{if(c.isWidget()){if(c.flags&32&&h>=e)return!0;c.flags&16&&(r=!0)}else{let u=h+c.length;if(h<=e&&(i=c,s=e-h,r=u<e),u>=e&&!o&&(o=c,a=e-h,l=h>e),h>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:l&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(a,t))}coordsAt(e,t,i){let{tile:s,offset:r}=this.tile.resolveBlock(e,t);return s.isWidget()?s.widget instanceof Ur?null:s.coordsInWidget(r,t,!0):s.coordsIn(r,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let a of r.children){if(a.length>=o){let l=s(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(r.isText()&&o<r.length){let a=Ze(r.text,o);if(a==o)return null;let l=Qn(r.dom,o,a).getClientRects();for(let c=0;c<l.length;c++){let h=l[c];if(c==l.length-1||h.top<h.bottom&&h.left<h.right)return h}}return null}return s(t,i)}measureVisibleLineHeights(e){let t=[],{from:i,to:s}=e,r=this.view.contentDOM.clientWidth,o=r>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==fe.LTR,c=0,h=(u,f,d)=>{for(let p=0;p<u.children.length&&!(f>s);p++){let m=u.children[p],g=f+m.length,y=m.dom.getBoundingClientRect(),{height:b}=y;if(d&&!p&&(c+=y.top-d.top),m instanceof Lt)g>i&&h(m,f,y);else if(f>=i&&(c>0&&t.push(-c),t.push(b+c),c=0,o)){let x=m.dom.lastChild,C=x?ys(x):[];if(C.length){let k=C[C.length-1],S=l?k.right-y.left:y.right-k.left;S>a&&(a=S,this.minWidth=r,this.minWidthFrom=f,this.minWidthTo=g)}}d&&p==u.children.length-1&&(c+=d.bottom-y.bottom),f=g+m.breakAfter}};return h(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?fe.RTL:fe.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let h=ys(c.dom);if(h.length!=1)return;a+=h[0].width,l=h[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=ys(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(B.replace({widget:new Ur(a),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return B.set(e)}updateDeco(){let e=1,t=this.view.state.facet(ur).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(va).map((r,o)=>{let a=typeof r=="function";return a&&(i=!0),a?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(N.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];e<this.decorations.length;)this.dynamicDecorationMap[e++]=!1;this.blockWrappers=this.view.state.facet(au).map(r=>typeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(su))try{if(c(this.view,e.range,e))return!0}catch(h){ze(this.view.state,h,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=wa(this.view),o={left:i.left-r.left,top:i.top-r.top,right:i.right+r.right,bottom:i.bottom+r.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;if(kp(this.view.scrollDOM,o,t.head<t.anchor?-1:1,e.x,e.y,Math.max(Math.min(e.xMargin,a),-a),Math.max(Math.min(e.yMargin,l),-l),this.view.textDirection==fe.LTR),window.visualViewport&&window.innerHeight-window.visualViewport.height>1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottom<window.visualViewport.offsetTop)){let c=this.view.docView.lineAt(t.head,1);if(c){let h=Lh(c.dom);c.dom.scrollIntoView({block:"nearest"}),Xh(h,!1)}}}lineHasWidget(e){let t=i=>i.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){Do(this.tile)}}function Do(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)Do(i,e)}}function Gp(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function uu(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=Wh(t.focusNode,t.focusOffset),s=qh(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let a=Se.get(s.node);if(!a||a.isText()&&a.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let l=Se.get(i.node);!l||l.isText()&&l.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function _p(n,e,t){let i=uu(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,a=s.nodeValue;if(/[\n\r]/.test(a)||n.state.doc.sliceString(i.from,i.to)!=a)return null;let l=e.invertedDesc;return{range:new ct(l.mapPos(r),l.mapPos(o),r,o),text:s}}function Jp(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e<n.childNodes.length&&n.childNodes[e].contentEditable=="false"?2:0)}let em=class{constructor(){this.changes=[]}compareRange(e,t){Mi(e,t,this.changes)}comparePoint(e,t){Mi(e,t,this.changes)}boundChange(e){Mi(e,e,this.changes)}};function tm(n,e,t){let i=new em;return N.compare(n,e,t,i),i.changes}class im{constructor(){this.changes=[]}compareRange(e,t){Mi(e,t,this.changes)}comparePoint(){}boundChange(e){Mi(e,e,this.changes)}}function nm(n,e,t){let i=new im;return N.compare(n,e,t,i),i.changes}function sm(n,e){for(let t=n;t&&t!=e;t=t.assignedSlot||t.parentNode)if(t.nodeType==1&&t.contentEditable=="false")return!0;return!1}function rm(n,e){let t=!1;return e&&n.iterChangedRanges((i,s)=>{i<e.to&&s>e.from&&(t=!0)}),t}class Ur extends Ut{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function om(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return A.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,a=r;t<0?o=Ze(s.text,r,!1):a=Ze(s.text,r);let l=i(s.text.slice(o,a));for(;o>0;){let c=Ze(s.text,o,!1);if(i(s.text.slice(c,o))!=l)break;o=c}for(;a<s.length;){let c=Ze(s.text,a);if(i(s.text.slice(a,c))!=l)break;a=c}return A.undirectionalRange(o+s.from,a+s.from)}function am(n,e,t,i,s){let r=Math.round((i-e.left)*n.defaultCharacterWidth);if(n.lineWrapping&&t.height>n.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((s-t.top-(n.defaultLineHeight-a)*.5)/a);r+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Qo(o,r,n.state.tabSize)}function Lo(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.to<e)){if(r.from<e&&r.to>e)return r;(!s||r.type==Le.Text&&(s.type!=r.type||(t<0?r.from<e:r.to>e)))&&(s=r)}}return s||i}return i}function lm(n,e,t,i){let s=Lo(n,e.head,e.assoc||-1),r=!i||s.type!=Le.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(s.from),l=n.posAtCoords({x:t==(a==fe.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(l!=null)return A.cursor(l,t?-1:1)}return A.cursor(t?s.to:s.from,t?-1:1)}function $l(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let a=e,l=null;;){let c=Up(s,r,o,a,t),h=Nh;if(!c){if(s.number==(t?n.state.doc.lines:1))return a;h=` -`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),c=n.visualLineSide(s,!t)}if(l){if(!l(h))return a}else{if(!i)return c;l=i(h)}a=c}}function cm(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==ye.Space&&(s=o),s==o}}function hm(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return A.cursor(s,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),c=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),h=n.documentTop;if(c)o==null&&(o=c.left-l.left),a=r<0?c.top:c.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(s-p.from))),a=(r<0?p.top:p.bottom)+h}let u=l.left+o,f=n.viewState.heightOracle.textHeight>>1,d=i??f;for(let p=0;;p+=f){let m=a+(d+p)*r,g=Xo(n,{x:u,y:m},!1,r);if(t?m>l.bottom:m<l.top)return A.cursor(g.pos,g.assoc);let y=n.coordsAtPos(g.pos,g.assoc),b=y?(y.top+y.bottom)/2:0;if(!y||(t?b>a:b<a))return A.cursor(g.pos,g.assoc,void 0,o)}}function yn(n,e,t){for(;;){let i=0;for(let s of n)s.between(e-1,e+1,(r,o,a)=>{if(e>r&&e<o){let l=i||t||(e-r<o-e?-1:1);e=l<0?r:o,i=l}});if(!i)return e}}function fu(n,e){let t=null;for(let i=0;i<e.ranges.length;i++){let s=e.ranges[i],r=null;if(s.empty){let o=yn(n,s.from,0);o!=s.from&&(r=A.cursor(o,-1))}else{let o=yn(n,s.from,-1),a=yn(n,s.to,1);(o!=s.from||a!=s.to)&&(s.undirectional?r=A.undirectionalRange(s.from,s.to):r=A.range(s.from==s.anchor?o:a,s.from==s.head?o:a))}r&&(t||(t=e.ranges.slice()),t[i]=r)}return t?A.create(t,e.mainIndex):e}function Fr(n,e,t){let i=yn(n.state.facet(Dn).map(s=>s(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:A.cursor(i,i<t.from?1:-1)}class Pt{constructor(e,t){this.pos=e,this.assoc=t}}function Xo(n,e,t,i){let s=n.contentDOM.getBoundingClientRect(),r=s.top+n.viewState.paddingTop,{x:o,y:a}=e,l=a-r,c;for(;;){if(l<0)return new Pt(0,1);if(l>n.viewState.docHeight)return new Pt(n.state.doc.length,-1);if(c=n.elementAtHeight(l),i==null)break;if(c.type==Le.Text){if(i<0?c.to<n.viewport.from:c.from>n.viewport.to)break;let f=n.docView.coordsAt(i<0?c.from:c.to,i>0?-1:1);if(f&&(i<0?f.top<=l+r:f.bottom>=l+r))break}let u=n.viewState.heightOracle.textHeight/2;l=i>0?c.bottom+u:c.top-u}if(n.viewport.from>=c.to||n.viewport.to<=c.from){if(t)return null;if(c.type==Le.Text){let u=am(n,s,c,o,a);return new Pt(u,u==c.from?1:-1)}}if(c.type!=Le.Text)return l<(c.top+c.bottom)/2?new Pt(c.from,1):new Pt(c.to,-1);let h=n.docView.lineAt(c.from,2);return(!h||h.length!=c.length)&&(h=n.docView.lineAt(c.from,-2)),new um(n,o,a,n.textDirectionAt(c.from)).scanTile(h,c.from)}class um{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to<e)&&(this.line=this.view.state.doc.lineAt(e),this.spans=this.view.bidiSpans(this.line)),this}baseDirAt(e,t){let{line:i,spans:s}=this.bidiSpansAt(e);return s[Ct.find(s,e-i.from,-1,t)].level==this.baseDir}dirAt(e,t){let{line:i,spans:s}=this.bidiSpansAt(e);return s[Ct.find(s,e-i.from,-1,t)].dir}bidiIn(e,t){let{spans:i,line:s}=this.bidiSpansAt(e);return i.length>1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from<t)}scan(e,t,i=!1){let s=0,r=e.length-1,o=new Set,a=this.bidiIn(e[0],e[r]),l,c,h=-1,u=1e9,f;e:for(;s<r;){let p=r-s,m=s+r>>1;t:if(o.has(m)){for(let b=1;b<p;b++){let x=m+b;if(x>=r&&(x-=p),!o.has(x)){m=x;break t}}break e}o.add(m);let g=t(m),y=0;if(g)for(let b=0;b<g.length;b++){let x=g[b];if(!(x.width==0&&g.length>1))if(x.bottom<this.y)(!l||l.bottom<x.bottom)&&(l=x),y=1;else if(x.top>this.y)(!c||c.top>x.top)&&(c=x),y=-1;else{let C=x.left>this.x?this.x-x.left:x.right<this.x?this.x-x.right:0,k=Math.abs(C);k<u&&(h=m,u=k,f=x),C&&(y=C<0==(this.baseDir==fe.LTR)?-1:1)}}y==-1&&(!a||this.baseDirAt(e[m],1))?r=m:y==1&&(!a||this.baseDirAt(e[m+1],-1))&&(s=m+1)}if(!f){if(!c&&!l)return{i:e[0],after:!1};let p=l&&(!c||this.y-l.bottom<c.top-this.y)?l:c;return this.y=(p.top+p.bottom)/2,this.scan(e,t,!0)}if(u&&!i){let{top:p,bottom:m}=f;if(l&&l.bottom>(p+p+m)/3)return this.y=l.bottom-1,this.scan(e,t,!0);if(c&&c.top<(p+m+m)/3)return this.y=c.top+1,this.scan(e,t,!0)}let d=(a?this.dirAt(e[h],1):this.baseDir)==fe.LTR;return{i:h,after:this.x>(f.left+f.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r<e.length;r=Ze(e.text,r))i.push(t+r);i.push(t+e.length);let s=this.scan(i,r=>{let o=i[r]-t,a=i[r+1]-t;return Qn(e.dom,o,a).getClientRects()});return s.after?new Pt(i[s.i+1],-1):new Pt(i[s.i],1)}scanTile(e,t){if(!e.length)return new Pt(t,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,t);if(a.isComposite())return this.scanTile(a,t)}let i=[t];for(let a=0,l=t;a<e.children.length;a++)i.push(l+=e.children[a].length);let s=this.scan(i,a=>{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:Qn(l.dom,0,l.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Pt(i[s.i+1],-1):new Pt(o,1)}}const ki="￿";class fm{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(_.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=ki}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=Se.get(s),a=s.nextSibling;if(a==t){o?.breakAfter&&!a&&i!=this.view.contentDOM&&this.lineBreak();break}let l=Se.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:Rs(s))||Rs(a)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!pm(a,t)&&this.lineBreak(),s=a}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,a;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(a=s.exec(t))&&(r=a.index,o=a[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);i=r+o}}readNode(e){let t=Se.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(dm(e,i.node,i.offset)?t:0))}}function dm(n,e,t){for(;;){if(!e||t<It(e))return!1;if(e==n)return!0;t=ii(e)+1,e=e.parentNode}}function pm(n,e){let t;for(;!(n==e||!n);n=n.nextSibling){let i=Se.get(n);if(!i?.isWidget())return!1;i&&(t||(t=[])).push(i)}if(t)for(let i of t){let s=i.overrideDOMText;if(s?.length)return!1}return!0}class Kl{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}}class mm{constructor(e,t,i,s){this.typeOver=s,this.bounds=null,this.text="",this.domChanged=t>-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=du(e.docView.tile,t,i,0))){let l=r||o?[]:Om(e),c=new fm(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=ym(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!Zo(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),h=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Zo(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),u=e.viewport;if((R.ios||R.chrome)&&c!=h&&Math.min(c,h)<=a.main.from&&Math.max(c,h)>=a.main.to&&(u.from>0||u.to<e.state.doc.length)){let f=Math.min(c,h),d=Math.max(c,h),p=u.from-f,m=u.to-d;(p==0||p==1||f==0)&&(m==0||m==-1||d==e.state.doc.length)&&(c=0,h=e.state.doc.length)}if(e.inputState.composing>-1&&a.ranges.length>1)this.newSel=a.replaceRange(A.range(h,c));else if(e.lineWrapping&&h==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let f=e.coordsAtPos(c,-1),d=0;f&&(d=e.inputState.lastTouchY<=f.bottom?-1:1),this.newSel=A.create([A.cursor(c,d)])}else this.newSel=A.single(h,c)}}}function du(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,a=-1;for(let l=0,c=i,h=i;l<n.children.length;l++){let u=n.children[l],f=c+u.length;if(c<e&&f>t)return du(u,e,t,c);if(f>=e&&s==-1&&(s=l,r=c),c>t&&u.dom.parentNode==n.dom){o=l,a=h;break}h=f,c=f+u.breakAfter}return{from:r,to:a<0?i+n.length:a,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o<n.children.length&&o>=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function pu(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=r.from,h=null;(o===8||R.android&&e.text.length<l-a)&&(c=r.to,h="end");let u=s.doc.sliceString(a,l,ki),f,d;!r.empty&&r.from>=a&&r.to<=l&&(e.typeOver||u!=e.text)&&u.slice(0,r.from-a)==e.text.slice(0,r.from-a)&&u.slice(r.to-a)==e.text.slice(f=e.text.length-(u.length-(r.to-a)))?t={from:r.from,to:r.to,insert:se.of(e.text.slice(r.from-a,f).split(ki))}:(d=mu(u,e.text,c-a,h))&&(R.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==ki+ki&&d.toB--,t={from:a+d.from,to:a+d.toA,insert:se.of(e.text.slice(d.from,d.toB).split(ki))})}else i&&(!n.hasFocus&&s.facet(Dt)||Es(i,r))&&(i=null);if(!t&&!i)return!1;if((R.mac||R.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:se.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).to<r.to&&n.docView.lineHasWidget(r.to)&&n.inputState.insertingTextAt>Date.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:R.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` - `&&n.lineWrapping&&(i&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:se.of([" "])}),t)return ka(n,t,i,o);if(i&&!Es(i,r)){let a=!1,l="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(a=!0),l=n.inputState.lastSelectionOrigin,l=="select.pointer"&&(i=fu(s.facet(Dn).map(c=>c(n)),i))),n.dispatch({selection:i,scrollIntoView:a,userEvent:l}),!0}else return!1}function ka(n,e,t,i=-1){if(R.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(R.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Ei(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.length<e.to-e.from&&e.to>s.head)&&Ei(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&Ei(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,a=()=>o||(o=gm(n,e,t));return n.state.facet(eu).some(l=>l(n,e.from,e.to,r,a))||n.dispatch(a()),!0}function gm(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.from<r.from||e.from>r.to){let l=e.from<r.from?-1:1,c=l<0?r.from:r.to,h=yn(s.facet(Dn).map(u=>u(n)),c,l);e.from==h&&(o=h)}if(o>-1)i={changes:e,selection:A.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let l=r.from<e.from?s.sliceDoc(r.from,e.from):"",c=r.to>e.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(l+e.insert.sliceString(0,void 0,n.state.lineBreak)+c))}else{let l=s.changes(e),c=t&&t.main.to<=l.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let h=n.state.sliceDoc(e.from,e.to),u,f=t&&uu(n,t.main.head);if(f){let p=e.insert.length-(e.to-e.from);u={from:f.from,to:f.to-p}}else u=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:l,range:c||p.map(l)};let m=p.to-d,g=m-h.length;if(n.state.sliceDoc(g,m)!=h||m>=u.from&&g<=u.to)return{range:p};let y=s.changes({from:g,to:m,insert:e.insert}),b=p.to-r.to;return{changes:y,range:c?A.range(Math.max(0,c.anchor+b),Math.max(0,c.head+b)):p.map(y)}})}else i={changes:l,selection:c&&s.selection.replaceRange(c)}}let a="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:a,scrollIntoView:!0})}function mu(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r<s&&n.charCodeAt(r)==e.charCodeAt(r);)r++;if(r==s&&n.length==e.length)return null;let o=n.length,a=e.length;for(;o>0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(i=="end"){let l=Math.max(0,r-Math.min(o,a));t-=o+l-r}if(o<r&&n.length<e.length){let l=t<=r&&t>=o?r-t:0;r-=l,a=r+(a-o),o=r}else if(a<r){let l=t<=r&&t>=a?r-t:0;r-=l,o=r+(o-a),a=r}return{from:r,toA:o,toB:a}}function Om(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new Kl(t,i)),(s!=t||r!=i)&&e.push(new Kl(s,r))),e}function ym(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?A.single(t+e,i+e):null}function Es(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}class Am{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,R.safari&&e.contentDOM.addEventListener("input",()=>null),R.gecko&&Em(e.contentDOM.ownerDocument)}handleEvent(e){!Cm(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Sm(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,a=i[r];a&&o!=!a.handlers.length&&(s.removeEventListener(r,this.handleEvent),a=null),a||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Ou.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),R.android&&R.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(R.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(gu.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||xm.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&R.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&bm(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,Ei(this.view.contentDOM,t.key,t.keyCode,t.mods))}ignoreDuringComposition(e){return!/^key/.test(e.type)||e.synthetic?!1:this.composing>0?!0:R.safari&&!R.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function bm(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Zl(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ze(t.state,s)}}}function Sm(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let a in r){let l=r[a];l&&t(a).handlers.push(Zl(i.value,l))}if(o)for(let a in o){let l=o[a];l&&t(a).observers.push(Zl(i.value,l))}}for(let i in Ot)t(i).handlers.push(Ot[i]);for(let i in je)t(i).observers.push(je[i]);return e}const gu=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],xm="dthko",Ou=[16,17,18,20,91,92,224,225],Hn=6;function Gn(n){return Math.max(0,n)*.7+8}function vm(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class wm{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Dh(e.contentDOM),this.atoms=e.state.facet(Dn).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(_.allowMultipleSelections)&&km(e,t),this.dragging=Pm(e,t)&&bu(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&vm(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=wa(this.view);e.clientX-l.left<=s+Hn?t=-Gn(s-e.clientX):e.clientX+l.right>=o-Hn&&(t=Gn(e.clientX-o)),e.clientY-l.top<=r+Hn?i=-Gn(r-e.clientY):e.clientY+l.bottom>=a-Hn&&(i=Gn(e.clientY-a)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=fu(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function km(n,e){let t=n.state.facet(Hh);return t.length?t[0](e):R.mac?e.metaKey:e.ctrlKey}function Qm(n,e){let t=n.state.facet(Gh);return t.length?t[0](e):R.mac?!e.altKey:!e.ctrlKey}function Pm(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=kn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r<s.length;r++){let o=s[r];if(o.left<=e.clientX&&o.right>=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Cm(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=Se.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}const Ot=Object.create(null),je=Object.create(null),yu=R.ie&&R.ie_version<15||R.ios&&R.webkit_version<604;function Tm(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Au(n,t.value)},50)}function pr(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function Au(n,e){e=pr(n.state,ba,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(Bo!=null&&t.selection.ranges.every(l=>l.empty)&&Bo==r.toString()){let l=-1;i=t.changeByRange(c=>{let h=t.doc.lineAt(c.from);if(h.from==l)return{range:c};l=h.from;let u=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:u},range:A.cursor(c.from+u.length)}})}else o?i=t.changeByRange(l=>{let c=r.line(s++);return{changes:{from:l.from,to:l.to,insert:c.text},range:A.cursor(l.from+c.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}je.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,R.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};je.wheel=je.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ot.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);je.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};je.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};je.touchend=(n,e)=>{n.inputState.touchActive=!1};Ot.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(_h))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=$m(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new wm(n,e,t,i)),i&&n.observer.ignore(()=>{Bh(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Ml(n,e,t,i){if(i==1)return A.cursor(e,t);if(i==2)return om(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,a=s?s.posAtEnd:r.to;return a<n.state.doc.length&&a==r.to&&a++,A.undirectionalRange(o,a)}}const Rm=R.ie&&R.ie_version<=11;let El=null,Ul=0,Fl=0;function bu(n){if(!Rm)return n.detail;let e=El,t=Fl;return El=n,Fl=Date.now(),Ul=!e||t>Date.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Ul+1)%3:1}function $m(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=bu(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,a){let l=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),c,h=Ml(n,l.pos,l.assoc,i);if(t.pos!=l.pos&&!o){let u=Ml(n,t.pos,t.assoc,i),f=Math.min(u.from,h.from),d=Math.max(u.to,h.to);h=f<h.from?A.range(f,d,h.assoc):A.range(d,f,h.assoc)}return o?s.replaceRange(s.main.extend(h.from,h.to,h.assoc)):a&&i==1&&s.ranges.length>1&&(c=Km(s,l.pos))?c:a?s.addRange(h):A.create([h])}}}function Km(n,e){for(let t=0;t<n.ranges.length;t++){let{from:i,to:s}=n.ranges[t];if(i<=e&&s>=e)return A.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ot.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=A.undirectionalRange(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",pr(n.state,Sa,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ot.dragend=n=>(n.inputState.draggedContent=null,!1);function Dl(n,e,t,i){if(t=pr(n.state,ba,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&Qm(n,e)?{from:r.from,to:r.to}:null,a={from:s,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ot.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Dl(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o<t.length;o++){let a=new FileReader;a.onerror=r,a.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(i[o]=a.result),r()},a.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Dl(n,e,i,!0),!0}return!1};Ot.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=yu?null:e.clipboardData;return t?(Au(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Tm(n),!1)};function Zm(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Mm(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:pr(n,Sa,e.join(n.lineBreak)),ranges:t,linewise:i}}let Bo=null;Ot.copy=Ot.cut=(n,e)=>{if(!gn(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=Mm(n.state);if(!t&&!s)return!1;Bo=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=yu?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(Zm(n,t),!1)};const Su=qt.define();function xu(n,e){let t=[];for(let i of n.facet(tu)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:Su.of(!0)}):null}function vu(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=xu(n.state,e);t?n.dispatch(t):n.update([])}},10)}je.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),vu(n)};je.blur=n=>{n.observer.clearSelectionRange(),vu(n)};je.compositionstart=je.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};je.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,R.chrome&&R.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};je.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ot.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let a=o[0],l=n.posAtDOM(a.startContainer,a.startOffset),c=n.posAtDOM(a.endContainer,a.endOffset);return ka(n,{from:l,to:c,insert:n.state.toText(r)},null),!0}}let s;if(R.chrome&&R.android&&(s=gu.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return R.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),R.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>je.compositionend(n,e),20),!1};const Ll=new Set;function Em(n){Ll.has(n)||(Ll.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const Xl=["pre-wrap","normal","pre-line","break-spaces"];let qi=!1;function Bl(){qi=!1}class Um{constructor(e){this.lineWrapping=e,this.doc=se.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Xl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i<e.length;i++){let s=e[i];s<0?i++:this.heightSamples[Math.floor(s*10)]||(t=!0,this.heightSamples[Math.floor(s*10)]=!0)}return t}refresh(e,t,i,s,r,o){let a=Xl.indexOf(e)>-1,l=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,l){this.heightSamples={};for(let c=0;c<o.length;c++){let h=o[c];h<0?c++:this.heightSamples[Math.floor(h*10)]=!0}}return l}}class Fm{constructor(e,t){this.from=e,this.heights=t,this.index=0}get more(){return this.index<this.heights.length}}class dt{constructor(e,t,i,s,r){this.from=e,this.length=t,this.top=i,this.height=s,this._content=r}get type(){return typeof this._content=="number"?Le.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof Ai?this._content.widget:null}get widgetLineBreaks(){return typeof this._content=="number"?this._content:0}join(e){let t=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(e._content)?e._content:[e]);return new dt(this.from,this.length+e.length,this.top,this.height+e.height,t)}}var pe=(function(n){return n[n.ByPos=0]="ByPos",n[n.ByHeight=1]="ByHeight",n[n.ByPosNoHeight=2]="ByPosNoHeight",n})(pe||(pe={}));const As=.001;class Ve{constructor(e,t,i=2){this.length=e,this.height=t,this.flags=i}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>As&&(qi=!0),this.height=e)}replace(e,t,i){return Ve.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let a=s.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:h,toB:u}=s[a],f=r.lineAt(l,pe.ByPosNoHeight,i.setDoc(t),0,0),d=f.to>=c?f:r.lineAt(c,pe.ByPosNoHeight,i,0,0);for(u+=d.to-c,c=d.to;a>0&&f.from<=s[a-1].toA;)l=s[a-1].fromA,h=s[a-1].fromB,a--,l<f.from&&(f=r.lineAt(l,pe.ByPosNoHeight,i,0,0));h+=f.from-l,l=f.from;let p=Qa.build(i.setDoc(o),e,h,u);r=Us(r,r.replace(l,c,p))}return r.updateHeight(i,0)}static empty(){return new ot(0,0,0)}static of(e){if(e.length==1)return e[0];let t=0,i=e.length,s=0,r=0;for(;;)if(t==i)if(s>r*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),i+=1+a.break,s-=a.size}else if(r>s*2){let a=e[i];a.break?e.splice(i,1,a.left,null,a.right):e.splice(i,1,a.left,a.right),i+=2+a.break,r-=a.size}else break;else if(s<r){let a=e[t++];a&&(s+=a.size)}else{let a=e[--i];a&&(r+=a.size)}let o=0;return e[t-1]==null?(o=1,t--):e[t]==null&&(o=1,i++),new Lm(Ve.of(e.slice(0,t)),o,Ve.of(e.slice(i)))}}function Us(n,e){return n==e?n:(n.constructor!=e.constructor&&(qi=!0),e)}Ve.prototype.size=1;const Dm=B.replace({});class wu extends Ve{constructor(e,t,i){super(e,t),this.deco=i,this.spaceAbove=0}mainBlock(e,t){return new dt(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.deco||0)}blockAt(e,t,i,s){return this.spaceAbove&&e<i+this.spaceAbove?new dt(s,0,i,this.spaceAbove,Dm):this.mainBlock(i,s)}lineAt(e,t,i,s,r){let o=this.mainBlock(s,r);return this.spaceAbove?this.blockAt(0,i,s,r).join(o):o}forEachLine(e,t,i,s,r,o){e<=r+this.length&&t>=r&&o(this.lineAt(0,pe.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}}class ot extends wu{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new dt(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof ot||s instanceof Ee&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof Ee?s=new ot(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Ve.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class Ee extends Ve{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*r);o=l/r,this.length>r+1&&(a=(this.height-l)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:a}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,s);if(t.lineWrapping){let c=s+(e<t.lineHeight?0:Math.round(Math.max(0,Math.min(1,(e-i)/this.height))*this.length)),h=t.doc.lineAt(c),u=a+h.length*l,f=Math.max(i,e-u/2);return new dt(h.from,h.length,f,u,0)}else{let c=Math.max(0,Math.min(o-r,Math.floor((e-i)/a))),{from:h,length:u}=t.doc.line(r+c);return new dt(h,u,i+a*c,a,0)}}lineAt(e,t,i,s,r){if(t==pe.ByHeight)return this.blockAt(e,i,s,r);if(t==pe.ByPosNoHeight){let{from:d,to:p}=i.doc.lineAt(e);return new dt(d,p-d,0,0,0)}let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(i,r),c=i.doc.lineAt(e),h=a+c.length*l,u=c.number-o,f=s+a*u+l*(c.from-r-u);return new dt(c.from,c.length,Math.max(s,Math.min(f,s+this.height-h)),h,0)}forEachLine(e,t,i,s,r,o){e=Math.max(e,r),t=Math.min(t,r+this.length);let{firstLine:a,perLine:l,perChar:c}=this.heightMetrics(i,r);for(let h=e,u=s;h<=t;){let f=i.doc.lineAt(h);if(h==e){let p=f.number-a;u+=l*p+c*(e-r-p)}let d=l+c*f.length;o(new dt(f.from,f.length,u,d,0)),u+=d,h=f.to+1}}replace(e,t,i){let s=this.length-t;if(s>0){let r=i[i.length-1];r instanceof Ee?i[i.length-1]=new Ee(r.length+s):i.push(null,new Ee(s-1))}if(e>0){let r=i[0];r instanceof Ee?i[0]=new Ee(e+r.length):i.unshift(new Ee(e-1),null)}return Ve.of(i)}decomposeLeft(e,t){t.push(new Ee(e-1),null)}decomposeRight(e,t){t.push(null,new Ee(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],a=Math.max(t,s.from),l=-1;for(s.from>t&&o.push(new Ee(s.from-t-1).updateHeight(e,t));a<=r&&s.more;){let h=e.doc.lineAt(a).length;o.length&&o.push(null);let u=s.heights[s.index++],f=0;u<0&&(f=-u,u=s.heights[s.index++]),l==-1?l=u:Math.abs(u-l)>=As&&(l=-2);let d=new ot(h,u,f);d.outdated=!1,o.push(d),a+=h+1}a<=r&&o.push(null,new Ee(r-a).updateHeight(e,a));let c=Ve.of(o);return(l<0||Math.abs(c.height-this.height)>=As||Math.abs(l-this.heightMetrics(e,t).perLine)>=As)&&(qi=!0),Us(this,c)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class Lm extends Ve{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return e<r?this.left.blockAt(e,t,i,s):this.right.blockAt(e,t,r,s+this.left.length+this.break)}lineAt(e,t,i,s,r){let o=s+this.left.height,a=r+this.left.length+this.break,l=t==pe.ByHeight?e<o:e<a,c=l?this.left.lineAt(e,t,i,s,r):this.right.lineAt(e,t,i,o,a);if(this.break||(l?c.to<a:c.from>a))return c;let h=t==pe.ByPosNoHeight?pe.ByPosNoHeight:pe.ByPos;return l?c.join(this.right.lineAt(a,h,i,o,a)):this.left.lineAt(a,h,i,s,r).join(c)}forEachLine(e,t,i,s,r,o){let a=s+this.left.height,l=r+this.left.length+this.break;if(this.break)e<l&&this.left.forEachLine(e,t,i,s,r,o),t>=l&&this.right.forEachLine(e,t,i,a,l,o);else{let c=this.lineAt(l,pe.ByPos,i,s,r);e<c.from&&this.left.forEachLine(e,c.from-1,i,s,r,o),c.to>=e&&c.from<=t&&o(c),t>c.to&&this.right.forEachLine(c.to+1,t,i,a,l,o)}}replace(e,t,i){let s=this.left.length+this.break;if(t<s)return this.balanced(this.left.replace(e,t,i),this.right);if(e>this.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let a of i)r.push(a);if(e>0&&Il(r,o-1),t<this.length){let a=r.length;this.decomposeRight(t,r),Il(r,a)}return Ve.of(r)}decomposeLeft(e,t){let i=this.left.length;if(e<=i)return this.left.decomposeLeft(e,t);t.push(this.left),this.break&&(i++,e>=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e<i&&this.left.decomposeRight(e,t),this.break&&e<s&&t.push(null),t.push(this.right)}balanced(e,t){return e.size>2*t.size||t.size>2*e.size?Ve.of(this.break?[e,null,t]:[e,t]):(this.left=Us(this.left,e),this.right=Us(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,a=t+r.length+this.break,l=null;return s&&s.from<=t+r.length&&s.more?l=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=a+o.length&&s.more?l=o=o.updateHeight(e,a,i,s):o.updateHeight(e,a,i),l?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function Il(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof Ee&&(i=n[e+1])instanceof Ee&&n.splice(e-1,3,new Ee(t.length+1+i.length))}const Xm=5;class Qa{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof ot?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new ot(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e<t||i.heightRelevant){let s=i.widget?i.widget.estimatedHeight:0,r=i.widget?i.widget.lineBreaks:0;s<0&&(s=this.oracle.lineHeight);let o=t-e;i.block?this.addBlock(new wu(o,s,i)):(o||r||s>=Xm)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new ot(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new Ee(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ot)return e;let t=new ot(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ot)&&!this.isCovered?this.nodes.push(new ot(0,-1,0)):(this.writtenTo<this.pos||t==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let i=e;for(let s of this.nodes)s instanceof ot&&s.updateHeight(this.oracle,i),i+=s?s.length:1;return this.nodes}static build(e,t,i,s){let r=new Qa(i,e);return N.spans(t,i,s,r,0),r.finish(i)}}function Bm(n,e,t){let i=new Im;return N.compare(n,e,t,i,0),i.changes}class Im{constructor(){this.changes=[]}compareRange(){}comparePoint(e,t,i,s){(e<t||i&&i.heightRelevant||s&&s.heightRelevant)&&Mi(e,t,this.changes,5)}}function Wm(n,e){let t=n.getBoundingClientRect(),i=n.ownerDocument,s=i.defaultView||window,r=Math.max(0,t.left),o=Math.min(s.innerWidth,t.right),a=Math.max(0,t.top),l=Math.min(s.innerHeight,t.bottom);for(let c=n.parentNode;c&&c!=i.body;)if(c.nodeType==1){let h=c,u=window.getComputedStyle(h);if((h.scrollHeight>h.clientHeight||h.scrollWidth>h.clientWidth)&&u.overflow!="visible"){let f=h.getBoundingClientRect();r=Math.max(r,f.left),o=Math.min(o,f.right),a=Math.max(a,f.top),l=Math.min(c==n.parentNode?s.innerHeight:l,f.bottom)}c=u.position=="absolute"||u.position=="fixed"?h.offsetParent:h.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function qm(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left<t.innerWidth&&e.right>0&&e.top<t.innerHeight&&e.bottom>0}function zm(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class Dr{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;i<e.length;i++){let s=e[i],r=t[i];if(s.from!=r.from||s.to!=r.to||s.size!=r.size)return!1}return!0}draw(e,t){return B.replace({widget:new Vm(this.displaySize*(t?e.scaleY:e.scaleX),t)}).range(this.from,this.to)}}class Vm extends Ut{constructor(e,t){super(),this.size=e,this.vertical=t}eq(e){return e.size==this.size&&e.vertical==this.vertical}toDOM(){let e=document.createElement("div");return this.vertical?e.style.height=this.size+"px":(e.style.width=this.size+"px",e.style.height="2px",e.style.display="inline-block"),e}get estimatedHeight(){return this.vertical?this.size:-1}}class Wl{constructor(e,t){this.view=e,this.state=t,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scaleX=1,this.scaleY=1,this.scrollOffset=0,this.scrolledToBottom=!1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=ql,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=fe.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let i=t.facet(xa).some(s=>typeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new Um(i),this.stateDeco=zl(t),this.heightMap=Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle.setDoc(t.doc),[new ct(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=B.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new _n(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?ql:new Pa(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(un(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=zl(this.state);let s=e.changedRanges,r=ct.extendWithRanges(s,Bm(i,this.stateDeco,e?e.changes:Re.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);Bl(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||qi)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.head<l.from||t.range.head>l.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(nu)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?fe.RTL:fe.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,h=0;if(a.width&&a.height){let{scaleX:k,scaleY:S}=Fh(t,a);(k>.005&&Math.abs(this.scaleX-k)>.005||S>.005&&Math.abs(this.scaleY-S)>.005)&&(this.scaleX=k,this.scaleY=S,c|=16,o=l=!0)}let u=(parseInt(i.paddingTop)||0)*this.scaleY,f=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=f)&&(this.paddingTop=u,this.paddingBottom=f,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let d=Dh(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=Ih(this.scrollParent||e.win);let m=(this.printing?zm:Wm)(t,this.paddingTop),g=m.top-this.pixelViewport.top,y=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let b=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(b!=this.inView&&(this.inView=b,b&&(l=!0)),!this.inView&&!this.scrollTarget&&!qm(e.dom))return 0;let x=a.width;if((this.contentDOMWidth!=x||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let k=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(k)&&(o=!0),o||s.lineWrapping&&Math.abs(x-this.contentDOMWidth)>s.charWidth){let{lineHeight:S,charWidth:w,textHeight:U}=e.docView.measureTextSize();o=S>0&&s.refresh(r,S,w,U,Math.max(5,x/w),k),o&&(e.docView.minWidth=0,c|=16)}g>0&&y>0?h=Math.max(g,y):g<0&&y<0&&(h=Math.min(g,y)),Bl();for(let S of this.viewports){let w=S.from==this.viewport.from?k:e.docView.measureVisibleLineHeights(S);this.heightMap=(o?Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle,[new ct(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Fm(S.from,w))}qi&&(c|=2)}let C=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return C&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(h,this.scrollTarget),c|=this.updateForViewport()),(c&2||C)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new _n(s.lineAt(o-i*1e3,pe.ByHeight,r,0,0).from,s.lineAt(a+(1-i)*1e3,pe.ByHeight,r,0,0).to);if(t){let{head:c}=t.range;if(c<l.from||c>l.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=s.lineAt(c,pe.ByPos,r,0,0),f;t.y=="center"?f=(u.top+u.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&c<l.from?f=u.top:f=u.bottom-h,l=new _n(s.lineAt(f-1e3/2,pe.ByHeight,r,0,0).from,s.lineAt(f+h+1e3/2,pe.ByHeight,r,0,0).to)}}return l}mapViewport(e,t){let i=t.mapPos(e.from,-1),s=t.mapPos(e.to,1);return new _n(this.heightMap.lineAt(i,pe.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(s,pe.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:t},i=0){if(!this.inView)return!0;let{top:s}=this.heightMap.lineAt(e,pe.ByPos,this.heightOracle,0,0),{bottom:r}=this.heightMap.lineAt(t,pe.ByPos,this.heightOracle,0,0),{visibleTop:o,visibleBottom:a}=this;return(e==0||s<=o-Math.max(10,Math.min(-i,250)))&&(t==this.state.doc.length||r>=a+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r<a+2*1e3}mapLineGaps(e,t){if(!e.length||t.empty)return e;let i=[];for(let s of e)t.touchesRange(s.from,s.to)||i.push(new Dr(t.mapPos(s.from),t.mapPos(s.to),s.size,s.displaySize));return i}ensureLineGaps(e,t){let i=this.heightOracle.lineWrapping,s=i?1e4:2e3,r=s>>1,o=s<<1;if(this.defaultTextDirection!=fe.LTR&&!i)return[];let a=[],l=(h,u,f,d)=>{if(u-h<r)return;let p=this.state.selection.main,m=[p.from];p.empty||m.push(p.to);for(let y of m)if(y>h&&y<u){l(h,y-10,f,d),l(y+10,u,f,d);return}let g=Ym(e,y=>y.from>=f.from&&y.to<=f.to&&Math.abs(y.from-h)<r&&Math.abs(y.to-u)<r&&!m.some(b=>y.from<b&&y.to>b));if(!g){if(u<f.to&&t&&i&&t.visibleRanges.some(x=>x.from<=u&&x.to>=u)){let x=t.moveToLineBoundary(A.cursor(u),!1,!0).head;x>h&&(u=x)}let y=this.gapSize(f,h,u,d),b=i||y<2e6?y:2e6;g=new Dr(h,u,y,b)}a.push(g)},c=h=>{if(h.length<o||h.type!=Le.Text)return;let u=jm(h.from,h.to,this.stateDeco);if(u.total<o)return;let f=this.scrollTarget?this.scrollTarget.range.head:null,d,p;if(i){let m=s/this.heightOracle.lineLength*this.heightOracle.lineHeight,g,y;if(f!=null){let b=es(u,f),x=((this.visibleBottom-this.visibleTop)/2+m)/h.height;g=b-x,y=b+x}else g=(this.visibleTop-h.top-m)/h.height,y=(this.visibleBottom-h.top+m)/h.height;d=Jn(u,g),p=Jn(u,y)}else{let m=u.total*this.heightOracle.charWidth,g=s*this.heightOracle.charWidth,y=0;if(m>2e6)for(let S of e)S.from>=h.from&&S.from<h.to&&S.size!=S.displaySize&&S.from*this.heightOracle.charWidth+y<this.pixelViewport.left&&(y=S.size-S.displaySize);let b=this.pixelViewport.left+y,x=this.pixelViewport.right+y,C,k;if(f!=null){let S=es(u,f),w=((x-b)/2+g)/m;C=S-w,k=S+w}else C=(b-g)/m,k=(x+g)/m;d=Jn(u,C),p=Jn(u,k)}d>h.from&&l(h.from,d,h,u),p<h.to&&l(p,h.to,h,u)};for(let h of this.viewportLines)Array.isArray(h.type)?h.type.forEach(c):c(h);return a}gapSize(e,t,i,s){let r=es(s,i)-es(s,t);return this.heightOracle.lineWrapping?e.height*r:s.total*this.heightOracle.charWidth*r}updateLineGaps(e){Dr.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=B.set(e.map(t=>t.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];N.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r<i.length&&!(s&8);r++){let o=this.visibleRanges[r],a=i[r];(o.from!=a.from||o.to!=a.to)&&(s|=4,e&&e.mapPos(o.from,-1)==a.from&&e.mapPos(o.to,1)==a.to||(s|=8))}return this.visibleRanges=i,s}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||un(this.heightMap.lineAt(e,pe.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||un(this.heightMap.lineAt(this.scaler.fromDOM(e),pe.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return un(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class _n{constructor(e,t){this.from=e,this.to=t}}function jm(n,e,t){let i=[],s=n,r=0;return N.spans(t,n,e,{span(){},point(o,a){o>s&&(i.push({from:s,to:o}),r+=o-s),s=a}},20),s<e&&(i.push({from:s,to:e}),r+=e-s),{total:r,ranges:i}}function Jn({total:n,ranges:e},t){if(t<=0)return e[0].from;if(t>=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],a=o-r;if(i<=a)return r+i;i-=a}}function es(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Ym(n,e){for(let t of n)if(e(t))return t}const ql={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function zl(n){let e=n.facet(ur).filter(i=>typeof i!="function"),t=n.facet(va).filter(i=>typeof i!="function");return t.length&&e.push(N.join(t)),e}class Pa{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:a,to:l})=>{let c=t.lineAt(a,pe.ByPos,e,0,0).top,h=t.lineAt(l,pe.ByPos,e,0,0).bottom;return s+=h-c,{from:a,to:l,top:c,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let a of this.viewports)a.domTop=o+(a.top-r)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),r=a.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=t<this.viewports.length?this.viewports[t]:null;if(!r||e<r.top)return s+(e-i)*this.scale;if(e<=r.bottom)return r.domTop+(e-r.top);i=r.bottom,s=r.domBottom}}fromDOM(e){for(let t=0,i=0,s=0;;t++){let r=t<this.viewports.length?this.viewports[t]:null;if(!r||e<r.domTop)return i+(e-s)/this.scale;if(e<=r.domBottom)return r.top+(e-r.domTop);i=r.bottom,s=r.domBottom}}eq(e){return e instanceof Pa?this.scale==e.scale&&this.viewports.length==e.viewports.length&&this.viewports.every((t,i)=>t.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}}function un(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new dt(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>un(s,e)):n._content)}const ts=K.define({combine:n=>n.join(" ")}),Io=K.define({combine:n=>n.indexOf(!0)>-1}),Wo=ei.newName(),ku=ei.newName(),Qu=ei.newName(),Pu={"&light":"."+ku,"&dark":"."+Qu};function qo(n,e,t){return new ei(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}const Nm=qo("."+Wo,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},Pu),Hm={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Lr=R.ie&&R.ie_version<=11;class Gm{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new Qp,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(R.ie&&R.ie_version<=11||R.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&R.android&&e.constructor.EDIT_CONTEXT!==!1&&!(R.chrome&&R.chrome_version<126)&&(this.editContext=new Jm(e),e.state.facet(Dt)&&(e.contentDOM.editContext=this.editContext.editContext)),Lr&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(Dt)?i.root.activeElement!=this.dom:!gn(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(R.ie&&R.ie_version<=11||R.android&&R.chrome)&&!i.state.selection.main.empty&&s.focusNode&&On(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=kn(e.root);if(!t)return!1;let i=R.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&_m(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=gn(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&Cp(this.dom,i)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(i),s&&(this.selectionChanged=!0),!0)}setSelectionRange(e,t){this.selectionRange.set(e.node,e.offset,t.node,t.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,t=null;for(let i=this.dom;i;)if(i.nodeType==1)!t&&e<this.scrollTargets.length&&this.scrollTargets[e]==i?e++:t||(t=this.scrollTargets.slice(0,e)),t&&t.push(i),i=i.assignedSlot||i.parentNode;else if(i.nodeType==11)i=i.host;else break;if(e<this.scrollTargets.length&&!t&&(t=this.scrollTargets.slice(0,e)),t){for(let i of this.scrollTargets)i.removeEventListener("scroll",this.onScroll);for(let i of this.scrollTargets=t)i.addEventListener("scroll",this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,Hm),Lr&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),Lr&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,t){var i;if(!this.delayedAndroidKey){let s=()=>{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&Ei(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange<Date.now()-50||!!(!((i=this.delayedAndroidKey)===null||i===void 0)&&i.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&gn(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new mm(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=pu(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Es(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Vl(t,e.previousSibling||e.target.previousSibling,-1),s=Vl(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Dt)!=e.state.facet(Dt)&&(e.view.contentDOM.editContext=e.state.facet(Dt)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function Vl(n,e,t){for(;e;){let i=Se.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function jl(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return On(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function _m(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return jl(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?jl(n,t):null}class Jm{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,a=this.toEditorPos(i.updateRangeStart),l=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>i.text.length;a==this.from&&r<this.from?a=r:l==this.to&&r>this.to&&(l=r);let h=mu(e.state.sliceDoc(a,l),i.text,(c?s.from:s.to)-a,c?"end":null);if(!h){let f=A.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Es(f,s)||e.dispatch({selection:f,userEvent:"select"});return}let u={from:h.from+a,to:h.toA+a,insert:se.of(i.text.slice(h.from,h.toB).split(` -`))};if((R.mac||R.android)&&u.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(u={from:a,to:l,insert:se.of([i.text.replace("."," ")])}),this.pendingContextChange=u,!e.state.readOnly){let f=this.to-this.from+(u.to-u.from+u.insert.length);ka(e,u,A.single(this.toEditorPos(i.selectionStart,f),this.toEditorPos(i.selectionEnd,f)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from<u.to&&!u.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),a=this.toEditorPos(i.rangeEnd);o<a;o++){let l=e.coordsForChar(o);r=l&&new DOMRect(l.left,l.top,l.right-l.left,l.bottom-l.top)||r||new DOMRect,s.push(r)}t.updateCharacterBounds(i.rangeStart,s)},this.handlers.textformatupdate=i=>{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,a=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(r.rangeStart),c=this.toEditorPos(r.rangeEnd);if(l<c){let h=`text-decoration: underline ${/^[a-z]/.test(o)?o+" ":o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${/thin/i.test(a)?1:2}px`;s.push(B.mark({attributes:{style:h}}).range(l,c))}}}e.dispatch({effects:ru.of(B.set(s))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let s=kn(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,a,l,c)=>{if(i)return;let h=c.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(c)){s=this.pendingContextChange=null,t+=h,this.to+=h;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=h,this.to+=h;else if(r<this.to){if(r<this.from||o>this.to||this.to-this.from+c.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),c.toString()),this.to+=h}t+=h}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class ${get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Pp(e.parent)||document,this.viewState=new Wl(this,e.state||_.create(e)),e.scrollTo&&e.scrollTo.is(Nn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ti).map(s=>new Zr(s));for(let s of this.plugins)s.update(this);this.observer=new Gm(this),this.inputState=new Am(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Rl(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof Pe?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let f of e){if(f.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=f.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,a=0,l=null;e.some(f=>f.annotation(Su))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=xu(r,o),l||(a=1));let c=this.observer.delayedAndroidKey,h=null;if(c?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(h=null)):this.observer.clear(),r.facet(_.phrases)!=this.state.facet(_.phrases))return this.setState(r);s=Ks.create(this,r,e),s.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(u&&(u=u.map(f.changes)),f.scrollIntoView){let{main:d}=f.state.selection,{x:p,y:m}=this.state.facet($.cursorScrollMargin);u=new Ui(d.empty?d:A.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of f.effects)d.is(Nn)&&(u=d.value.clip(this.state))}this.viewState.update(s,u),this.bidiCache=Fs.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(hn)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(ts)!=s.state.facet(ts)&&(this.viewState.mustMeasureContent=!0),(t||i||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let f of this.state.facet(Fo))try{f(s)}catch(d){ze(this.state,d,"update listener")}(l||h)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),h&&!pu(this,h)&&c.force&&Ei(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Wl(this,e),this.plugins=e.facet(Ti).map(i=>new Zr(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new Rl(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ti),i=e.state.facet(Ti);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Zr(r));else{let a=this.plugins[o];a.mustUpdate=e,s.push(a)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s<this.plugins.length;s++)this.plugins[s].update(this);t!=i&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let t=e.value;if(t&&t.docViewUpdate)try{t.docViewUpdate(this)}catch(i){ze(this.state,i,"doc view update listener")}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(Ih(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let h=c.map(d=>{try{return d.read(this)}catch(p){return ze(this.state,p),Yl}}),u=Ks.create(this,this.state,[]),f=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),f=this.docView.update(u),f&&this.docViewUpdate());for(let d=0;d<c.length;d++)if(h[d]!=Yl)try{let p=c[d];p.write&&p.write(h[d],this)}catch(p){ze(this.state,p)}if(f&&this.docView.updateSelection(!0),!u.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,o=-1;continue}else{let p=((r<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(r).top)-o)/this.scaleY;if((p>1||p<-1)&&!(R.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Fo))a(t)}get themeClasses(){return Wo+" "+(this.state.facet(Io)?Qu:ku)+" "+this.state.facet(ts)}updateAttrs(){let e=Nl(this,ou,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Dt)?"true":"false",class:"cm-content",style:`${R.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Nl(this,xa,t);let i=this.observer.ignore(()=>{let s=wl(this.contentDOM,this.contentAttrs,t),r=wl(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is($.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(hn);let e=this.state.facet($.cspNonce);ei.mount(this.root,this.styleModules.concat(Nm).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.plugin!=e)&&this.pluginMap.set(e,t=this.plugins.find(i=>i.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Fr(this,e,$l(this,e,t,i))}moveByGroup(e,t){return Fr(this,e,$l(this,e,t,i=>cm(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return A.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return lm(this,e,t,i)}moveVertically(e,t,i){return Fr(this,e,hm(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=Xo(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),Xo(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),r=s[Ct.find(s,e-i.from,-1,t)];return this.docView.coordsAt(e,t,r.dir==fe.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(iu)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>eg)return Yh(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||jh(r.isolates,i=Pl(this,e))))return r.order;i||(i=Pl(this,e));let s=Ep(e.text,t,i);return this.bidiCache.push(new Fs(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||R.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Bh(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return Nn.of(new Ui(typeof e=="number"?A.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Nn.of(new Ui(A.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return xe.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return xe.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=ei.newName(),s=[ts.of(i),hn.of(qo(`.${i}`,e))];return t&&t.dark&&s.push(Io.of(!0)),s}static baseTheme(e){return ri.lowest(hn.of(qo("."+Wo,e,Pu)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&Se.get(i)||Se.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}}$.styleModule=hn;$.inputHandler=eu;$.clipboardInputFilter=ba;$.clipboardOutputFilter=Sa;$.scrollHandler=su;$.focusChangeEffect=tu;$.perLineTextDirection=iu;$.exceptionSink=Jh;$.updateListener=Fo;$.editable=Dt;$.mouseSelectionStyle=_h;$.dragMovesSelection=Gh;$.clickAddsSelectionRange=Hh;$.decorations=ur;$.blockWrappers=au;$.outerDecorations=va;$.atomicRanges=Dn;$.bidiIsolatedRanges=lu;$.cursorScrollMargin=K.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});$.scrollMargins=cu;$.darkTheme=Io;$.cspNonce=K.define({combine:n=>n.length?n[0]:""});$.contentAttributes=xa;$.editorAttributes=ou;$.lineWrapping=$.contentAttributes.of({class:"cm-lineWrapping"});$.announce=z.define();const eg=4096,Yl={};class Fs{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:fe.LTR;for(let r=Math.max(0,e.length-10);r<e.length;r++){let o=e[r];o.dir==s&&!t.touchesRange(o.from,o.to)&&i.push(new Fs(t.mapPos(o.from,1),t.mapPos(o.to,-1),o.dir,o.isolates,!1,o.order))}return i}}function Nl(n,e,t){for(let i=n.state.facet(e),s=i.length-1;s>=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Oa(o,t)}return t}const tg=R.mac?"mac":R.windows?"win":R.linux?"linux":"key";function ig(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,a;for(let l=0;l<t.length-1;++l){const c=t[l];if(/^(cmd|meta|m)$/i.test(c))a=!0;else if(/^a(lt)?$/i.test(c))s=!0;else if(/^(c|ctrl|control)$/i.test(c))r=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))e=="mac"?a=!0:r=!0;else throw new Error("Unrecognized modifier name: "+c)}return s&&(i="Alt-"+i),r&&(i="Ctrl-"+i),a&&(i="Meta-"+i),o&&(i="Shift-"+i),i}function is(n,e,t){return e.altKey&&(n="Alt-"+n),e.ctrlKey&&(n="Ctrl-"+n),e.metaKey&&(n="Meta-"+n),t!==!1&&e.shiftKey&&(n="Shift-"+n),n}const ng=ri.default($.domEventHandlers({keydown(n,e){return Tu(Cu(e.state),n,e,"editor")}})),mr=K.define({enables:ng}),Hl=new WeakMap;function Cu(n){let e=n.facet(mr),t=Hl.get(e);return t||Hl.set(e,t=og(e.reduce((i,s)=>i.concat(s),[]))),t}function sg(n,e,t){return Tu(Cu(n.state),e,n,t)}let Nt=null;const rg=4e3;function og(n,e=tg){let t=Object.create(null),i=Object.create(null),s=(o,a)=>{let l=i[o];if(l==null)i[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,a,l,c,h)=>{var u,f;let d=t[o]||(t[o]=Object.create(null)),p=a.split(/ (?!$)/).map(y=>ig(y,e));for(let y=1;y<p.length;y++){let b=p.slice(0,y).join(" ");s(b,!0),d[b]||(d[b]={preventDefault:!0,stopPropagation:!1,run:[x=>{let C=Nt={view:x,prefix:b,scope:o};return setTimeout(()=>{Nt==C&&(Nt=null)},rg),!0}]})}let m=p.join(" ");s(m,!1);let g=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((f=(u=d._any)===null||u===void 0?void 0:u.run)===null||f===void 0?void 0:f.slice())||[]});l&&g.run.push(l),c&&(g.preventDefault=!0),h&&(g.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let h=t[c]||(t[c]=Object.create(null));h._any||(h._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:u}=o;for(let f in h)h[f].run.push(d=>u(d,zo))}let l=o[e]||o.key;if(l)for(let c of a)r(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}let zo=null;function Tu(n,e,t,i){zo=e;let s=bp(e),r=Ne(s,0),o=Qt(r)==s.length&&s!=" ",a="",l=!1,c=!1,h=!1;Nt&&Nt.view==t&&Nt.scope==i&&(a=Nt.prefix+" ",Ou.indexOf(e.keyCode)<0&&(c=!0,Nt=null));let u=new Set,f=g=>{if(g){for(let y of g.run)if(!u.has(y)&&(u.add(y),y(t)))return g.stopPropagation&&(h=!0),!0;g.preventDefault&&(g.stopPropagation&&(h=!0),c=!0)}return!1},d=n[i],p,m;return d&&(f(d[a+is(s,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(R.windows&&e.ctrlKey&&e.altKey)&&!(R.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=ti[e.keyCode])&&p!=s?(f(d[a+is(p,e,!0)])||e.shiftKey&&(m=vn[e.keyCode])!=s&&m!=p&&f(d[a+is(m,e,!1)]))&&(l=!0):o&&e.shiftKey&&f(d[a+is(s,e,!0)])&&(l=!0),!l&&f(d._any)&&(l=!0)),c&&(l=!0),l&&h&&e.stopPropagation(),zo=null,l}class gi{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=Ru(e);return[new gi(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return ag(e,t,i)}}function Ru(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==fe.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function Gl(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,a=n.posAtCoords({x:r.left+1,y:o}),l=n.posAtCoords({x:r.right-1,y:o});return a==null||l==null?i:{from:Math.max(i.from,Math.min(a,l)),to:Math.min(i.to,Math.max(a,l))}}function ag(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==fe.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=Ru(n),c=o.querySelector(".cm-line"),h=c&&window.getComputedStyle(c),u=a.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),f=a.right-(h?parseInt(h.paddingRight):0),d=Lo(n,i,1),p=Lo(n,s,-1),m=d.type==Le.Text?d:null,g=p.type==Le.Text?p:null;if(m&&(n.lineWrapping||d.widgetLineBreaks)&&(m=Gl(n,i,1,m)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=Gl(n,s,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return b(x(t.from,t.to,m));{let k=m?x(t.from,null,m):C(d,!1),S=g?x(null,t.to,g):C(p,!0),w=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&k.bottom+n.defaultLineHeight/2<S.top?w.push(y(u,k.bottom,f,S.top)):k.bottom<S.top&&n.elementAtHeight((k.bottom+S.top)/2).type==Le.Text&&(k.bottom=S.top=(k.bottom+S.top)/2),b(k).concat(w).concat(b(S))}function y(k,S,w,U){return new gi(e,k-l.left,S-l.top,Math.max(0,w-k),U-S)}function b({top:k,bottom:S,horizontal:w}){let U=[];for(let F=0;F<w.length;F+=2)U.push(y(w[F],k,w[F+1],S));return U}function x(k,S,w){let U=1e9,F=-1e9,V=[];function E(Q,D,P,j,ae){let J=n.coordsAtPos(Q,Q==w.to?-2:2),ee=n.coordsAtPos(P,P==w.from?2:-2);!J||!ee||(U=Math.min(J.top,ee.top,U),F=Math.max(J.bottom,ee.bottom,F),ae==fe.LTR?V.push(r&&D?u:J.left,r&&j?f:ee.right):V.push(!r&&j?u:ee.left,!r&&D?f:J.right))}let M=k??w.from,Y=S??w.to;for(let Q of n.visibleRanges)if(Q.to>M&&Q.from<Y)for(let D=Math.max(Q.from,M),P=Math.min(Q.to,Y);;){let j=n.state.doc.lineAt(D);for(let ae of n.bidiSpans(j)){let J=ae.from+j.from,ee=ae.to+j.from;if(J>=P)break;ee>D&&E(Math.max(J,D),k==null&&J<=M,Math.min(ee,P),S==null&&ee>=Y,ae.dir)}if(D=j.to+1,D>=P)break}return V.length==0&&E(M,k==null,Y,S==null,n.textDirection),{top:U,bottom:F,horizontal:V}}function C(k,S){let w=a.top+(S?k.top:k.bottom);return{top:w,bottom:w,horizontal:[]}}}function lg(n,e){return n.constructor==e.constructor&&n.eq(e)}class cg{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(bs)!=e.state.facet(bs)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(bs);for(;t<i.length&&i[t]!=this.layer;)t++;this.dom.style.zIndex=String((this.layer.above?150:-1)-t)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:t}=this.view;(e!=this.scaleX||t!=this.scaleY)&&(this.scaleX=e,this.scaleY=t,this.dom.style.transform=`scale(${1/e}, ${1/t})`)}draw(e){if(e.length!=this.drawn.length||e.some((t,i)=>!lg(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,R.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const bs=K.define();function $u(n){return[xe.define(e=>new cg(e,n)),bs.of(n)]}const zi=K.define({combine(n){return yt(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function hg(n={}){return[zi.of(n),ug,fg,pg,nu.of(!0)]}function Ku(n){return n.startState.facet(zi)!=n.state.facet(zi)}const ug=$u({above:!0,markers(n){let{state:e}=n,t=e.facet(zi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&R.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=s.empty?s:A.cursor(s.head,s.assoc);for(let l of gi.forRange(n,o,a))i.push(l)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Ku(n);return t&&_l(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){_l(e.state,n)},class:"cm-cursorLayer"});function _l(n,e){e.style.animationDuration=n.facet(zi).cursorBlinkRate+"ms"}const fg=$u({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of gi.forRange(n,"cm-selectionBackground",s))e.push(r);if(R.ios&&!t.empty&&n.state.facet(zi).iosSelectionHandles){for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-start",A.cursor(t.from,1)))e.push(s);for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-end",A.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Ku(n)},class:"cm-selectionLayer"}),dg=R.gecko&&R.gecko_version==153?"#ffffff01":"transparent",pg=ri.highest($.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${dg} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Zu=z.define({map(n,e){return n==null?null:e.mapPos(n)}}),fn=Te.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(Zu)?i.value:t,n)}}),mg=xe.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(fn);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(fn)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(fn),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(fn)!=n&&this.view.dispatch({effects:Zu.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function gg(){return[fn,mg]}function Jl(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,a;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;a=e.exec(r.value);)s(o+a.index,a)}function Og(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}class yg{constructor(e){const{regexp:t,decoration:i,decorate:s,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,s)this.addMatch=(a,l,c,h)=>s(h,c,c+a[0].length,a,l);else if(typeof i=="function")this.addMatch=(a,l,c,h)=>{let u=i(a,l,c);u&&h(c,c+a[0].length,u)};else if(i)this.addMatch=(a,l,c,h)=>h(c,c+a[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new Bt,i=t.add.bind(t);for(let{from:s,to:r}of Og(e,this.maxLength))Jl(e.state.doc,this.regexp,s,r,(o,a)=>this.addMatch(a,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,a,l)=>{l>=e.view.viewport.from&&a<=e.view.viewport.to&&(i=Math.min(a,i),s=Math.max(l,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),a=Math.min(r.to,s);if(a>=o){let l=e.state.doc.lineAt(o),c=l.to<a?e.state.doc.lineAt(a):l,h=Math.max(r.from,l.from),u=Math.min(r.to,c.to);if(this.boundary){for(;o>l.from;o--)if(this.boundary.test(l.text[o-1-l.from])){h=o;break}for(;a<c.to;a++)if(this.boundary.test(c.text[a-c.from])){u=a;break}}let f=[],d,p=(m,g,y)=>f.push(y.range(m,g));if(l==c)for(this.regexp.lastIndex=h-l.from;(d=this.regexp.exec(l.text))&&d.index<u-l.from;)this.addMatch(d,e,d.index+l.from,p);else Jl(e.state.doc,this.regexp,h,u,(m,g)=>this.addMatch(g,e,m,p));t=t.update({filterFrom:h,filterTo:u,filter:(m,g)=>m<h||g>u,add:f})}}return t}}const Vo=/x/.unicode!=null?"gu":"g",Ag=new RegExp(`[\0-\b ---Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,Vo),bg={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Xr=null;function Sg(){var n;if(Xr==null&&typeof document<"u"&&document.body){let e=document.body.style;Xr=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Xr||!1}const Ss=K.define({combine(n){let e=yt(n,{render:null,specialChars:Ag,addSpecialChars:null});return(e.replaceTabs=!Sg())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Vo)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Vo)),e}});function xg(n={}){return[Ss.of(n),vg()]}let ec=null;function vg(){return ec||(ec=xe.fromClass(class{constructor(n){this.view=n,this.decorations=B.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(Ss)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new yg({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=Ne(e[0],0);if(r==9){let o=s.lineAt(i),a=t.state.tabSize,l=_i(o.text,a,i-o.from);return B.replace({widget:new Pg((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=B.replace({widget:new Qg(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(Ss);n.startState.facet(Ss)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const wg="•";function kg(n){return n>=32?wg:n==10?"␤":String.fromCharCode(9216+n)}class Qg extends Ut{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=kg(this.code),i=e.state.phrase("Control character")+" "+(bg[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}}class Pg extends Ut{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Cg(){return Rg}const Tg=B.line({class:"cm-activeLine"}),Rg=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(Tg.range(s.from)),e=s.from)}return B.set(t)}},{decorations:n=>n.decorations}),jo=2e3;function $g(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>jo||t.off>jo||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=i;l<=s;l++){let c=n.doc.line(l);c.length<=a&&r.push(A.range(c.from+o,c.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=i;l<=s;l++){let c=n.doc.line(l),h=Qo(c.text,o,n.tabSize,!0);if(h<0)r.push(A.cursor(c.to));else{let u=Qo(c.text,a,n.tabSize);r.push(A.range(c.from+h,c.from+u))}}}return r}function Kg(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function tc(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>jo?-1:s==i.length?Kg(n,e.clientX):_i(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function Zg(n,e){let t=tc(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let a=tc(n,s);if(!a)return i;let l=$g(n.state,t,a);return l.length?o?A.create(l.concat(i.ranges)):A.create(l):i}}:null}function Mg(n){let e=(t=>t.altKey&&t.button==0);return $.mouseSelectionStyle.of((t,i)=>e(i)?Zg(t,i):null)}const Eg={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},Ug={style:"cursor: crosshair"};function Fg(n={}){let[e,t]=Eg[n.key||"Alt"],i=xe.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,$.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?Ug:null})]}const ns="-10000px";class Mu{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(l=>l);if(s===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;l<r.length;l++){let c=r[l],h=-1;if(c){for(let u=0;u<this.tooltips.length;u++){let f=this.tooltips[u];f&&f.create==c.create&&(h=u)}if(h<0)o[l]=this.createTooltipView(c,l?o[l-1]:null),a&&(a[l]=!!c.above);else{let u=o[l]=this.tooltipViews[h];a&&(a[l]=t[h]),u.update&&u.update(e)}}}for(let l of this.tooltipViews)o.indexOf(l)<0&&(this.removeTooltipView(l),(i=l.destroy)===null||i===void 0||i.call(l));return t&&(a.forEach((l,c)=>t[c]=l),t.length=a.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}}function Dg(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const Br=K.define({combine:n=>{var e,t,i;return{position:R.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||Dg}}}),ic=new WeakMap,Ca=xe.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Br);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new Mu(n,gr,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Br);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=ns,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(R.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=wa(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let a=this.manager.tooltipViews[o];return a.getCoords?a.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Br).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let a=0;a<this.manager.tooltips.length;a++){let l=this.manager.tooltips[a],c=this.manager.tooltipViews[a],{dom:h}=c,u=n.pos[a],f=n.size[a];if(!u||l.clip!==!1&&(u.bottom<=Math.max(t.top,i.top)||u.top>=Math.min(t.bottom,i.bottom)||u.right<Math.max(t.left,i.left)-.1||u.left>Math.min(t.right,i.right)+.1)){h.style.top=ns;continue}let d=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=f.right-f.left,g=(e=ic.get(c))!==null&&e!==void 0?e:f.bottom-f.top,y=c.offset||Xg,b=this.view.textDirection==fe.LTR,x=f.width>i.right-i.left?b?i.left:i.right-f.width:b?Math.max(i.left,Math.min(u.left-(d?14:0)+y.x,i.right-m)):Math.min(Math.max(i.left,u.left-m+(d?14:0)-y.x),i.right-m),C=this.above[a];!l.strictSide&&(C?u.top-g-p-y.y<i.top:u.bottom+g+p+y.y>i.bottom)&&C==i.bottom-u.bottom>u.top-i.top&&(C=this.above[a]=!C);let k=(C?u.top-i.top:i.bottom-u.bottom)-p;if(k<g&&c.resize!==!1){if(k<this.view.defaultLineHeight){h.style.top=ns;continue}ic.set(c,g),h.style.height=(g=k)/r+"px"}else h.style.height&&(h.style.height="");let S=C?u.top-g-p-y.y:u.bottom+p+y.y,w=x+m;if(c.overlap!==!0)for(let U of o)U.left<w&&U.right>x&&U.top<S+g&&U.bottom>S&&(S=C?U.top-g-2-p:U.bottom+p+2);if(this.position=="absolute"?(h.style.top=(S-n.parent.top)/r+"px",nc(h,(x-n.parent.left)/s)):(h.style.top=S/r+"px",nc(h,x/s)),d){let U=u.left+(b?y.x:-y.x)-(x+14-7);d.style.left=U/s+"px"}c.overlap!==!0&&o.push({left:x,top:S,right:w,bottom:S+g}),h.classList.toggle("cm-tooltip-above",C),h.classList.toggle("cm-tooltip-below",!C),c.positioned&&c.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=ns}},{eventObservers:{scroll(){this.maybeMeasure()}}});function nc(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}const Lg=$.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Xg={x:0,y:0},gr=K.define({enables:[Ca,Lg]}),Ds=K.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])});class Or{static create(e){return new Or(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Mu(e,Ds,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Bg=gr.compute([Ds],n=>{let e=n.facet(Ds);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:Or.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),Ig=K.define();class Wg{constructor(e,t,i,s,r,o){this.view=e,this.source=t,this.field=i,this.locked=s,this.setHover=r,this.hoverTime=o,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;e<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-e):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:e,lastMove:t}=this,i=e.docView.tile.nearest(t.target);if(!i)return;let s,r=1;if(i.isWidget())s=i.posAtStart;else{if(s=e.posAtCoords(t),s==null)return;let o=e.coordsAtPos(s);if(!o||t.y<o.top||t.y>o.bottom||t.x<o.left-e.defaultCharacterWidth||t.x>o.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(s)).find(c=>c.from<=s&&c.to>=s),l=a&&a.dir==fe.RTL?-1:1;r=t.x<o.left?-l:l}this.activateHover(e,s,r)}activateHover(e,t,i,s){let r=this.source(e,t,i),o=a=>{if(a&&!(Array.isArray(a)&&!a.length)){let l=Array.isArray(a)?a:[a];s&&this.locked.set(l,s),e.dispatch({effects:this.setHover.of(l)})}};if(r&&"then"in r){let a=this.pending={pos:t};r.then(l=>{this.pending==a&&(this.pending=null,o(l))},l=>ze(e.state,l,"hover tooltip"))}else o(r)}get tooltip(){let e=this.view.plugin(Ca),t=e?e.manager.tooltips.findIndex(i=>i.create==Or.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:s,tooltip:r}=this;if(s.length&&!this.locked.has(s)&&r&&!qg(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,a=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==a?this.view.posAtCoords(this.lastMove)!=o:!zg(this.view,o,a,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t);let{active:s}=this;s.length&&!this.locked.has(s)&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const ss=4;function qg(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let a=o.getBoundingClientRect();s=Math.min(a.top,s),r=Math.max(a.bottom,r)}return e.clientX>=t-ss&&e.clientX<=i+ss&&e.clientY>=s-ss&&e.clientY<=r+ss}function zg(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),a=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.right<i||o.top>s||Math.min(o.bottom,a)<s)return!1;let l=n.posAtCoords({x:i,y:s},!1);return l>=e&&l<=t}function Eu(n,e={}){let t=z.define(),i=new WeakMap,s=Te.define({create(){return[]},update(o,a){let l=i.get(o);if(o.length&&(e.hideOnChange&&(a.docChanged||a.selection)?o=[]:l&&l(a)?o=[]:e.hideOn&&(o=o.filter(c=>!e.hideOn(a,c)))),a.docChanged&&o.length){let c=[];for(let h of o){let u=a.changes.mapPos(h.pos,-1,De.TrackDel);if(u!=null){let f=Object.assign(Object.create(null),h);f.pos=u,f.end!=null&&(f.end=a.changes.mapPos(f.end)),c.push(f)}}o=c}for(let c of a.effects)c.is(t)&&(o=c.value,l=void 0),(c.is(Vg)&&!c.value||c.value==s)&&(o=[]);return o.length&&l&&i.set(o,l),o},provide:o=>Ds.from(o)});const r=xe.define(o=>new Wg(o,n,s,i,t,e.hoverTime||300));return{active:s,extension:[s,r,Ig.of(r),Bg]}}function Uu(n,e){let t=n.plugin(Ca);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const Vg=z.define(),sc=K.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Fu(n,e){let t=n.plugin(Du),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Du=xe.fromClass(class{constructor(n){this.input=n.state.facet(Vi),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(sc);this.top=new rs(n,!0,e.topContainer),this.bottom=new rs(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(sc);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new rs(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new rs(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Vi);if(t!=this.input){let i=t.filter(l=>l),s=[],r=[],o=[],a=[];for(let l of i){let c=this.specs.indexOf(l),h;c<0?(h=l(n.view),a.push(h)):(h=this.panels[c],h.update&&h.update(n)),s.push(h),(h.top?r:o).push(h)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>$.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class rs{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=rc(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=rc(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function rc(n){let e=n.nextSibling;return n.remove(),e}const Vi=K.define({enables:Du});function jg(n,e){let t,i=new Promise(o=>t=o),s=o=>Yg(o,e,t);n.state.field(Ir,!1)?n.dispatch({effects:Lu.of(s)}):n.dispatch({effects:z.appendConfig.of(Ir.init(()=>[s]))});let r=Xu.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(l=>n.win.setTimeout(l,10)))(()=>{n.state.field(Ir).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}const Ir=Te.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(Lu)?n=[t.value].concat(n):t.is(Xu)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>Vi.computeN([n],e=>e.field(n))}),Lu=z.define(),Xu=z.define();function Yg(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=he("form"),e.input){let a=he("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),i.appendChild(he("label",(e.label||"")+": ",a))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(he("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let a=0;a<s.length;a++){let l=s[a];l.addEventListener("keydown",c=>{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let r=he("div",i,he("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(a){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(a)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=i.querySelector(e.focus):a=i.querySelector("input")||i.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}class Mt extends Jt{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Mt.prototype.elementClass="";Mt.prototype.toDOM=void 0;Mt.prototype.mapMode=De.TrackBefore;Mt.prototype.startSide=Mt.prototype.endSide=-1;Mt.prototype.point=!0;const xs=K.define(),Ng=K.define(),Hg={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>N.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},An=K.define();function Bu(n){return[Iu(),An.of({...Hg,...n})]}const oc=K.define({combine:n=>n.some(e=>e)});function Iu(n){return[Gg]}const Gg=xe.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(An).map(e=>new lc(n,e)),this.fixed=!n.state.facet(oc);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(oc)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=N.iter(this.view.state.facet(xs),this.view.viewport.from),i=[],s=this.gutters.map(r=>new _g(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let a of r.type)if(a.type==Le.Text&&o){Yo(t,i,a.from);for(let l of s)l.line(this.view,a,i);o=!1}else if(a.widget)for(let l of s)l.widget(this.view,a)}else if(r.type==Le.Text){Yo(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(An),t=n.state.facet(An),i=n.docChanged||n.heightChanged||n.viewportChanged||!N.eq(n.startState.facet(xs),n.state.facet(xs),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new lc(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>$.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==fe.LTR?{left:i,right:s}:{right:i,left:s}})});function ac(n){return Array.isArray(n)?n:[n]}function Yo(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class _g{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=N.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let a=new Wu(e,o,r,i);s.elements.push(a),s.dom.appendChild(a.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Yo(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(Ng)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class lc{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let l=r.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=s.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,a,s)&&s.preventDefault()});this.markers=ac(t.markers(e)),t.initialSpacer&&(this.spacer=new Wu(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=ac(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!N.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class Wu{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),Jg(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let a=o,l=r<t.length?t[r++]:null,c=!1;if(l){let h=l.elementClass;h&&(i+=" "+h);for(let u=o;u<this.markers.length;u++)if(this.markers[u].compare(l)){a=u,c=!0;break}}else a=this.markers.length;for(;o<a;){let h=this.markers[o++];if(h.toDOM){h.destroy(s);let u=s.nextSibling;s.remove(),s=u}}if(!l)break;l.toDOM&&(c?s=s.nextSibling:this.dom.insertBefore(l.toDOM(e),s)),c&&o++}this.dom.className=i,this.markers=t}destroy(){this.setMarkers(null,[])}}function Jg(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++)if(!n[t].compare(e[t]))return!1;return!0}const eO=K.define(),tO=K.define(),Ri=K.define({combine(n){return yt(n,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,t){let i=Object.assign({},e);for(let s in t){let r=i[s],o=t[s];i[s]=r?(a,l,c)=>r(a,l,c)||o(a,l,c):o}return i}})}});class Wr extends Mt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function qr(n,e){return n.state.facet(Ri).formatNumber(e,n.state)}const iO=An.compute([Ri],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(eO)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new Wr(qr(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(tO)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(Ri)!=e.state.facet(Ri),initialSpacer(e){return new Wr(qr(e,cc(e.state.doc.lines)))},updateSpacer(e,t){let i=qr(t.view,cc(t.view.state.doc.lines));return i==e.number?e:new Wr(i)},domEventHandlers:n.facet(Ri).domEventHandlers,side:"before"}));function nO(n={}){return[Ri.of(n),Iu(),iO]}function cc(n){let e=9;for(;e<n;)e=e*10+9;return e}const sO=new class extends Mt{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},rO=xs.compute(["selection"],n=>{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(sO.range(s)))}return N.of(e)});function oO(){return rO}const qu=1024;let aO=0;class zr{constructor(e,t){this.from=e,this.to=t}}class G{constructor(e={}){this.id=aO++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=et.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}G.closedBy=new G({deserialize:n=>n.split(" ")});G.openedBy=new G({deserialize:n=>n.split(" ")});G.group=new G({deserialize:n=>n.split(" ")});G.isolate=new G({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});G.contextHash=new G({perNode:!0});G.lookAhead=new G({perNode:!0});G.mounted=new G({perNode:!0});class bn{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[G.mounted.id]}}const lO=Object.create(null);class et{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):lO,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new et(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(G.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(G.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}}et.none=new et("",Object.create(null),0,8);class Ta{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let t=[];for(let i of this.types){let s=null;for(let r of e){let o=r(i);if(o){s||(s=Object.assign({},i.props));let a=o[1],l=o[0];l.combine&&l.id in s&&(a=l.combine(s[l.id],a)),s[l.id]=a}}t.push(s?new et(i.name,s,i.id,i.flags):i)}return new Ta(t)}}const os=new WeakMap,hc=new WeakMap;var be;(function(n){n[n.ExcludeBuffers=1]="ExcludeBuffers",n[n.IncludeAnonymous=2]="IncludeAnonymous",n[n.IgnoreMounts=4]="IgnoreMounts",n[n.IgnoreOverlays=8]="IgnoreOverlays",n[n.EnterBracketed=16]="EnterBracketed"})(be||(be={}));class ke{constructor(e,t,i,s,r){if(this.type=e,this.children=t,this.positions=i,this.length=s,this.props=null,r&&r.length){this.props=Object.create(null);for(let[o,a]of r)this.props[typeof o=="number"?o:o.id]=a}}toString(){let e=bn.get(this);if(e&&!e.overlay)return e.tree.toString();let t="";for(let i of this.children){let s=i.toString();s&&(t&&(t+=","),t+=s)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}cursor(e=0){return new Ho(this.topNode,e)}cursorAt(e,t=0,i=0){let s=os.get(this)||this.topNode,r=new Ho(s);return r.moveTo(e,t),os.set(this,r._tree),r}get topNode(){return new Je(this,0,0,null)}resolve(e,t=0){let i=Pn(os.get(this)||this.topNode,e,t,!1);return os.set(this,i),i}resolveInner(e,t=0){let i=Pn(hc.get(this)||this.topNode,e,t,!0);return hc.set(this,i),i}resolveStack(e,t=0){return uO(this,e,t)}iterate(e){let{enter:t,leave:i,from:s=0,to:r=this.length}=e,o=e.mode||0,a=(o&be.IncludeAnonymous)>0;for(let l=this.cursor(o|be.IncludeAnonymous);;){let c=!1;if(l.from<=r&&l.to>=s&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&i&&(a||!l.type.isAnonymous)&&i(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Ka(et.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new ke(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new ke(et.none,t,i,s)))}static build(e){return fO(e)}}ke.empty=new ke(et.none,[],[],0);class Ra{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Ra(this.buffer,this.index)}}class ni{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return et.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],i=this.buffer[e+3],s=this.set.types[t],r=s.name;if(/\W/.test(r)&&!s.isError&&(r=JSON.stringify(r)),e+=4,i==e)return r;let o=[];for(;e<i;)o.push(this.childString(e)),e=this.buffer[e+3];return r+"("+o.join(",")+")"}findChild(e,t,i,s,r){let{buffer:o}=this,a=-1;for(let l=e;l!=t&&!(zu(r,s,o[l+1],o[l+2])&&(a=l,i>0));l=o[l+3]);return a}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let a=e,l=0;a<t;){r[l++]=s[a++],r[l++]=s[a++]-i;let c=r[l++]=s[a++]-i;r[l++]=s[a++]-e,o=Math.max(o,c)}return new ni(r,o,this.set)}}function zu(n,e,t,i){switch(n){case-2:return t<e;case-1:return i>=e&&t<e;case 0:return t<e&&i>e;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Pn(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to<e);){let o=!i&&n instanceof Je&&n.index<0?null:n.parent;if(!o)return n;n=o}let r=i?0:be.IgnoreOverlays;if(i)for(let o=n,a=o.parent;a;o=a,a=o.parent)o instanceof Je&&o.index<0&&((s=a.enter(e,t,r))===null||s===void 0?void 0:s.from)!=o.from&&(n=a);for(;;){let o=n.enter(e,t,r);if(!o)return n;n=o}}class Vu{cursor(e=0){return new Ho(this,e)}getChild(e,t=null,i=null){let s=uc(this,e,t,i);return s.length?s[0]:null}getChildren(e,t=null,i=null){return uc(this,e,t,i)}resolve(e,t=0){return Pn(this,e,t,!1)}resolveInner(e,t=0){return Pn(this,e,t,!0)}matchContext(e){return No(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),i=this;for(;t;){let s=t.lastChild;if(!s||s.to!=t.to)break;s.type.isError&&s.from==s.to?(i=t,t=s.prevSibling):t=s}return i}get node(){return this}get next(){return this.parent}}class Je extends Vu{constructor(e,t,i,s){super(),this._tree=e,this.from=t,this.index=i,this._parent=s}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,t,i,s,r=0){for(let o=this;;){for(let{children:a,positions:l}=o._tree,c=t>0?a.length:-1;e!=c;e+=t){let h=a[e],u=l[e]+o.from,f;if(!(!(r&be.EnterBracketed&&h instanceof ke&&(f=bn.get(h))&&!f.overlay&&f.bracketed&&i>=u&&i<=u+h.length)&&!zu(s,i,u,u+h.length))){if(h instanceof ni){if(r&be.ExcludeBuffers)continue;let d=h.findChild(0,h.buffer.length,t,i-u,s);if(d>-1)return new Tt(new cO(o,h,e,u),null,d)}else if(r&be.IncludeAnonymous||!h.type.isAnonymous||$a(h)){let d;if(!(r&be.IgnoreMounts)&&(d=bn.get(h))&&!d.overlay)return new Je(d.tree,u,e,o);let p=new Je(h,u,e,o);return r&be.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?h.children.length-1:0,t,i,s,r)}}}if(r&be.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&be.IgnoreOverlays)&&(s=bn.get(this._tree))&&s.overlay){let r=e-this.from,o=i&be.EnterBracketed&&s.bracketed;for(let{from:a,to:l}of s.overlay)if((t>0||o?a<=r:a<r)&&(t<0||o?l>=r:l>r))return new Je(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function uc(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function No(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class cO{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}}class Tt extends Vu{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new Tt(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&be.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new Tt(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Tt(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new Tt(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new ke(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function ju(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;r<n.length;r++){let o=n[r];(o.from>t.from||o.to<t.to)&&(t=o,e=r)}let i=t instanceof Je&&t.index<0?null:t.parent,s=n.slice();return i?s[e]=i:s.splice(e,1),new hO(s,t)}class hO{constructor(e,t){this.heads=e,this.node=t}get next(){return ju(this.heads)}}function uO(n,e,t){let i=n.resolveInner(e,t),s=null;for(let r=i instanceof Je?i:i.context.parent;r;r=r.parent)if(r.index<0){let o=r.parent;(s||(s=[i])).push(o.resolve(e,t)),r=o}else{let o=bn.get(r.tree);if(o&&o.overlay&&o.overlay[0].from<=e&&o.overlay[o.overlay.length-1].to>=e){let a=new Je(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(Pn(a,e,t,!1))}}return s?ju(s):i}class Ho{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~be.EnterBracketed,e instanceof Je)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof Je?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&be.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&be.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&be.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index<s.buffer.buffer.length)return!1}else for(let r=0;r<this.index;r++)if(s.buffer.buffer[r+3]<this.index)return!1;({index:t,parent:i}=s)}else({index:t,_parent:i}=this._tree);for(;i;{index:t,_parent:i}=i)if(t>-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let a=i._tree.children[r];if(this.mode&be.IncludeAnonymous||a instanceof ni||!a.type.isAnonymous||$a(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,i=0;if(e&&e.context==this.buffer)e:for(let s=this.index,r=this.stack.length;r>=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s<this.stack.length;s++)t=new Tt(this.buffer,t,this.stack[s]);return this.bufferNode=new Tt(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let i=0;;){let s=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){i++;continue}this.type.isAnonymous||(s=!0)}for(;;){if(s&&t&&t(this),s=this.type.isAnonymous,!i)return;if(this.nextSibling())break;this.parent(),i--,s=!0}}}matchContext(e){if(!this.buffer)return No(this.node.parent,e);let{buffer:t}=this.buffer,{types:i}=t.set;for(let s=e.length-1,r=this.stack.length-1;s>=0;r--){if(r<0)return No(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}}function $a(n){return n.children.some(e=>e instanceof ni||!e.type.isAnonymous||$a(e))}function fO(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=qu,reused:r=[],minRepeatType:o=i.types.length}=n,a=Array.isArray(t)?new Ra(t,t.length):t,l=i.types,c=0,h=0;function u(k,S,w,U,F,V){let{id:E,start:M,end:Y,size:Q}=a,D=h,P=c;if(Q<0)if(a.next(),Q==-1){let I=r[E];w.push(I),U.push(M-k);return}else if(Q==-3){c=E;return}else if(Q==-4){h=E;return}else throw new RangeError(`Unrecognized record size: ${Q}`);let j=l[E],ae,J,ee=M-k;if(Y-M<=s&&(J=g(a.pos-S,F))){let I=new Uint16Array(J.size-J.skip),H=a.pos-J.size,ce=I.length;for(;a.pos>H;)ce=y(J.start,I,ce);ae=new ni(I,Y-J.start,i),ee=J.start-k}else{let I=a.pos-Q;a.next();let H=[],ce=[],W=E>=o?E:-1,te=0,re=Y;for(;a.pos>I;)W>=0&&a.id==W&&a.size>=0?(a.end<=re-s&&(p(H,ce,M,te,a.end,re,W,D,P),te=H.length,re=a.end),a.next()):V>2500?f(M,I,H,ce):u(M,I,H,ce,W,V+1);if(W>=0&&te>0&&te<H.length&&p(H,ce,M,te,M,re,W,D,P),H.reverse(),ce.reverse(),W>-1&&te>0){let Me=d(j,P);ae=Ka(j,H,ce,0,H.length,0,Y-M,Me,Me)}else ae=m(j,H,ce,Y-M,D-Y,P)}w.push(ae),U.push(ee)}function f(k,S,w,U){let F=[],V=0,E=-1;for(;a.pos>S;){let{id:M,start:Y,end:Q,size:D}=a;if(D>4)a.next();else{if(E>-1&&Y<E)break;E<0&&(E=Q-s),F.push(M,Y,Q),V++,a.next()}}if(V){let M=new Uint16Array(V*4),Y=F[F.length-2];for(let Q=F.length-3,D=0;Q>=0;Q-=3)M[D++]=F[Q],M[D++]=F[Q+1]-Y,M[D++]=F[Q+2]-Y,M[D++]=D;w.push(new ni(M,F[2]-Y,i)),U.push(Y-k)}}function d(k,S){return(w,U,F)=>{let V=0,E=w.length-1,M,Y;if(E>=0&&(M=w[E])instanceof ke){if(!E&&M.type==k&&M.length==F)return M;(Y=M.prop(G.lookAhead))&&(V=U[E]+M.length+Y)}return m(k,w,U,F,V,S)}}function p(k,S,w,U,F,V,E,M,Y){let Q=[],D=[];for(;k.length>U;)Q.push(k.pop()),D.push(S.pop()+w-F);k.push(m(i.types[E],Q,D,V-F,M-V,Y)),S.push(F-w)}function m(k,S,w,U,F,V,E){if(V){let M=[G.contextHash,V];E=E?[M].concat(E):[M]}if(F>25){let M=[G.lookAhead,F];E=E?[M].concat(E):[M]}return new ke(k,S,w,U,E)}function g(k,S){let w=a.fork(),U=0,F=0,V=0,E=w.end-s,M={size:0,start:0,skip:0};e:for(let Y=w.pos-k;w.pos>Y;){let Q=w.size;if(w.id==S&&Q>=0){M.size=U,M.start=F,M.skip=V,V+=4,U+=4,w.next();continue}let D=w.pos-Q;if(Q<0||D<Y||w.start<E)break;let P=w.id>=o?4:0,j=w.start;for(w.next();w.pos>D;){if(w.size<0)if(w.size==-3||w.size==-4)P+=4;else break e;else w.id>=o&&(P+=4);w.next()}F=j,U+=Q,V+=P}return(S<0||U==k)&&(M.size=U,M.start=F,M.skip=V),M.size>4?M:void 0}function y(k,S,w){let{id:U,start:F,end:V,size:E}=a;if(a.next(),E>=0&&U<o){let M=w;if(E>4){let Y=a.pos-(E-4);for(;a.pos>Y;)w=y(k,S,w)}S[--w]=M,S[--w]=V-k,S[--w]=F-k,S[--w]=U}else E==-3?c=U:E==-4&&(h=U);return w}let b=[],x=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,b,x,-1,0);let C=(e=n.length)!==null&&e!==void 0?e:b.length?x[0]+b[0].length:0;return new ke(l[n.topID],b.reverse(),x.reverse(),C)}const fc=new WeakMap;function vs(n,e){if(!n.isAnonymous||e instanceof ni||e.type!=n)return 1;let t=fc.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof ke)){t=1;break}t+=vs(n,i)}fc.set(e,t)}return t}function Ka(n,e,t,i,s,r,o,a,l){let c=0;for(let p=i;p<s;p++)c+=vs(n,e[p]);let h=Math.ceil(c*1.5/8),u=[],f=[];function d(p,m,g,y,b){for(let x=g;x<y;){let C=x,k=m[x],S=vs(n,p[x]);for(x++;x<y;x++){let w=vs(n,p[x]);if(S+w>=h)break;S+=w}if(x==C+1){if(S>h){let w=p[C];d(w.children,w.positions,0,w.children.length,m[C]+b);continue}u.push(p[C])}else{let w=m[x-1]+p[x-1].length-k;u.push(Ka(n,p,m,C,x,k,w,null,l))}f.push(k+b-r)}}return d(e,t,i,s,0),(a||l)(u,f,o)}class dO{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Tt?this.setBuffer(e.context.buffer,e.index,t):e instanceof Je&&this.map.set(e.tree,t)}get(e){return e instanceof Tt?this.getBuffer(e.context.buffer,e.index):e instanceof Je?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Oi{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new Oi(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let h=a<t.length?t[a]:null,u=h?h.fromA:1e9;if(u-l>=i)for(;o&&o.from<u;){let f=o;if(l>=f.from||u<=f.to||c){let d=Math.max(f.from,l)-c,p=Math.min(f.to,u)-c;f=d>=p?null:new Oi(d,p,f.tree,f.offset+c,a>0,!!h)}if(f&&s.push(f),o.to>u)break;o=r<e.length?e[r++]:null}if(!h)break;l=h.toA,c=h.toA-h.toB}return s}}class Yu{startParse(e,t,i){return typeof e=="string"&&(e=new pO(e)),i=i?i.length?i.map(s=>new zr(s.from,s.to)):[new zr(0,0)]:[new zr(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}}class pO{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new G({perNode:!0});let mO=0;class lt{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=mO++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof lt&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new lt(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new Ls(e);return i=>i.modified.indexOf(t)>-1?i:Ls.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}}let gO=0;class Ls{constructor(e){this.name=e,this.instances=[],this.id=gO++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(a=>a.base==e&&OO(t,a.modified));if(i)return i;let s=[],r=new lt(e.name,s,e,t);for(let a of t)a.instances.push(r);let o=yO(t);for(let a of e.set)if(!a.modified.length)for(let l of o)s.push(Ls.get(a,l));return r}}function OO(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function yO(n){let e=[[]];for(let t=0;t<n.length;t++)for(let i=0,s=e.length;i<s;i++)e.push(e[i].concat(n[t]));return e.sort((t,i)=>i.length-t.length)}function Nu(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,a=s;for(let u=0;;){if(a=="..."&&u>0&&u+3==s.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!f)throw new RangeError("Invalid path: "+s);if(r.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),u+=f[0].length,u==s.length)break;let d=s[u++];if(u==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);a=s.slice(u)}let l=r.length-1,c=r[l];if(!c)throw new RangeError("Invalid path: "+s);let h=new Cn(i,o,l>0?r.slice(0,l):null);e[c]=h.sort(e[c])}}return Hu.add(e)}const Hu=new G({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Cn(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}});class Cn{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}}Cn.empty=new Cn([],2,null);function Gu(n,e){let t=Object.create(null);for(let r of n)if(!Array.isArray(r.tag))t[r.tag.id]=r.class;else for(let o of r.tag)t[o.id]=r.class;let{scope:i,all:s=null}=e||{};return{style:r=>{let o=s;for(let a of r)for(let l of a.set){let c=t[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:i}}function AO(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function bO(n,e,t,i=0,s=n.length){let r=new SO(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}class SO{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:a,to:l}=e;if(a>=i||l<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let c=s,h=xO(e)||Cn.empty,u=AO(r,h.tags);if(u&&(c&&(c+=" "),c+=u,h.mode==1&&(s+=(s?" ":"")+u)),this.startSpan(Math.max(t,a),c),h.opaque)return;let f=e.tree&&e.tree.prop(G.mounted);if(f&&f.overlay){let d=e.node.enter(f.overlay[0].from+a,1),p=this.highlighters.filter(g=>!g.scope||g.scope(f.tree.type)),m=e.firstChild();for(let g=0,y=a;;g++){let b=g<f.overlay.length?f.overlay[g]:null,x=b?b.from+a:l,C=Math.max(t,y),k=Math.min(i,x);if(C<k&&m)for(;e.from<k&&(this.highlightRange(e,C,k,s,r),this.startSpan(Math.min(k,e.to),c),!(e.to>=x||!e.nextSibling())););if(!b||x>i)break;y=b.to+a,y>t&&(this.highlightRange(d.cursor(),Math.max(t,b.from+a),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),c))}m&&e.parent()}else if(e.firstChild()){f&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),c)}while(e.nextSibling());e.parent()}}}function xO(n){let e=n.type.prop(Hu);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const T=lt.define,as=T(),Vt=T(),dc=T(Vt),pc=T(Vt),jt=T(),ls=T(jt),Vr=T(jt),wt=T(),li=T(wt),xt=T(),vt=T(),Go=T(),on=T(Go),cs=T(),O={comment:as,lineComment:T(as),blockComment:T(as),docComment:T(as),name:Vt,variableName:T(Vt),typeName:dc,tagName:T(dc),propertyName:pc,attributeName:T(pc),className:T(Vt),labelName:T(Vt),namespace:T(Vt),macroName:T(Vt),literal:jt,string:ls,docString:T(ls),character:T(ls),attributeValue:T(ls),number:Vr,integer:T(Vr),float:T(Vr),bool:T(jt),regexp:T(jt),escape:T(jt),color:T(jt),url:T(jt),keyword:xt,self:T(xt),null:T(xt),atom:T(xt),unit:T(xt),modifier:T(xt),operatorKeyword:T(xt),controlKeyword:T(xt),definitionKeyword:T(xt),moduleKeyword:T(xt),operator:vt,derefOperator:T(vt),arithmeticOperator:T(vt),logicOperator:T(vt),bitwiseOperator:T(vt),compareOperator:T(vt),updateOperator:T(vt),definitionOperator:T(vt),typeOperator:T(vt),controlOperator:T(vt),punctuation:Go,separator:T(Go),bracket:on,angleBracket:T(on),squareBracket:T(on),paren:T(on),brace:T(on),content:wt,heading:li,heading1:T(li),heading2:T(li),heading3:T(li),heading4:T(li),heading5:T(li),heading6:T(li),contentSeparator:T(wt),list:T(wt),quote:T(wt),emphasis:T(wt),strong:T(wt),link:T(wt),monospace:T(wt),strikethrough:T(wt),inserted:T(),deleted:T(),changed:T(),invalid:T(),meta:cs,documentMeta:T(cs),annotation:T(cs),processingInstruction:T(cs),definition:lt.defineModifier("definition"),constant:lt.defineModifier("constant"),function:lt.defineModifier("function"),standard:lt.defineModifier("standard"),local:lt.defineModifier("local"),special:lt.defineModifier("special")};for(let n in O){let e=O[n];e instanceof lt&&(e.name=n)}Gu([{tag:O.link,class:"tok-link"},{tag:O.heading,class:"tok-heading"},{tag:O.emphasis,class:"tok-emphasis"},{tag:O.strong,class:"tok-strong"},{tag:O.keyword,class:"tok-keyword"},{tag:O.atom,class:"tok-atom"},{tag:O.bool,class:"tok-bool"},{tag:O.url,class:"tok-url"},{tag:O.labelName,class:"tok-labelName"},{tag:O.inserted,class:"tok-inserted"},{tag:O.deleted,class:"tok-deleted"},{tag:O.literal,class:"tok-literal"},{tag:O.string,class:"tok-string"},{tag:O.number,class:"tok-number"},{tag:[O.regexp,O.escape,O.special(O.string)],class:"tok-string2"},{tag:O.variableName,class:"tok-variableName"},{tag:O.local(O.variableName),class:"tok-variableName tok-local"},{tag:O.definition(O.variableName),class:"tok-variableName tok-definition"},{tag:O.special(O.variableName),class:"tok-variableName2"},{tag:O.definition(O.propertyName),class:"tok-propertyName tok-definition"},{tag:O.typeName,class:"tok-typeName"},{tag:O.namespace,class:"tok-namespace"},{tag:O.className,class:"tok-className"},{tag:O.macroName,class:"tok-macroName"},{tag:O.propertyName,class:"tok-propertyName"},{tag:O.operator,class:"tok-operator"},{tag:O.comment,class:"tok-comment"},{tag:O.meta,class:"tok-meta"},{tag:O.invalid,class:"tok-invalid"},{tag:O.punctuation,class:"tok-punctuation"}]);var jr;const $i=new G;function _u(n){return K.define({combine:n?e=>e.concat(n):void 0})}const Za=new G;class mt{constructor(e,t,i=[],s=""){this.data=e,this.name=s,_.prototype.hasOwnProperty("tree")||Object.defineProperty(_.prototype,"tree",{get(){return Ce(this)}}),this.parser=t,this.extension=[si.of(this),_.languageData.of((r,o,a)=>{let l=mc(r,o,a),c=l.type.prop($i);if(!c)return[];let h=r.facet(c),u=l.type.prop(Za);if(u){let f=l.resolve(o-l.from,a);for(let d of u)if(d.test(f,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(h)}}return h})].concat(i)}isActiveAt(e,t,i=-1){return mc(e,t,i).type.prop($i)==this.data}findRegions(e){let t=e.facet(si);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop($i)==this.data){i.push({from:o,to:o+r.length});return}let a=r.prop(G.mounted);if(a){if(a.tree.prop($i)==this.data){if(a.overlay)for(let l of a.overlay)i.push({from:l.from+o,to:l.to+o});else i.push({from:o,to:o+r.length});return}else if(a.overlay){let l=i.length;if(s(a.tree,a.overlay[0].from+o),i.length>l)return}}for(let l=0;l<r.children.length;l++){let c=r.children[l];c instanceof ke&&s(c,r.positions[l]+o)}};return s(Ce(e),0),i}get allowsNesting(){return!0}}mt.setState=z.define();function mc(n,e,t){let i=n.facet(si),s=Ce(n).topNode;if(!i||i.allowsNesting)for(let r=s;r;r=r.enter(e,t,be.ExcludeBuffers|be.EnterBracketed))r.type.isTop&&(s=r);return s}class Xs extends mt{constructor(e,t,i){super(e,t,[],i),this.parser=t}static define(e){let t=_u(e.languageData);return new Xs(t,e.parser.configure({props:[$i.add(i=>i.isTop?t:void 0)]}),e.name)}configure(e,t){return new Xs(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Ce(n){let e=n.field(mt.state,!1);return e?e.tree:ke.empty}class vO{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e<i||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let an=null;class Bs{constructor(e,t,i=[],s,r,o,a,l){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new Bs(e,t,[],ke.empty,0,i,[],null)}startParse(){return this.parser.startParse(new vO(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=ke.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let s=this.parse.advance();if(s)if(this.fragments=this.withoutTempSkipped(Oi.addTree(s,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(i=this.parse.stoppedAt)!==null&&i!==void 0?i:this.state.doc.length,this.tree=s,this.parse=null,this.treeLen<(t??this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Oi.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=an;an=this;try{return e()}finally{an=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=gc(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,h,u,f)=>l.push({fromA:c,toA:h,fromB:u,toB:f})),i=Oi.applyChanges(i,l),s=ke.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let h=e.mapPos(c.from,1),u=e.mapPos(c.to,-1);h<u&&a.push({from:h,to:u})}}}return new Bs(this.parser,t,i,s,r,o,a,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let i=0;i<this.skipped.length;i++){let{from:s,to:r}=this.skipped[i];s<e.to&&r>e.from&&(this.fragments=gc(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends Yu{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let l=an;if(l){for(let c of s)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new ke(et.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return an}}function gc(n,e,t){return Oi.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class ji{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new ji(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Bs.create(e.facet(si).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new ji(i)}}mt.state=Te.define({create:ji.init,update(n,e){for(let t of e.effects)if(t.is(mt.setState))return t.value;return e.startState.facet(si)!=e.state.facet(si)?ji.init(e.state):n.apply(e)}});let Ju=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Ju=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const Yr=typeof navigator<"u"&&(!((jr=navigator.scheduling)===null||jr===void 0)&&jr.isInputPending)?()=>navigator.scheduling.isInputPending():null,wO=xe.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(mt.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(mt.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Ju(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:i,viewport:{to:s}}=this.view,r=i.field(mt.state);if(r.tree==r.context.tree&&r.context.isDone(s+1e5))return;let o=Date.now()+Math.min(this.chunkBudget,100,e&&!Yr?Math.max(25,e.timeRemaining()-5):1e9),a=r.context.treeLen<s&&i.doc.length>s+1e3,l=r.context.work(()=>Yr&&Yr()||Date.now()>o,s+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:mt.setState.of(new ji(r.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ze(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),si=K.define({combine(n){return n.length?n[0]:null},enables:n=>[mt.state,wO,$.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class kO{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}const QO=K.define(),yr=K.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function Is(n){let e=n.facet(yr);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Tn(n,e){let t="",i=n.tabSize,s=n.facet(yr)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r<e;r++)t+=s;return t}function Ma(n,e){n instanceof _&&(n=new Ar(n));for(let i of n.state.facet(QO)){let s=i(n,e);if(s!==void 0)return s}let t=Ce(n.state);return t.length>=e?PO(n,t,e):null}class Ar{constructor(e,t={}){this.state=e,this.options=t,this.unit=Is(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s<e:s<=e)?{text:i.text.slice(s-i.from),from:s}:{text:i.text.slice(0,s-i.from),from:i.from}:i}textAfterPos(e,t=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:i,from:s}=this.lineAt(e,t);return i.slice(e-s,Math.min(i.length,e+100-s))}column(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.countColumn(i,e-s),o=this.options.overrideIndentation?this.options.overrideIndentation(s):-1;return o>-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return _i(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const ef=new G;function PO(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.from<i.node.from||o.to>i.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return tf(i,n,t)}function tf(n,e,t){for(let i=n;i;i=i.next){let s=TO(i.node);if(s)return s(Ea.create(e,t,i))}return 0}function CO(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function TO(n){let e=n.type.prop(ef);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(G.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>nf(o,!0,1,void 0,r&&!CO(o)?s.from:void 0)}return n.parent==null?RO:null}function RO(){return 0}class Ea extends Ar{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new Ea(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if($O(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return tf(this.context.next,this.base,this.pos)}}function $O(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function KO(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==i)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+c}}a=l.to}}function ZO({closing:n,align:e=!0,units:t=1}){return i=>nf(i,e,t,n)}function nf(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,a=i&&r.slice(o,o+i.length)==i||s==n.pos+o,l=e?KO(n):null;return l?a?n.column(l.from):n.column(l.to):n.baseIndent+(a?0:n.unit*t)}const MO=n=>n.baseIndent;function Nr({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const EO=200;function UO(){return _.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+EO)return n;let r=t.sliceString(s.from,i);if(!e.some(c=>c.test(r)))return n;let{state:o}=n,a=-1,l=[];for(let{head:c}of o.selection.ranges){let h=o.doc.lineAt(c);if(h.from==a)continue;a=h.from;let u=Ma(o,h.from);if(u==null)continue;let f=/^\s*/.exec(h.text)[0],d=Tn(o,u);f!=d&&l.push({from:h.from,to:h.from+f.length,insert:d})}return l.length?[n,{changes:l,sequential:!0}]:n})}const FO=K.define(),sf=new G;function DO(n){let e=n.firstChild,t=n.lastChild;return e&&e.to<t.from?{from:e.to,to:t.type.isError?n.to:t.from}:null}function LO(n,e,t){let i=Ce(n);if(i.length<t)return null;let s=i.resolveStack(t,1),r=null;for(let o=s;o;o=o.next){let a=o.node;if(a.to<=t||a.from>t)continue;if(r&&a.from<e)break;let l=a.type.prop(sf);if(l&&(a.to<i.length-50||i.length==n.doc.length||!XO(a))){let c=l(a,n);c&&c.from<=t&&c.from>=e&&c.to>t&&(r=c)}}return r}function XO(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Ws(n,e,t){for(let i of n.facet(FO)){let s=i(n,e,t);if(s)return s}return LO(n,e,t)}function rf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const br=z.define({map:rf}),Ln=z.define({map:rf});function of(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const xi=Te.define({create(){return B.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((i,s)=>n=Oc(n,i,s)),n=n.map(e.changes);let t=[];for(let i of e.effects)i.is(br)&&!BO(n,i.value.from,i.value.to)?t.push(i.value):i.is(Ln)&&(n=n.update({filter:(s,r)=>i.value.from!=s||i.value.to!=r,filterFrom:i.value.from,filterTo:i.value.to}));if(t.length){let{preparePlaceholder:i}=e.state.facet(cf),s=t.map(r=>(i?B.replace({widget:new YO(i(e.state,r))}):yc).range(r.from,r.to));n=n.update({add:s})}return e.selection&&(n=Oc(n,e.selection.main.head)),n},provide:n=>$.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t<n.length;){let i=n[t++],s=n[t++];if(typeof i!="number"||typeof s!="number")throw new RangeError("Invalid JSON for fold state");e.push(yc.range(i,s))}return B.set(e,!0)}});function Oc(n,e,t=e){let i=!1;return n.between(e,t,(s,r)=>{s<t&&r>e&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function qs(n,e,t){var i;let s=null;return(i=n.field(xi,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function BO(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function af(n,e){return n.field(xi,!1)?e:e.concat(z.appendConfig.of(hf()))}const IO=n=>{for(let e of of(n)){let t=Ws(n.state,e.from,e.to);if(t)return n.dispatch({effects:af(n.state,[br.of(t),lf(n,t)])}),!0}return!1},WO=n=>{if(!n.state.field(xi,!1))return!1;let e=[];for(let t of of(n)){let i=qs(n.state,t.from,t.to);i&&e.push(Ln.of(i),lf(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function lf(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return $.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}const qO=n=>{let{state:e}=n,t=[];for(let i=0;i<e.doc.length;){let s=n.lineBlockAt(i),r=Ws(e,s.from,s.to);r&&t.push(br.of(r)),i=(r?n.lineBlockAt(r.to):s).to+1}return t.length&&n.dispatch({effects:af(n.state,t)}),!!t.length},zO=n=>{let e=n.state.field(xi,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(Ln.of({from:i,to:s}))}),n.dispatch({effects:t}),!0},VO=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:IO},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:WO},{key:"Ctrl-Alt-[",run:qO},{key:"Ctrl-Alt-]",run:zO}],jO={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},cf=K.define({combine(n){return yt(n,jO)}});function hf(n){return[xi,GO]}function uf(n,e){let{state:t}=n,i=t.facet(cf),s=o=>{let a=n.lineBlockAt(n.posAtDOM(o.target)),l=qs(n.state,a.from,a.to);l&&n.dispatch({effects:Ln.of(l)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}const yc=B.replace({widget:new class extends Ut{toDOM(n){return uf(n,null)}}});class YO extends Ut{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return uf(e,this.value)}}const NO={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class Hr extends Mt{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function HO(n={}){let e={...NO,...n},t=new Hr(e,!0),i=new Hr(e,!1),s=xe.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(si)!=o.state.facet(si)||o.startState.field(xi,!1)!=o.state.field(xi,!1)||Ce(o.startState)!=Ce(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new Bt;for(let l of o.viewportLineBlocks){let c=qs(o.state,l.from,l.to)?i:Ws(o.state,l.from,l.to)?t:null;c&&a.add(l.from,l.from,c)}return a.finish()}}),{domEventHandlers:r}=e;return[s,Bu({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(s))===null||a===void 0?void 0:a.markers)||N.empty},initialSpacer(){return new Hr(e,!1)},domEventHandlers:{...r,click:(o,a,l)=>{if(r.click&&r.click(o,a,l))return!0;let c=qs(o.state,a.from,a.to);if(c)return o.dispatch({effects:Ln.of(c)}),!0;let h=Ws(o.state,a.from,a.to);return h?(o.dispatch({effects:br.of(h)}),!0):!1}}}),hf()]}const GO=$.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class Xn{constructor(e,t){this.specs=e;let i;function s(a){let l=ei.newName();return(i||(i=Object.create(null)))["."+l]=a,l}const r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof mt?a=>a.prop($i)==o.data:o?a=>a==o:void 0,this.style=Gu(e.map(a=>({tag:a.tag,class:a.class||s(Object.assign({},a,{tag:null}))})),{all:r}).style,this.module=i?new ei(i):null,this.themeType=t.themeType}static define(e,t){return new Xn(e,t||{})}}const _o=K.define(),_O=K.define({combine(n){return n.length?[n[0]]:null}});function Gr(n){let e=n.facet(_o);return e.length?e:n.facet(_O)}function JO(n,e){let t=[t0],i;return n instanceof Xn&&(n.module&&t.push($.styleModule.of(n.module)),i=n.themeType),i?t.push(_o.computeN([$.darkTheme],s=>s.facet($.darkTheme)==(i=="dark")?[n]:[])):t.push(_o.of(n)),t}class e0{constructor(e){this.markCache=Object.create(null),this.tree=Ce(e.state),this.decorations=this.buildDeco(e,Gr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=Ce(e.state),i=Gr(e.state),s=i!=Gr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length<r.to&&!s&&t.type==this.tree.type&&o>=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return B.none;let i=new Bt;for(let{from:s,to:r}of e.visibleRanges)bO(this.tree,t,(o,a,l)=>{i.add(o,a,this.markCache[l]||(this.markCache[l]=B.mark({class:l})))},s,r);return i.finish()}}const t0=ri.high(xe.fromClass(e0,{decorations:n=>n.decorations})),i0=Xn.define([{tag:O.meta,color:"#404740"},{tag:O.link,textDecoration:"underline"},{tag:O.heading,textDecoration:"underline",fontWeight:"bold"},{tag:O.emphasis,fontStyle:"italic"},{tag:O.strong,fontWeight:"bold"},{tag:O.strikethrough,textDecoration:"line-through"},{tag:O.keyword,color:"#708"},{tag:[O.atom,O.bool,O.url,O.contentSeparator,O.labelName],color:"#219"},{tag:[O.literal,O.inserted],color:"#164"},{tag:[O.string,O.deleted],color:"#a11"},{tag:[O.regexp,O.escape,O.special(O.string)],color:"#e40"},{tag:O.definition(O.variableName),color:"#00f"},{tag:O.local(O.variableName),color:"#30a"},{tag:[O.typeName,O.namespace],color:"#085"},{tag:O.className,color:"#167"},{tag:[O.special(O.variableName),O.macroName],color:"#256"},{tag:O.definition(O.propertyName),color:"#00c"},{tag:O.comment,color:"#940"},{tag:O.invalid,color:"#f00"}]),n0=$.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),ff=1e4,df="()[]{}",pf=K.define({combine(n){return yt(n,{afterCursor:!0,brackets:df,maxScanDistance:ff,renderMatch:o0})}}),s0=B.mark({class:"cm-matchingBracket"}),r0=B.mark({class:"cm-nonmatchingBracket"});function o0(n){let e=[],t=n.matched?s0:r0;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Ac(n){let e=[],t=n.facet(pf);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Rt(n,i.head,-1,t)||i.head>0&&Rt(n,i.head-1,1,t)||t.afterCursor&&(Rt(n,i.head,1,t)||i.head<n.doc.length&&Rt(n,i.head+1,-1,t));s&&(e=e.concat(t.renderMatch(s,n)))}return B.set(e,!0)}const a0=xe.fromClass(class{constructor(n){this.paused=!1,this.decorations=Ac(n.state)}update(n){(n.docChanged||n.selectionSet||this.paused)&&(n.view.composing?(this.decorations=this.decorations.map(n.changes),this.paused=!0):(this.decorations=Ac(n.state),this.paused=!1))}},{decorations:n=>n.decorations}),l0=[a0,n0];function c0(n={}){return[pf.of(n),l0]}const h0=new G;function Jo(n,e,t){let i=n.prop(e<0?G.openedBy:G.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function ea(n){let e=n.type.prop(h0);return e?e(n.node):n}function Rt(n,e,t,i={}){let s=i.maxScanDistance||ff,r=i.brackets||df,o=Ce(n),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let c=Jo(l.type,t,r);if(c&&l.from<l.to){let h=ea(l);if(h&&(t>0?e>=h.from&&e<h.to:e>h.from&&e<=h.to))return u0(n,e,t,l,h,c,r)}}return f0(n,e,t,o,a.type,s,r)}function u0(n,e,t,i,s,r,o){let a=i.parent,l={from:s.from,to:s.to},c=0,h=a?.cursor();if(h&&(t<0?h.childBefore(i.from):h.childAfter(i.to)))do if(t<0?h.to<=i.from:h.from>=i.to){if(c==0&&r.indexOf(h.type.name)>-1&&h.from<h.to){let u=ea(h);return{start:l,end:u?{from:u.from,to:u.to}:void 0,matched:!0}}else if(Jo(h.type,t,o))c++;else if(Jo(h.type,-t,o)){if(c==0){let u=ea(h);return{start:l,end:u&&u.from<u.to?{from:u.from,to:u.to}:void 0,matched:!1}}c--}}while(t<0?h.prevSibling():h.nextSibling());return{start:l,matched:!1}}function f0(n,e,t,i,s,r,o){if(t<0?!e:e==n.doc.length)return null;let a=t<0?n.sliceDoc(e-1,e):n.sliceDoc(e,e+1),l=o.indexOf(a);if(l<0||l%2==0!=t>0)return null;let c={from:t<0?e-1:e,to:t>0?e+1:e},h=n.doc.iterRange(e,t>0?n.doc.length:0),u=0;for(let f=0;!h.next().done&&f<=r;){let d=h.value;t<0&&(f+=d.length);let p=e+f*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let y=o.indexOf(d[m]);if(!(y<0||i.resolveInner(p+m,1).type!=s))if(y%2==0==t>0)u++;else{if(u==1)return{start:c,end:{from:p+m,to:p+m+1},matched:y>>1==l>>1};u--}}t>0&&(f+=d.length)}return h.done?{start:c,matched:!1}:null}const d0=Object.create(null),bc=[et.none],Sc=[],xc=Object.create(null),p0=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])p0[n]=m0(d0,e);function _r(n,e){Sc.indexOf(n)>-1||(Sc.push(n),console.warn(e))}function m0(n,e){let t=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let h=n[c]||O[c];h?typeof h=="function"?l.length?l=l.map(h):_r(c,`Modifier ${c} used at start of tag`):l.length?_r(c,`Tag ${c} used as modifier`):l=Array.isArray(h)?h:[h]:_r(c,`Unknown highlighting tag ${c}`)}for(let c of l)t.push(c)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(a=>a.id),r=xc[s];if(r)return r.id;let o=xc[s]=et.define({id:bc.length,name:i,props:[Nu({[i]:t})]});return bc.push(o),o.id}fe.RTL,fe.LTR;const g0=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=Fa(n.state,t.from);return i.line?O0(n):i.block?A0(n):!1};function Ua(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}const O0=Ua(x0,0),y0=Ua(mf,0),A0=Ua((n,e)=>mf(n,e,S0(e)),0);function Fa(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const ln=50;function b0(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-ln,i),o=n.sliceDoc(s,s+ln),a=/\s*$/.exec(r)[0].length,l=/^\s*/.exec(o)[0].length,c=r.length-a;if(r.slice(c-e.length,c)==e&&o.slice(l,l+t.length)==t)return{open:{pos:i-a,margin:a&&1},close:{pos:s+l,margin:l&&1}};let h,u;s-i<=2*ln?h=u=n.sliceDoc(i,s):(h=n.sliceDoc(i,i+ln),u=n.sliceDoc(s-ln,s));let f=/^\s*/.exec(h)[0].length,d=/\s*$/.exec(u)[0].length,p=u.length-d-t.length;return h.slice(f,f+e.length)==e&&u.slice(p,p+t.length)==t?{open:{pos:i+f+e.length,margin:/\s/.test(h.charAt(f+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(u.charAt(p-1))?1:0}}:null}function S0(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function mf(n,e,t=e.selection.ranges){let i=t.map(r=>Fa(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>b0(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,a;o<s.length;o++)if(a=s[o]){let l=i[o],{open:c,close:h}=a;r.push({from:c.pos-l.open.length,to:c.pos+c.margin},{from:h.pos-h.margin,to:h.pos+l.close.length})}return{changes:r}}return null}function x0(n,e,t=e.selection.ranges){let i=[],s=-1;e:for(let{from:r,to:o}of t){let a=i.length,l=1e9,c;for(let h=r;h<=o;){let u=e.doc.lineAt(h);if(c==null&&(c=Fa(e,u.from).line,!c))continue e;if(u.from>s&&(r==o||o>u.from)){s=u.from;let f=/^\s*/.exec(u.text)[0].length,d=f==u.length,p=u.text.slice(f,f+c.length)==c?f:-1;f<u.text.length&&f<l&&(l=f),i.push({line:u,comment:p,token:c,indent:f,empty:d,single:!1})}h=u.to+1}if(l<1e9)for(let h=a;h<i.length;h++)i[h].indent<i[h].line.text.length&&(i[h].indent=l);i.length==a+1&&(i[a].single=!0)}if(n!=2&&i.some(r=>r.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:a,token:l,indent:c,empty:h,single:u}of i)(u||!h)&&r.push({from:a.from+c,insert:l+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:a,token:l}of i)if(a>=0){let c=o.from+a,h=c+l.length;o.text[h-o.from]==" "&&h++,r.push({from:c,to:h})}return{changes:r}}return null}const ta=qt.define(),ws=qt.define(),v0=K.define(),gf=K.define({combine(n){return yt(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),Da=Te.define({create(){return $t.empty},update(n,e){let t=e.state.facet(gf),i=e.annotation(ta);if(i){let l=_e.fromTransaction(e,i.selection),c=i.side,h=c==0?n.undone:n.done;return l?h=Vs(h,h.length,t.minDepth,l):h=Af(h,e.startState.selection),new $t(c==0?i.rest:h,c==0?h:i.rest)}let s=e.annotation(ws);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(Pe.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=_e.fromTransaction(e),o=e.annotation(Pe.time),a=e.annotation(Pe.userEvent);return r?n=n.addChanges(r,o,a,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new $t(n.done.map(_e.fromJSON),n.undone.map(_e.fromJSON))}});function w0(n={}){return[Da,gf.of(n),$.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?La:e.inputType=="historyRedo"?zs:null;return i?(e.preventDefault(),i(t)):!1}})]}function Sr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(Da,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}const La=Sr(0,!1),zs=Sr(1,!1),k0=Sr(0,!0),Q0=Sr(1,!0);function Of(n){return function(e){let t=e.field(Da,!1);if(!t)return 0;let i=n==0?t.done:t.undone;return i.length-(i.length&&!i[0].changes?1:0)}}const vc=Of(0),wc=Of(1);class _e{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new _e(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new _e(e.changes&&Re.fromJSON(e.changes),[],e.mapped&&Zt.fromJSON(e.mapped),e.startSelection&&A.fromJSON(e.startSelection),e.selectionsAfter.map(A.fromJSON))}static fromTransaction(e,t){let i=ht;for(let s of e.startState.facet(v0)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new _e(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,ht)}static selection(e){return new _e(void 0,ht,void 0,void 0,e)}}function Vs(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function P0(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,a)=>{for(let l=0;l<t.length;){let c=t[l++],h=t[l++];a>=c&&o<=h&&(i=!0)}}),i}function C0(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function yf(n,e){return n.length?e.length?n.concat(e):n:e}const ht=[],T0=200;function Af(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-T0));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),Vs(n,n.length-1,1e9,t.setSelAfter(i)))}else return[_e.selection([e])]}function R0(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function Jr(n,e){if(!n.length)return n;let t=n.length,i=ht;for(;t;){let s=$0(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[_e.selection(i)]:ht}function $0(n,e,t){let i=yf(n.selectionsAfter.length?n.selectionsAfter.map(a=>a.map(e)):ht,t);if(!n.changes)return _e.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new _e(s,z.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}const K0=/^(input\.type|delete)($|\.)/;class $t{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new $t(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!i||K0.test(i))&&(!a.selectionsAfter.length&&t-this.prevTime<s.newGroupDelay&&s.joinToEvent(r,P0(a.changes,e.changes))||i=="input.type.compose")?o=Vs(o,o.length-1,s.minDepth,new _e(e.changes.compose(a.changes),yf(z.mapEffects(e.effects,a.changes),a.effects),a.mapped,a.startSelection,ht)):o=Vs(o,o.length,s.minDepth,e),new $t(o,ht,t,i)}addSelection(e,t,i,s){let r=this.done.length?this.done[this.done.length-1].selectionsAfter:ht;return r.length>0&&t-this.prevTime<s&&i==this.prevUserEvent&&i&&/^select($|\.)/.test(i)&&C0(r[r.length-1],e)?this:new $t(Af(this.done,e),this.undone,t,i)}addMapping(e){return new $t(Jr(this.done,e),Jr(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,i){let s=e==0?this.done:this.undone;if(s.length==0)return null;let r=s[s.length-1],o=r.selectionsAfter[0]||(r.startSelection?r.startSelection.map(r.changes.invertedDesc,1):t.selection);if(i&&r.selectionsAfter.length)return t.update({selection:r.selectionsAfter[r.selectionsAfter.length-1],annotations:ta.of({side:e,rest:R0(s),selection:o}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(r.changes){let a=s.length==1?ht:s.slice(0,s.length-1);return r.mapped&&(a=Jr(a,r.mapped)),t.update({changes:r.changes,selection:r.startSelection,effects:r.effects,annotations:ta.of({side:e,rest:a,selection:o}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}}$t.empty=new $t(ht,ht);const Z0=[{key:"Mod-z",run:La,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:zs,preventDefault:!0},{linux:"Ctrl-Shift-z",run:zs,preventDefault:!0},{key:"Mod-u",run:k0,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Q0,preventDefault:!0}];function Ji(n,e){return A.create(n.ranges.map(e),n.mainIndex)}function At(n,e){return n.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function bt({state:n,dispatch:e},t){let i=Ji(n.selection,t);return i.eq(n.selection,!0)?!1:(e(At(n,i)),!0)}function xr(n,e){return A.cursor(e?n.to:n.from)}function bf(n,e){return bt(n,t=>t.empty?n.moveByChar(t,e):xr(t,e))}function Be(n){return n.textDirectionAt(n.state.selection.main.head)==fe.LTR}const Sf=n=>bf(n,!Be(n)),xf=n=>bf(n,Be(n));function vf(n,e){return bt(n,t=>t.empty?n.moveByGroup(t,e):xr(t,e))}const M0=n=>vf(n,!Be(n)),E0=n=>vf(n,Be(n));function U0(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function vr(n,e,t){let i=Ce(n).resolveInner(e.head),s=t?G.closedBy:G.openedBy;for(let l=e.head;;){let c=t?i.childAfter(l):i.childBefore(l);if(!c)break;U0(n,c,s)?i=c:l=t?c.to:c.from}let r=i.type.prop(s),o,a;return r&&(o=t?Rt(n,i.from,1):Rt(n,i.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?i.to:i.from,A.cursor(a,t?-1:1)}const F0=n=>bt(n,e=>vr(n.state,e,!Be(n))),D0=n=>bt(n,e=>vr(n.state,e,Be(n)));function wf(n,e){return bt(n,t=>{if(!t.empty)return xr(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const kf=n=>wf(n,!1),Qf=n=>wf(n,!0);function Pf(n){let e=n.scrollDOM.clientHeight<n.scrollDOM.scrollHeight-2,t=0,i=0,s;if(e){for(let r of n.state.facet($.scrollMargins)){let o=r(n);o?.top&&(t=Math.max(o?.top,t)),o?.bottom&&(i=Math.max(o?.bottom,i))}s=n.scrollDOM.clientHeight-t-i}else s=(n.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:t,marginBottom:i,selfScroll:e,height:Math.max(n.defaultLineHeight,s-5)}}function Cf(n,e){let t=Pf(n),{state:i}=n,s=Ji(i.selection,o=>o.empty?n.moveVertically(o,e,t.height):xr(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),a=n.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,c=a.bottom-t.marginBottom;o&&o.top>l&&o.bottom<c&&(r=$.scrollIntoView(s.main.head,{y:"start",yMargin:o.top-l}))}return n.dispatch(At(i,s),{effects:r}),!0}const kc=n=>Cf(n,!1),ia=n=>Cf(n,!0);function oi(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=A.cursor(i.from+r))}return s}const L0=n=>bt(n,e=>oi(n,e,!0)),X0=n=>bt(n,e=>oi(n,e,!1)),B0=n=>bt(n,e=>oi(n,e,!Be(n))),I0=n=>bt(n,e=>oi(n,e,Be(n))),W0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).from,1)),q0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).to,-1));function z0(n,e,t){let i=!1,s=Ji(n.selection,r=>{let o=Rt(n,r.head,-1)||Rt(n,r.head,1)||r.head>0&&Rt(n,r.head-1,1)||r.head<n.doc.length&&Rt(n,r.head+1,-1);if(!o||!o.end)return r;i=!0;let a=o.start.from==r.head?o.end.to:o.end.from;return A.cursor(a)});return i?(e(At(n,s)),!0):!1}const V0=({state:n,dispatch:e})=>z0(n,e);function ft(n,e,t){let i=Ji(n.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=A.range(s.head,s.anchor));let r=t(s);return A.range(s.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(At(n.state,i)),!0)}function Tf(n,e){return ft(n,e,t=>n.moveByChar(t,e))}const Rf=n=>Tf(n,!Be(n)),$f=n=>Tf(n,Be(n));function Kf(n,e){return ft(n,e,t=>n.moveByGroup(t,e))}const j0=n=>Kf(n,!Be(n)),Y0=n=>Kf(n,Be(n)),N0=n=>{let e=!Be(n);return ft(n,e,t=>vr(n.state,t,e))},H0=n=>{let e=Be(n);return ft(n,e,t=>vr(n.state,t,e))};function Zf(n,e){return ft(n,e,t=>n.moveVertically(t,e))}const Mf=n=>Zf(n,!1),Ef=n=>Zf(n,!0);function Uf(n,e){return ft(n,e,t=>n.moveVertically(t,e,Pf(n).height))}const Qc=n=>Uf(n,!1),Pc=n=>Uf(n,!0),G0=n=>ft(n,!0,e=>oi(n,e,!0)),_0=n=>ft(n,!1,e=>oi(n,e,!1)),J0=n=>{let e=!Be(n);return ft(n,e,t=>oi(n,t,e))},ey=n=>{let e=Be(n);return ft(n,e,t=>oi(n,t,e))},ty=n=>ft(n,!1,e=>A.cursor(n.lineBlockAt(e.head).from)),iy=n=>ft(n,!0,e=>A.cursor(n.lineBlockAt(e.head).to)),Cc=({state:n,dispatch:e})=>(e(At(n,{anchor:0})),!0),Tc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.doc.length})),!0),Rc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:0})),!0),$c=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),ny=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),sy=({state:n,dispatch:e})=>{let t=wr(n).map(({from:i,to:s})=>A.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:A.create(t),userEvent:"select"})),!0},ry=({state:n,dispatch:e})=>{let t=Ji(n.selection,i=>{let s=Ce(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:a}=o;if((a.from<i.from&&a.to>=i.to||a.to>i.to&&a.from<=i.from)&&o.next)return A.range(a.to,a.from)}return i});return t.eq(n.selection)?!1:(e(At(n,t)),!0)};function Ff(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to<n.state.doc.length:o.from>0)for(let a=r;;){let l=n.moveVertically(a,e);if(l.head<o.from||l.head>o.to){s.some(c=>c.head==l.head)||s.push(l);break}else{if(l.head==a.head)break;a=l}}}return s.length==i.ranges.length?!1:(n.dispatch(At(t,A.create(s,s.length-1))),!0)}const oy=n=>Ff(n,!1),ay=n=>Ff(n,!0),ly=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=A.create([t.main]):t.main.empty||(i=A.create([A.cursor(t.main.head)])),i?(e(At(n,i)),!0):!1};function Bn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:a}=r;if(o==a){let l=e(r);l<o?(t="delete.backward",l=hs(n,l,!1)):l>o&&(t="delete.forward",l=hs(n,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=hs(n,o,!1),a=hs(n,a,!0);return o==a?{range:r}:{changes:{from:o,to:a},range:A.cursor(o,o<r.head?-1:1)}});return s.changes.empty?!1:(n.dispatch(i.update(s,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?$.announce.of(i.phrase("Selection deleted")):void 0})),!0)}function hs(n,e,t){if(n instanceof $)for(let i of n.state.facet($.atomicRanges).map(s=>s(n)))i.between(e,e,(s,r)=>{s<e&&r>e&&(e=t?r:s)});return e}const Df=(n,e,t)=>Bn(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),a,l;if(t&&!e&&s>o.from&&s<o.from+200&&!/[^ \t]/.test(a=o.text.slice(0,s-o.from))){if(a[a.length-1]==" ")return s-1;let c=_i(a,r.tabSize),h=c%Is(r)||Is(r);for(let u=0;u<h&&a[a.length-1-u]==" ";u++)s--;l=s}else l=Ze(o.text,s-o.from,e,e)+o.from,l==s&&o.number!=(e?r.doc.lines:1)?l+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(o.text.slice(l-o.from,s-o.from))&&(l=Ze(o.text,l-o.from,!1,!1)+o.from);return l}),na=n=>Df(n,!1,!0),Lf=n=>Df(n,!0,!1),Xf=(n,e)=>Bn(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let a=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let l=Ze(r.text,i-r.from,e)+r.from,c=r.text.slice(Math.min(i,l)-r.from,Math.max(i,l)-r.from),h=o(c);if(a!=null&&h!=a)break;(c!=" "||i!=t.head)&&(a=h),i=l}return i}),Bf=n=>Xf(n,!1),cy=n=>Xf(n,!0),hy=n=>Bn(n,e=>{let t=n.lineBlockAt(e.head).to;return e.head<t?t:Math.min(n.state.doc.length,e.head+1)}),uy=n=>Bn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),fy=n=>Bn(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head<t?t:Math.min(n.state.doc.length,e.head+1)}),dy=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:se.of(["",""])},range:A.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},py=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:Ze(r.text,s-r.from,!1)+r.from,a=s==r.to?s+1:Ze(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:a,insert:n.doc.slice(s,a).append(n.doc.slice(o,s))},range:A.cursor(a)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function wr(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function If(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of wr(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),a=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let l of r.ranges)s.push(A.range(Math.min(n.doc.length,l.anchor+a),Math.min(n.doc.length,l.head+a)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let l of r.ranges)s.push(A.range(l.anchor-a,l.head-a))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:A.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const my=({state:n,dispatch:e})=>If(n,e,!1),gy=({state:n,dispatch:e})=>If(n,e,!0);function Wf(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of wr(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const Oy=({state:n,dispatch:e})=>Wf(n,e,!1),yy=({state:n,dispatch:e})=>Wf(n,e,!0),Ay=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(wr(e).map(({from:s,to:r})=>(s>0?s--:r<e.doc.length&&r++,{from:s,to:r}))),i=Ji(e.selection,s=>{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),a=n.coordsAtPos(s.head,s.assoc||1);a&&(r=o.bottom+n.documentTop-a.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function by(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Ce(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(G.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}const Kc=qf(!1),Sy=qf(!0);function qf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,a=e.doc.lineAt(r),l=!n&&r==o&&by(e,r);n&&(r=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Ar(e,{simulateBreak:r,simulateDoubleBreak:!!l}),h=Ma(c,r);for(h==null&&(h=_i(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));o<a.to&&/\s/.test(a.text[o-a.from]);)o++;l?{from:r,to:o}=l:r>a.from&&r<a.from+100&&!/\S/.test(a.text.slice(0,r))&&(r=a.from);let u=["",Tn(e,h)];return l&&u.push(Tn(e,c.lineIndent(a.from,-1))),{changes:{from:r,to:o,insert:se.of(u)},range:A.cursor(r+1+u[1].length)}});return t(e.update(i,{scrollIntoView:!0,userEvent:"input"})),!0}}function Xa(n,e){let t=-1;return n.changeByRange(i=>{let s=[];for(let o=i.from;o<=i.to;){let a=n.doc.lineAt(o);a.number>t&&(i.empty||i.to>a.from)&&(e(a,s,i),t=a.number),o=a.to+1}let r=n.changes(s);return{changes:s,range:A.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}const xy=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Ar(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=Xa(n,(r,o,a)=>{let l=Ma(i,r.from);if(l==null)return;/\S/.test(r.text)||(l=0);let c=/^\s*/.exec(r.text)[0],h=Tn(n,l);(c!=h||a.from<r.from+c.length)&&(t[r.from]=l,o.push({from:r.from,to:r.from+c.length,insert:h}))});return s.changes.empty||e(n.update(s,{userEvent:"indent"})),!0},zf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Xa(n,(t,i)=>{i.push({from:t.from,insert:n.facet(yr)})}),{userEvent:"input.indent"})),!0),Vf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Xa(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=_i(s,n.tabSize),o=0,a=Tn(n,Math.max(0,r-Is(n)));for(;o<s.length&&o<a.length&&s.charCodeAt(o)==a.charCodeAt(o);)o++;i.push({from:t.from+o,to:t.from+s.length,insert:a.slice(o)})}),{userEvent:"delete.dedent"})),!0),vy=n=>(n.setTabFocusMode(),!0),wy=[{key:"Ctrl-b",run:Sf,shift:Rf,preventDefault:!0},{key:"Ctrl-f",run:xf,shift:$f},{key:"Ctrl-p",run:kf,shift:Mf},{key:"Ctrl-n",run:Qf,shift:Ef},{key:"Ctrl-a",run:W0,shift:ty},{key:"Ctrl-e",run:q0,shift:iy},{key:"Ctrl-d",run:Lf},{key:"Ctrl-h",run:na},{key:"Ctrl-k",run:hy},{key:"Ctrl-Alt-h",run:Bf},{key:"Ctrl-o",run:dy},{key:"Ctrl-t",run:py},{key:"Ctrl-v",run:ia}],ky=[{key:"ArrowLeft",run:Sf,shift:Rf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:M0,shift:j0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:B0,shift:J0,preventDefault:!0},{key:"ArrowRight",run:xf,shift:$f,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:E0,shift:Y0,preventDefault:!0},{mac:"Cmd-ArrowRight",run:I0,shift:ey,preventDefault:!0},{key:"ArrowUp",run:kf,shift:Mf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Cc,shift:Rc},{mac:"Ctrl-ArrowUp",run:kc,shift:Qc},{key:"ArrowDown",run:Qf,shift:Ef,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Tc,shift:$c},{mac:"Ctrl-ArrowDown",run:ia,shift:Pc},{key:"PageUp",run:kc,shift:Qc},{key:"PageDown",run:ia,shift:Pc},{key:"Home",run:X0,shift:_0,preventDefault:!0},{key:"Mod-Home",run:Cc,shift:Rc},{key:"End",run:L0,shift:G0,preventDefault:!0},{key:"Mod-End",run:Tc,shift:$c},{key:"Enter",run:Kc,shift:Kc},{key:"Mod-a",run:ny},{key:"Backspace",run:na,shift:na,preventDefault:!0},{key:"Delete",run:Lf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Bf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:cy,preventDefault:!0},{mac:"Mod-Backspace",run:uy,preventDefault:!0},{mac:"Mod-Delete",run:fy,preventDefault:!0}].concat(wy.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),Qy=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:F0,shift:N0},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:D0,shift:H0},{key:"Alt-ArrowUp",run:my},{key:"Shift-Alt-ArrowUp",run:Oy},{key:"Alt-ArrowDown",run:gy},{key:"Shift-Alt-ArrowDown",run:yy},{key:"Mod-Alt-ArrowUp",run:oy},{key:"Mod-Alt-ArrowDown",run:ay},{key:"Escape",run:ly},{key:"Mod-Enter",run:Sy},{key:"Alt-l",mac:"Ctrl-l",run:sy},{key:"Mod-i",run:ry,preventDefault:!0},{key:"Mod-[",run:Vf},{key:"Mod-]",run:zf},{key:"Mod-Alt-\\",run:xy},{key:"Shift-Mod-k",run:Ay},{key:"Shift-Mod-\\",run:V0},{key:"Mod-/",run:g0},{key:"Alt-A",run:y0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:vy}].concat(ky),Py={key:"Tab",run:zf,shift:Vf};class jf{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=Ce(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(Nf(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}}function Zc(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Cy(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;r<s.length;r++)t[s[r]]=!0}let i=Zc(e)+Zc(t)+"*$";return[new RegExp("^"+i),new RegExp(i)]}function Yf(n){let e=n.map(s=>typeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Cy(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function Ty(n,e){return t=>{for(let i=Ce(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}let Mc=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function yi(n){return n.selection.main.from}function Nf(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}const Ba=qt.define();function Ry(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(a=>{if(a!=s&&t!=i&&n.sliceDoc(a.from+r,a.from+o)!=n.sliceDoc(t,i))return{range:a};let l=n.toText(e);return{changes:{from:a.from+r,to:i==s.from?a.to:a.from+o,insert:l},range:A.cursor(a.from+r+l.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const Ec=new WeakMap;function $y(n){if(!Array.isArray(n))return n;let e=Ec.get(n);return e||Ec.set(n,e=Yf(n)),e}const js=z.define(),Rn=z.define();class Ky{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t<e.length;){let i=Ne(e,t),s=Qt(i);this.chars.push(i);let r=e.slice(t,t+s),o=r.toUpperCase();this.folded.push(Ne(o==r?r.toLowerCase():o,0)),t+=s}this.astral=e.length!=this.chars.length}ret(e,t){return this.score=e,this.matched=t,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:t,folded:i,any:s,precise:r,byWord:o}=this;if(t.length==1){let b=Ne(e,0),x=Qt(b),C=x==e.length?0:-100;if(b!=t[0])if(b==i[0])C+=-200;else return null;return this.ret(C,[0,x])}let a=e.indexOf(this.pattern);if(a==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let l=t.length,c=0;if(a<0){for(let b=0,x=Math.min(e.length,200);b<x&&c<l;){let C=Ne(e,b);(C==t[c]||C==i[c])&&(s[c++]=b),b+=Qt(C)}if(c<l)return null}let h=0,u=0,f=!1,d=0,p=-1,m=-1,g=/[a-z]/.test(e),y=!0;for(let b=0,x=Math.min(e.length,200),C=0;b<x&&u<l;){let k=Ne(e,b);a<0&&(h<l&&k==t[h]&&(r[h++]=b),d<l&&(k==t[d]||k==i[d]?(d==0&&(p=b),m=b+1,d++):d=0));let S,w=k<255?k>=48&&k<=57||k>=97&&k<=122?2:k>=65&&k<=90?1:0:(S=fa(k))!=S.toLowerCase()?1:S!=S.toUpperCase()?2:0;(!b||w==1&&g||C==0&&w!=0)&&(t[u]==k||i[u]==k&&(f=!0)?o[u++]=b:o.length&&(y=!1)),C=w,b+=Qt(k)}return u==l&&o[0]==0&&y?this.result(-100+(f?-200:0),o,e):d==l&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):a>-1?this.ret(-700-e.length,[a,a+this.pattern.length]):d==l?this.ret(-900-e.length,[p,m]):u==l?this.result(-100+(f?-200:0)+-700+(y?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let a=o+(this.astral?Qt(Ne(i,o)):1);r&&s[r-1]==o?s[r-1]=a:(s[r++]=o,s[r++]=a)}return this.ret(e-i.length,s)}}class Zy{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let t=e.slice(0,this.pattern.length),i=t==this.pattern?0:t.toLowerCase()==this.folded?-200:null;return i==null?null:(this.matched=[0,t.length],this.score=i+(e.length==this.pattern.length?0:-100),this)}}const Ke=K.define({combine(n){return yt(n,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:My,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>Uc(e(i),t(i)),optionClass:(e,t)=>i=>Uc(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function Uc(n,e){return n?e?n+" "+e:n:e}function My(n,e,t,i,s,r){let o=n.textDirection==fe.RTL,a=o,l=!1,c="top",h,u,f=e.left-s.left,d=s.right-e.right,p=i.right-i.left,m=i.bottom-i.top;if(a&&f<Math.min(p,d)?a=!1:!a&&d<Math.min(p,f)&&(a=!0),p<=(a?f:d))h=Math.max(s.top,Math.min(t.top,s.bottom-m))-e.top,u=Math.min(400,a?f:d);else{l=!0,u=Math.min(400,(o?e.right:s.right-e.left)-30);let b=s.bottom-e.bottom;b>=m||b>e.top?h=t.bottom-e.top:(c="bottom",h=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,y=(e.right-e.left)/r.offsetWidth;return{style:`${c}: ${h/g}px; max-width: ${u/y}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":a?"left":"right")}}const Ia=z.define();function Ey(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let a=t.displayLabel||t.label,l=0;for(let c=0;c<r.length;){let h=r[c++],u=r[c++];h>l&&o.appendChild(document.createTextNode(a.slice(l,h)));let f=o.appendChild(document.createElement("span"));f.appendChild(document.createTextNode(a.slice(h,u))),f.className="cm-completionMatchedText",l=u}return l<a.length&&o.appendChild(document.createTextNode(a.slice(l))),o},position:50},{render(t){if(!t.detail)return null;let i=document.createElement("span");return i.className="cm-completionDetail",i.textContent=t.detail,i},position:80}),e.sort((t,i)=>t.position-i.position).map(t=>t.render)}function eo(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.ceil((n-e)/t);return{from:n-i*t,to:n-(i-1)*t}}class Uy{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,a=e.state.facet(Ke);this.optionContent=Ey(a),this.optionClass=a.optionClass,this.tooltipClass=a.tooltipClass,this.range=eo(r.length,o,a.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=e.state.field(t).open;for(let h=l.target,u;h&&h!=this.dom;h=h.parentNode)if(h.nodeName=="LI"&&(u=/-(\d+)$/.exec(h.id))&&+u[1]<c.length){this.applyCompletion(e,c[+u[1]]),l.preventDefault();return}if(l.target==this.list){let h=this.list.classList.contains("cm-completionListIncompleteTop")&&l.clientY<this.list.firstChild.getBoundingClientRect().top?this.range.from-1:this.list.classList.contains("cm-completionListIncompleteBottom")&&l.clientY>this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;h!=null&&(e.dispatch({effects:Ia.of(h)}),l.preventDefault())}}),this.dom.addEventListener("focusout",l=>{let c=e.state.field(this.stateField,!1);c&&c.tooltip&&e.state.facet(Ke).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:Rn.of(null)})}),this.showOptions(r,s.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:a}=i.open;(!s.open||s.open.options!=r)&&(this.range=eo(r.length,o,e.state.facet(Ke).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),a!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected<this.range.from||t.selected>=this.range.to)&&(this.range=eo(t.options.length,t.selected,this.view.state.facet(Ke).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(a=>{a&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(a,s)}).catch(a=>ze(this.view.state,a,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&Dy(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom<Math.max(r.top,t.top)+10?null:this.view.state.facet(Ke).positionInfo(this.view,t,s,i,r,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className="cm-tooltip cm-completionInfo "+(e.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(e,t,i){const s=document.createElement("ul");s.id=t,s.setAttribute("role","listbox"),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label",this.view.state.phrase("Completions")),s.addEventListener("mousedown",o=>{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;o<i.to;o++){let{completion:a,match:l}=e[o],{section:c}=a;if(c){let f=typeof c=="string"?c:c.name;if(f!=r&&(o>i.from||i.from==0))if(r=f,typeof c!="string"&&c.header)s.appendChild(c.header(c));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=f}}const h=s.appendChild(document.createElement("li"));h.id=t+"-"+o,h.setAttribute("role","option");let u=this.optionClass(a);u&&(h.className=u);for(let f of this.optionContent){let d=f(a,this.view.state,this.view,l);d&&h.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.to<e.length&&s.classList.add("cm-completionListIncompleteBottom"),s}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function Fy(n,e){return t=>new Uy(t,n,e)}function Dy(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.top<t.top?n.scrollTop-=(t.top-i.top)/s:i.bottom>t.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function Fc(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function Ly(n,e){let t=[],i=null,s=null,r=h=>{t.push(h);let{section:u}=h.completion;if(u){i||(i=[]);let f=typeof u=="string"?u:u.name;i.some(d=>d.name==f)||i.push(typeof u=="string"?{name:f}:u)}},o=e.facet(Ke);for(let h of n)if(h.hasResult()){let u=h.result.getMatch;if(h.result.filter===!1)for(let f of h.result.options)r(new Mc(f,h.source,u?u(f):[],1e9-t.length));else{let f=e.sliceDoc(h.from,h.to),d,p=o.filterStrict?new Zy(f):new Ky(f);for(let m of h.result.options)if(d=p.match(m.label)){let g=m.displayLabel?u?u(m,d.matched):[]:d.matched,y=d.score+(m.boost||0);if(r(new Mc(m,h.source,g,y)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:b}=m.section;s||(s=Object.create(null)),s[b]=Math.max(y,s[b]||-1e9)}}}}if(i){let h=Object.create(null),u=0,f=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.name<p.name?-1:1);for(let d of i.sort(f))u-=1e5,h[d.name]=u;for(let d of t){let{section:p}=d.completion;p&&(d.score+=h[typeof p=="string"?p:p.name])}}let a=[],l=null,c=o.compareCompletions;for(let h of t.sort((u,f)=>f.score-u.score||c(u.completion,f.completion))){let u=h.completion;!l||l.label!=u.label||l.detail!=u.detail||l.type!=null&&u.type!=null&&l.type!=u.type||l.apply!=u.apply||l.boost!=u.boost?a.push(h):Fc(h.completion)>Fc(l)&&(a[a.length-1]=h),l=h.completion}return a}class Ki{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new Ki(this.options,Dc(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(c=>c.isPending))return s.setDisabled();let a=Ly(e,t);if(!a.length)return s&&e.some(c=>c.isPending)?s.setDisabled():null;let l=t.facet(Ke).selectOnOpen?0:-1;if(s&&s.selected!=l&&s.selected!=-1){let c=s.options[s.selected].completion;for(let h=0;h<a.length;h++)if(a[h].completion==c){l=h;break}}return new Ki(a,Dc(i,l),{pos:e.reduce((c,h)=>h.hasResult()?Math.min(c,h.from):c,1e8),create:zy,above:r.aboveCursor},s?s.timestamp:Date.now(),l,!1)}map(e){return new Ki(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Ki(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class Ys{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Ys(Wy,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(Ke),r=(i.override||t.languageDataAt("autocomplete",yi(t)).map($y)).map(l=>(this.active.find(h=>h.source==l)||new ut(l,this.active.some(h=>h.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((l,c)=>l==this.active[c])&&(r=this.active);let o=this.open,a=e.effects.some(l=>l.is(Wa));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!Xy(r,this.active)||a?o=Ki.build(r,t,this.id,o,i,a):o&&o.disabled&&!r.some(l=>l.isPending)&&(o=null),!o&&r.every(l=>!l.isPending)&&r.some(l=>l.hasResult())&&(r=r.map(l=>l.hasResult()?new ut(l.source,0):l));for(let l of e.effects)l.is(Ia)&&(o=o&&o.setSelected(l.value,this.id));return r==this.active&&o==this.open?this:new Ys(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?By:Iy}}function Xy(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t<n.length&&!n[t].hasResult();)t++;for(;i<e.length&&!e[i].hasResult();)i++;let s=t==n.length,r=i==e.length;if(s||r)return s==r;if(n[t++].result!=e[i++].result)return!1}}const By={"aria-autocomplete":"list"},Iy={};function Dc(n,e){let t={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":n};return e>-1&&(t["aria-activedescendant"]=n+"-"+e),t}const Wy=[];function Hf(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(Ba);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}class ut{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=Hf(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new ut(s.source,0)),i&4&&s.state==0&&(s=new ut(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(js))s=new ut(s.source,1,r.value);else if(r.is(Rn))s=new ut(s.source,0);else if(r.is(Wa))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(yi(e.state))}}class Fi extends ut{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),a=yi(e.state);if(a>o||!s||t&2&&(yi(e.startState)==this.from||a<this.limit))return new ut(this.source,t&4?1:0);let l=e.changes.mapPos(this.limit);return qy(s.validFor,e.state,r,o)?new Fi(this.source,this.explicit,l,s,r,o):s.update&&(s=s.update(s,r,o,new jf(e.state,a,!1)))?new Fi(this.source,this.explicit,l,s,s.from,(i=s.to)!==null&&i!==void 0?i:yi(e.state)):new ut(this.source,1,this.explicit)}map(e){if(e.empty)return this;let t=this.result.map?this.result.map(this.result,e):this.result;return t?new Fi(this.source,this.explicit,e.mapPos(this.limit),t,e.mapPos(this.from),e.mapPos(this.to,1)):new ut(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}}function qy(n,e,t,i){if(!n)return!1;let s=e.sliceDoc(t,i);return typeof n=="function"?n(s,t,i,e):Nf(n,!0).test(s)}const Wa=z.define({map(n,e){return n.map(t=>t.map(e))}}),He=Te.define({create(){return Ys.start()},update(n,e){return n.update(e)},provide:n=>[gr.from(n,e=>e.tooltip),$.contentAttributes.from(n,e=>e.attrs)]});function qa(n,e){const t=e.completion.apply||e.completion.label;let i=n.state.field(He).active.find(s=>s.source==e.source);return i instanceof Fi?(typeof t=="string"?n.dispatch({...Ry(n.state,t,i.from,i.to),annotations:Ba.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}const zy=Fy(He,qa);function us(n,e="option"){return t=>{let i=t.state.field(He,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp<t.state.facet(Ke).interactionDelay)return!1;let s=1,r;e=="page"&&(r=Uu(t,i.open.tooltip))&&(s=Math.max(2,Math.floor(r.dom.offsetHeight/r.dom.querySelector("li").offsetHeight)-1));let{length:o}=i.open.options,a=i.open.selected>-1?i.open.selected+s*(n?1:-1):n?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:Ia.of(a)}),!0}}const Vy=n=>{let e=n.state.field(He,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<n.state.facet(Ke).interactionDelay?!1:qa(n,e.open.options[e.open.selected])},to=n=>n.state.field(He,!1)?(n.dispatch({effects:js.of(!0)}),!0):!1,jy=n=>{let e=n.state.field(He,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Rn.of(null)}),!0)};class Yy{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const Ny=50,Hy=1e3,Gy=xe.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(He).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(He),t=n.state.facet(Ke);if(!n.selectionSet&&!n.docChanged&&n.startState.field(He)==e)return;let i=n.transactions.some(r=>{let o=Hf(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;r<this.running.length;r++){let o=this.running[r];if(i||o.context.abortOnDocChange&&n.docChanged||o.updates.length+n.transactions.length>Ny&&Date.now()-o.time>Hy){for(let a of o.context.abortListeners)try{a()}catch(l){ze(this.view.state,l)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(js)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(He);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=yi(e),i=new jf(e,t,n.explicit,this.view),s=new Yy(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:Rn.of(null)}),ze(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(Ke),i=this.view.state.field(He);for(let s=0;s<this.running.length;s++){let r=this.running[s];if(r.done===void 0)continue;if(this.running.splice(s--,1),r.done){let a=yi(r.updates.length?r.updates[0].startState:this.view.state),l=Math.min(a,r.done.from+(r.active.explicit?0:1)),c=new Fi(r.active.source,r.active.explicit,l,r.done,r.done.from,(n=r.done.to)!==null&&n!==void 0?n:a);for(let h of r.updates)c=c.update(h,t);if(c.hasResult()){e.push(c);continue}}let o=i.active.find(a=>a.source==r.active.source);if(o&&o.isPending)if(r.done==null){let a=new ut(r.active.source,0);for(let l of r.updates)a=a.update(l,t);a.isPending||e.push(a)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:Wa.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(He,!1);if(e&&e.tooltip&&this.view.state.facet(Ke).closeOnBlur){let t=e.open&&Uu(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Rn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:js.of(!1)}),20),this.composing=0}}}),_y=typeof navigator=="object"&&/Win/.test(navigator.platform),Jy=ri.highest($.domEventHandlers({keydown(n,e){let t=e.state.field(He,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(_y&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&qa(e,i),!1}})),Gf=$.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class eA{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}}class za{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,De.TrackDel),i=e.mapPos(this.to,1,De.TrackDel);return t==null||i==null?null:new za(this.field,t,i)}}class Va{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let l of this.lines){if(i.length){let c=o,h=/^\t*/.exec(l)[0].length;for(let u=0;u<h;u++)c+=e.facet(yr);s.push(t+c.length-h),l=c+l.slice(h)}i.push(l),t+=l.length+1}let a=this.fieldPositions.map(l=>new za(l.field,s[l.line]+l.from,s[l.line]+l.to));return{text:i,ranges:a}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let a=r[1]?+r[1]:null,l=r[2]||r[3]||"",c=-1;a===0&&(a=1e9);let h=l.replace(/\\[{}]/g,u=>u[1]);for(let u=0;u<t.length;u++)(a!=null?t[u].seq==a:h&&t[u].name==h)&&(c=u);if(c<0){let u=0;for(;u<t.length&&(a==null||t[u].seq!=null&&t[u].seq<a);)u++;t.splice(u,0,{seq:a,name:h}),c=u;for(let f of s)f.field>=c&&f.field++}for(let u of s)if(u.line==i.length&&u.from>r.index){let f=r[2]?3+(r[1]||"").length:2;u.from-=f,u.to-=f}s.push(new eA(c,i.length,r.index,r.index+h.length)),o=o.slice(0,r.index)+l+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(a,l,c)=>{for(let h of s)h.line==i.length&&h.from>c&&(h.from--,h.to--);return l}),i.push(o)}return new Va(i,s)}}let tA=B.widget({widget:new class extends Ut{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),iA=B.mark({class:"cm-snippetField"});class en{constructor(e,t){this.ranges=e,this.active=t,this.deco=B.set(e.map(i=>(i.from==i.to?tA:iA).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new en(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const In=z.define({map(n,e){return n&&n.map(e)}}),nA=z.define(),$n=Te.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(In))return t.value;if(t.is(nA)&&n)return new en(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>$.decorations.from(n,e=>e?e.deco:B.none)});function ja(n,e){return A.create(n.filter(t=>t.field==e).map(t=>A.range(t.from,t.to)))}function sA(n){let e=Va.parse(n);return(t,i,s,r)=>{let{text:o,ranges:a}=e.instantiate(t.state,s),{main:l}=t.state.selection,c={changes:{from:s,to:r==l.from?l.to:r,insert:se.of(o)},scrollIntoView:!0,annotations:i?[Ba.of(i),Pe.userEvent.of("input.complete")]:void 0};if(a.length&&(c.selection=ja(a,0)),a.some(h=>h.field>0)){let h=new en(a,0),u=c.effects=[In.of(h)];t.state.field($n,!1)===void 0&&u.push(z.appendConfig.of([$n,cA,hA,Gf]))}t.dispatch(t.state.update(c))}}function _f(n){return({state:e,dispatch:t})=>{let i=e.field($n,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:ja(i.ranges,s),effects:In.of(r?null:new en(i.ranges,s)),scrollIntoView:!0})),!0}}const rA=({state:n,dispatch:e})=>n.field($n,!1)?(e(n.update({effects:In.of(null)})),!0):!1,oA=_f(1),aA=_f(-1),lA=[{key:"Tab",run:oA,shift:aA},{key:"Escape",run:rA}],Lc=K.define({combine(n){return n.length?n[0]:lA}}),cA=ri.highest(mr.compute([Lc],n=>n.facet(Lc)));function Ye(n,e){return{...e,apply:sA(n)}}const hA=$.domEventHandlers({mousedown(n,e){let t=e.state.field($n,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:ja(t.ranges,s.field),effects:In.of(t.ranges.some(r=>r.field>s.field)?new en(t.ranges,s.field):null),scrollIntoView:!0}),!0)}}),Kn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},mi=z.define({map(n,e){let t=e.mapPos(n,-1,De.TrackAfter);return t??void 0}}),Ya=new class extends Jt{};Ya.startSide=1;Ya.endSide=-1;const Jf=Te.define({create(){return N.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(mi)&&(n=n.update({add:[Ya.range(t.value,t.value+1)]}));return n}});function uA(){return[dA,Jf]}const io="()[]{}<>«»»«[]{}";function ed(n){for(let e=0;e<io.length;e+=2)if(io.charCodeAt(e)==n)return io.charAt(e+1);return fa(n<128?n:n+1)}function td(n,e){return n.languageDataAt("closeBrackets",e)[0]||Kn}const fA=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),dA=$.inputHandler.of((n,e,t,i)=>{if((fA?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Qt(Ne(i,0))==1||e!=s.from||t!=s.to)return!1;let r=gA(n.state,i);return r?(n.dispatch(r),!0):!1}),pA=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=td(n,n.selection.main.head).brackets||Kn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let a=OA(n.doc,o.head);for(let l of i)if(l==a&&kr(n.doc,o.head)==ed(Ne(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:A.cursor(o.head-l.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},mA=[{key:"Backspace",run:pA}];function gA(n,e){let t=td(n,n.selection.main.head),i=t.brackets||Kn.brackets;for(let s of i){let r=ed(Ne(s,0));if(e==s)return r==s?bA(n,s,i.indexOf(s+s+s)>-1,t):yA(n,s,r,t.before||Kn.before);if(e==r&&id(n,n.selection.main.from))return AA(n,s,r)}return null}function id(n,e){let t=!1;return n.field(Jf).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function kr(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Qt(Ne(t,0)))}function OA(n,e){let t=n.sliceString(e-2,e);return Qt(Ne(t,0))==t.length?t:t.slice(1)}function yA(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:mi.of(o.to+e.length),range:A.range(o.anchor+e.length,o.head+e.length)};let a=kr(n.doc,o.head);return!a||/\s/.test(a)||i.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:mi.of(o.head+e.length),range:A.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function AA(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&kr(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:A.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function bA(n,e,t,i){let s=i.stringPrefixes||Kn.stringPrefixes,r=null,o=n.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:mi.of(a.to+e.length),range:A.range(a.anchor+e.length,a.head+e.length)};let l=a.head,c=kr(n.doc,l),h;if(c==e){if(Xc(n,l))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(id(n,l)){let f=t&&n.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+f.length,insert:f},range:A.cursor(l+f.length)}}}else{if(t&&n.sliceDoc(l-2*e.length,l)==e+e&&(h=Bc(n,l-2*e.length,s))>-1&&Xc(n,h))return{changes:{insert:e+e+e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(n.charCategorizer(l)(c)!=ye.Word&&Bc(n,l,s)>-1&&!SA(n,l,e,s))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)}}return{range:r=a}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function Xc(n,e){let t=Ce(n).resolveInner(e+1);return t.parent&&t.from==e}function SA(n,e,t,i){let s=Ce(n).resolveInner(e,-1),r=i.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),l=a.indexOf(t);if(!l||l>-1&&i.indexOf(a.slice(0,l))>-1){let h=s.firstChild;for(;h&&h.from==s.from&&h.to-h.from>t.length+l;){if(n.sliceDoc(h.to-t.length,h.to)==t)return!1;h=h.firstChild}return!0}let c=s.to==e&&s.parent;if(!c)break;s=c}return!1}function Bc(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=ye.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=ye.Word)return r}return-1}function xA(n={}){return[Jy,He,Ke.of(n),Gy,vA,Gf]}const nd=[{key:"Ctrl-Space",run:to},{mac:"Alt-`",run:to},{mac:"Alt-i",run:to},{key:"Escape",run:jy},{key:"ArrowDown",run:us(!0)},{key:"ArrowUp",run:us(!1)},{key:"PageDown",run:us(!0,"page")},{key:"PageUp",run:us(!1,"page")},{key:"Enter",run:Vy}],vA=ri.highest(mr.computeN([Ke],n=>n.facet(Ke).defaultKeymap?[nd]:[]));var Ic={};class Ns{constructor(e,t,i,s,r,o,a,l,c,h=0,u){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=a,this.bufferBase=l,this.curContext=c,this.lookAhead=h,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new Ns(e,[],t,i,i,0,[],0,s?new Wc(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos<this.pos-25&&this.setLookAhead(this.pos),a=r.dynamicPrecedence(s);if(a&&(this.score+=a),i==0){s<r.minRepeatTerm&&this.reducePos<this.pos&&(this.reducePos=this.pos),this.pushState(r.getGoto(this.state,s,!0),this.reducePos),s<r.minRepeatTerm&&this.storeNode(s,this.reducePos,this.reducePos,o?8:4,!0),this.reduceContext(s,this.reducePos);return}let l=this.stack.length-(i-1)*3-(e&262144?6:0),c=l?this.stack[l-2]:this.p.ranges[0].from;s<r.minRepeatTerm&&c==this.reducePos&&this.reducePos<this.pos&&(this.reducePos=this.pos);let h=this.reducePos-c;h>=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(c==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=h):this.p.lastBigReductionSize<h&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=c,this.p.lastBigReductionSize=h));let u=l?this.stack[l-1]:0,f=this.bufferBase+this.buffer.length-u;if(s<r.minRepeatTerm||e&131072){let d=r.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(s,c,d,f+4,!0)}if(e&262144)this.state=this.stack[l];else{let d=this.stack[l-3];this.state=r.getGoto(d,s,!0)}for(;this.stack.length>l;)this.stack.pop();this.reduceContext(s,c)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let o=this.buffer.length;if(o>0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let a=!1;for(let l=o;l>0&&this.buffer[l-2]>i;l-=4)if(this.buffer[l-1]>=0){a=!0;break}if(a)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let a=o.stateFlag(r,1);!a&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,a?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new Ns(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new wA(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;r<t.length;r+=2)(o=t[r+1])!=this.state&&this.p.parser.hasAction(o,e)&&s.push(t[r],o);if(this.stack.length<120)for(let r=0;s.length<8&&r<t.length;r+=2){let o=t[r+1];s.some((a,l)=>l&1&&a==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s<t.length&&i.length<4;s+=2){let r=t[s+1];if(r==this.state)continue;let o=this.split();o.pushState(r,this.pos),o.storeNode(0,o.pos,o.pos,4,!0),o.shiftContext(t[s],this.pos),o.reducePos=this.pos,o.score-=200,i.push(o)}return i}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if((t&65536)==0)return!1;if(!e.validAction(this.state,t)){let i=t>>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let a=(o>>19)-r;if(a>1){let l=o&65535,c=this.stack.length-a*3;if(c>=0&&e.getGoto(this.stack[c],l,!1)>=0)return a<<19|65536|l}}else{let a=i(o,r+1);if(a!=null)return a}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new Wc(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){return e<=this.lookAhead?!1:(this.emitLookAhead(),this.lookAhead=e,!0)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class Wc{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class wA{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}}class Hs{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new Hs(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new Hs(this.stack,this.pos,this.index)}}function dn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i<n.length;){let r=0;for(;;){let o=n.charCodeAt(i++),a=!1;if(o==126){r=65535;break}o>=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),r+=l,a)break;r*=46}t?t[s++]=r:t=new e(r)}return t}class ks{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const qc=new ks;class kA{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=qc,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;r<i.from;){if(!s)return null;let o=this.ranges[--s];r-=i.from-o.to,i=o}for(;t<0?r>i.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t<this.chunk.length)i=this.pos+e,s=this.chunk.charCodeAt(t);else{let r=this.resolveOffset(e,1);if(r==null)return-1;if(i=r,i>=this.chunk2Pos&&i<this.chunk2Pos+this.chunk2.length)s=this.chunk2.charCodeAt(i-this.chunk2Pos);else{let o=this.rangeIndex,a=this.range;for(;a.to<=i;)a=this.ranges[++o];this.chunk2=this.input.chunk(this.chunk2Pos=i),i+this.chunk2.length>a.to&&(this.chunk2=this.chunk2.slice(0,a.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=e,this.token.end=i}acceptTokenTo(e,t){this.token.value=e,this.token.end=t}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=qc,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}}class Di{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;sd(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}Di.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class sa{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?dn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(sd(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}}sa.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class Wn{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function sd(n,e,t,i,s,r){let o=0,a=1<<i,{dialect:l}=t.p.parser;e:for(;(a&n[o])!=0;){let c=n[o+1];for(let d=o+3;d<c;d+=2)if((n[d+1]&a)>0){let p=n[d];if(l.allows(p)&&(e.token.value==-1||e.token.value==p||QA(p,e.token.value,s,r))){e.acceptToken(p);break}}let h=e.next,u=0,f=n[o+2];if(e.next<0&&f>u&&n[c+f*3-3]==65535){o=n[c+f*3-1];continue e}for(;u<f;){let d=u+f>>1,p=c+d+(d<<1),m=n[p],g=n[p+1]||65536;if(h<m)f=d;else if(h>=g)u=d+1;else{o=n[p+2],e.advance();continue e}}break}}function zc(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function QA(n,e,t,i){let s=zc(t,i,e);return s<0||zc(t,i,n)<s}const nt=typeof process<"u"&&Ic&&/\bparse\b/.test(Ic.LOG);let no=null;function Vc(n,e,t){let i=n.cursor(be.IncludeAnonymous);for(i.moveTo(e);;)if(!(t<0?i.childBefore(e):i.childAfter(e)))for(;;){if((t<0?i.to<e:i.from>e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class PA{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Vc(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Vc(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let i=this.trees[t],s=this.index[t];if(s==i.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let r=i.children[s],o=this.start[t]+i.positions[s];if(o>e)return this.nextStart=o,null;if(r instanceof ke){if(o==e){if(o<this.safeFrom)return null;let a=o+r.length;if(a<=this.safeTo){let l=r.prop(G.lookAhead);if(!l||a+l<this.fragment.to)return r}}this.index[t]++,o+r.length>=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}}class CA{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new ks)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let c=0;c<r.length;c++){if((1<<c&o)==0)continue;let h=r[c],u=this.tokens[c];if(!(i&&!h.fallback)&&((h.contextual||u.start!=e.pos||u.mask!=o||u.context!=a)&&(this.updateCachedToken(u,h,e),u.mask=o,u.context=a),u.lookAhead>u.end+25&&(l=Math.max(u.lookAhead,l)),u.value!=0)){let f=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!h.extend&&(i=u,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!i&&e.pos==this.stream.end&&(i=new ks,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new ks,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o<r.specialized.length;o++)if(r.specialized[o]==e.value){let a=r.specializers[o](this.stream.read(e.start,e.end),i);if(a>=0&&i.p.parser.dialect.allows(a>>1)){(a&1)==0?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;r<s;r+=3)if(this.actions[r]==e)return s;return this.actions[s++]=e,this.actions[s++]=t,this.actions[s++]=i,s}addActions(e,t,i,s){let{state:r}=e,{parser:o}=e.p,{data:a}=o;for(let l=0;l<2;l++)for(let c=o.stateSlot(r,l?2:1);;c+=3){if(a[c]==65535)if(a[c+1]==1)c=Ft(a,c+2);else{s==0&&a[c+1]==2&&(s=this.putAction(Ft(a,c+2),t,i,s));break}a[c]==t&&(s=this.putAction(Ft(a,c+1),t,i,s))}return s}}class TA{constructor(e,t,i,s){this.parser=e,this.input=t,this.ranges=s,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new kA(t,s),this.tokens=new CA(e,this.stream),this.topTerm=e.top[1];let{from:r}=s[0];this.stacks=[Ns.start(this,e.top[0],r)],this.fragments=i.length&&this.stream.end-r>e.bufferLength*4?new PA(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;o<e.length;o++){let a=e[o];for(;;){if(this.tokens.mainToken=null,a.pos>t)i.push(a);else{if(this.advanceStack(a,i,e))continue;{s||(s=[],r=[]),s.push(a);let l=this.tokens.getMainToken(a);r.push(l.value,l.end)}}break}}if(!i.length){let o=s&&KA(s);if(o)return nt&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw nt&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return nt&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((a,l)=>l.score-a.score);i.length>o;)i.pop();i.some(a=>a.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o<i.length-1;o++){let a=i[o];for(let l=o+1;l<i.length;l++){let c=i[l];if(a.sameState(c)||a.buffer.length>500&&c.buffer.length>500)if((a.score-c.score||a.buffer.length-c.buffer.length)>0)i.splice(l--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,a)=>a.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o<i.length;o++)i[o].pos<this.minStackPos&&(this.minStackPos=i[o].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}advanceStack(e,t,i){let s=e.pos,{parser:r}=this,o=nt?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let c=e.curContext&&e.curContext.tracker.strict,h=c?e.curContext.hash:0;for(let u=this.fragments.nodeAt(s);u;){let f=this.parser.nodeSet.types[u.type.id]==u.type?r.getGoto(e.state,u.type.id):-1;if(f>-1&&u.length&&(!c||(u.prop(G.contextHash)||0)==h))return e.useNode(u,f),nt&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(u.type.id)})`),!0;if(!(u instanceof ke)||u.children.length==0||u.positions[0]>0)break;let d=u.children[0];if(d instanceof ke&&u.positions[0]==0)u=d;else break}}let a=r.stateSlot(e.state,4);if(a>0)return e.reduce(a),nt&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(a&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let c=0;c<l.length;){let h=l[c++],u=l[c++],f=l[c++],d=c==l.length||!i,p=d?e:e.split(),m=this.tokens.mainToken;if(p.apply(h,u,m?m.start:p.pos,f),nt&&console.log(o+this.stackID(p)+` (via ${(h&65536)==0?"shift":`reduce of ${r.getName(h&65535)}`} for ${r.getName(u)} @ ${s}${p==e?"":", split"})`),d)return!0;p.pos>s?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return jc(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o<e.length;o++){let a=e[o],l=t[o<<1],c=t[(o<<1)+1],h=nt?this.stackID(a)+" -> ":"";if(a.deadEnd&&(r||(r=!0,a.restart(),nt&&console.log(h+this.stackID(a)+" (restarted)"),this.advanceFully(a,i))))continue;let u=a.split(),f=h;for(let d=0;d<10&&u.forceReduce()&&(nt&&console.log(f+this.stackID(u)+" (via force-reduce)"),!this.advanceFully(u,i));d++)nt&&(f=this.stackID(u)+" -> ");for(let d of a.recoverByInsert(l))nt&&console.log(h+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>a.pos?(c==a.pos&&(c++,l=0),a.recoverByDelete(l,c),nt&&console.log(h+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),jc(a,i)):(!s||s.score<u.score)&&(s=u)}return s}stackToTree(e){return e.close(),ke.build({buffer:Hs.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(no||(no=new WeakMap)).get(e);return t||no.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}}function jc(n,e){for(let t=0;t<e.length;t++){let i=e[t];if(i.pos==n.pos&&i.sameState(n)){e[t].score<n.score&&(e[t]=n);return}}e.push(n)}class RA{constructor(e,t,i){this.source=e,this.flags=t,this.disabled=i}allows(e){return!this.disabled||this.disabled[e]==0}}const so=n=>n;class $A{constructor(e){this.start=e.start,this.shift=e.shift||so,this.reduce=e.reduce||so,this.reuse=e.reuse||so,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Gs extends Yu{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;a<e.repeatNodeCount;a++)t.push("");let i=Object.keys(e.topRules).map(a=>e.topRules[a][1]),s=[];for(let a=0;a<t.length;a++)s.push([]);function r(a,l,c){s[a].push([l,l.deserialize(String(c))])}if(e.nodeProps)for(let a of e.nodeProps){let l=a[0];typeof l=="string"&&(l=G[l]);for(let c=1;c<a.length;){let h=a[c++];if(h>=0)r(h,l,a[c++]);else{let u=a[c+-h];for(let f=-h;f>0;f--)r(a[c++],l,u);c++}}}this.nodeSet=new Ta(t.map((a,l)=>et.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:s[l],top:i.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=qu;let o=dn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;a<this.specializerSpecs.length;a++)this.specialized[a]=this.specializerSpecs[a].term;this.specializers=this.specializerSpecs.map(Yc),this.states=dn(e.states,Uint32Array),this.data=dn(e.stateData),this.goto=dn(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(a=>typeof a=="number"?new Di(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new TA(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],a=o&1,l=s[r++];if(a&&i)return l;for(let c=r+(o>>1);r<c;r++)if(s[r]==e)return l;if(a)return-1}}hasAction(e,t){let i=this.data;for(let s=0;s<2;s++)for(let r=this.stateSlot(e,s?2:1),o;;r+=3){if((o=i[r])==65535)if(i[r+1]==1)o=i[r=Ft(i,r+2)];else{if(i[r+1]==2)return Ft(i,r+2);break}if(o==t||o==0)return Ft(i,r+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Ft(this.data,r+2);else break;s=t(Ft(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ft(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(Gs.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(a=>a.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=Yc(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;r<t.length;r++)if(!i[r])for(let o=this.dialects[t[r]],a;(a=this.data[o++])!=65535;)(s||(s=new Uint8Array(this.maxTerm+1)))[a]=1;return new RA(e,i,s)}static deserialize(e){return new Gs(e)}}function Ft(n,e){return n[e]|n[e+1]<<16}function KA(n){let e=null;for(let t of n){let i=t.p.stoppedAt;(t.pos==t.p.stream.end||i!=null&&t.pos>i)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.score<t.score)&&(e=t)}return e}function Yc(n){if(n.external){let e=n.extend?1:0;return(t,i)=>n.external(t,i)<<1|e}return n.get}const ZA=316,MA=317,Nc=1,EA=2,UA=3,FA=4,DA=318,LA=320,XA=321,BA=5,IA=6,WA=0,ra=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],rd=125,qA=59,oa=47,zA=42,VA=43,jA=45,YA=60,NA=44,HA=63,GA=46,_A=91,JA=new $A({start:!1,shift(n,e){return e==BA||e==IA||e==LA?n:e==XA},strict:!1}),eb=new Wn((n,e)=>{let{next:t}=n;(t==rd||t==-1||e.context)&&n.acceptToken(DA)},{contextual:!0,fallback:!0}),tb=new Wn((n,e)=>{let{next:t}=n,i;ra.indexOf(t)>-1||t==oa&&((i=n.peek(1))==oa||i==zA)||t!=rd&&t!=qA&&t!=-1&&!e.context&&n.acceptToken(ZA)},{contextual:!0}),ib=new Wn((n,e)=>{n.next==_A&&!e.context&&n.acceptToken(MA)},{contextual:!0}),nb=new Wn((n,e)=>{let{next:t}=n;if(t==VA||t==jA){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(Nc);n.acceptToken(i?Nc:EA)}}else t==HA&&n.peek(1)==GA&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(UA))},{contextual:!0});function ro(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}const sb=new Wn((n,e)=>{if(n.next!=YA||!e.dialectEnabled(WA)||(n.advance(),n.next==oa))return;let t=0;for(;ra.indexOf(n.next)>-1;)n.advance(),t++;if(ro(n.next,!0)){for(n.advance(),t++;ro(n.next,!1);)n.advance(),t++;for(;ra.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==NA)return;for(let i=0;;i++){if(i==7){if(!ro(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(FA,-t)}),rb=Nu({"get set async static":O.modifier,"for while do if else switch try catch finally return throw break continue default case defer":O.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":O.operatorKeyword,"let var const using function class extends":O.definitionKeyword,"import export from":O.moduleKeyword,"with debugger new":O.keyword,TemplateString:O.special(O.string),super:O.atom,BooleanLiteral:O.bool,this:O.self,null:O.null,Star:O.modifier,VariableName:O.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":O.function(O.variableName),VariableDefinition:O.definition(O.variableName),Label:O.labelName,PropertyName:O.propertyName,PrivatePropertyName:O.special(O.propertyName),"CallExpression/MemberExpression/PropertyName":O.function(O.propertyName),"FunctionDeclaration/VariableDefinition":O.function(O.definition(O.variableName)),"ClassDeclaration/VariableDefinition":O.definition(O.className),"NewExpression/VariableName":O.className,PropertyDefinition:O.definition(O.propertyName),PrivatePropertyDefinition:O.definition(O.special(O.propertyName)),UpdateOp:O.updateOperator,"LineComment Hashbang":O.lineComment,BlockComment:O.blockComment,Number:O.number,String:O.string,Escape:O.escape,ArithOp:O.arithmeticOperator,LogicOp:O.logicOperator,BitOp:O.bitwiseOperator,CompareOp:O.compareOperator,RegExp:O.regexp,Equals:O.definitionOperator,Arrow:O.function(O.punctuation),": Spread":O.punctuation,"( )":O.paren,"[ ]":O.squareBracket,"{ }":O.brace,"InterpolationStart InterpolationEnd":O.special(O.brace),".":O.derefOperator,", ;":O.separator,"@":O.meta,TypeName:O.typeName,TypeDefinition:O.definition(O.typeName),"type enum interface implements namespace module declare":O.definitionKeyword,"abstract global Privacy readonly override":O.modifier,"is keyof unique infer asserts":O.operatorKeyword,JSXAttributeValue:O.attributeValue,JSXText:O.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":O.angleBracket,"JSXIdentifier JSXNameSpacedName":O.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":O.attributeName,"JSXBuiltin/JSXIdentifier":O.standard(O.tagName)}),ob={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},ab={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},lb={__proto__:null,"<":193},cb=Gs.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}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export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:JA,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[rb],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$<r#p#q$=h#q#r$>x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A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JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr07[$D|k$i&j(Wp(Z!b'}0/l$]#t(T,2j(e$I[OY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[tb,ib,nb,sb,2,3,4,5,6,7,8,9,10,11,12,13,14,eb,new sa("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new sa("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>ob[n]||-1},{term:343,get:n=>ab[n]||-1},{term:95,get:n=>lb[n]||-1}],tokenPrec:15201}),od=[Ye("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ye("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ye("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ye("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ye("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ye(`try { +`){[e,t]=Bi(this,e,t);let s="";for(let r=0,o=0;r<this.children.length&&o<=t;r++){let a=this.children[r],l=o+a.length;o>e&&r&&(s+=i),e<l&&t>o&&(s+=a.sliceString(e-o,t-o,i)),o=l+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof kt))return 0;let i=0,[s,r,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==a)return i;let l=this.children[s],c=e.children[r];if(l!=c)return i+l.scanIdentical(c,t);i+=l.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new we(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,a=[],l=0,c=-1,h=[];function u(d){let p;if(d.lines>r&&d instanceof kt)for(let m of d.children)u(m);else d.lines>o&&(l>o||!l)?(f(),a.push(d)):d instanceof we&&l&&(p=h[h.length-1])instanceof we&&d.lines+p.lines<=32?(l+=d.lines,c+=d.length+1,h[h.length-1]=new we(p.text.concat(d.text),p.length+1+d.length)):(l+d.lines>s&&f(),l+=d.lines,c+=d.length+1,h.push(d))}function f(){l!=0&&(a.push(h.length==1?h[0]:kt.from(h,c)),c=-1,l=h.length=0)}for(let d of e)u(d);return f(),a.length==1?a[0]:new kt(a,t)}}se.empty=new we([""],0);function sp(n){let e=-1;for(let t of n)e+=t.length+1;return e}function ys(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r<n.length&&s<=i;r++){let a=n[r],l=s+a.length;l>=t&&(l>i&&(a=a.slice(0,i-s)),s<t&&(a=a.slice(t-s)),o?(e[e.length-1]+=a,o=!1):e.push(a)),s=l+1}return e}function pl(n,e,t){return ys(n,[""],e,t)}class pn{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof we?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,a=s instanceof we?s.text.length:s.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof we){let l=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=s.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof we?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class vh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new pn(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class wh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(se.prototype[Symbol.iterator]=function(){return this.iter()},pn.prototype[Symbol.iterator]=vh.prototype[Symbol.iterator]=wh.prototype[Symbol.iterator]=function(){return this});class rp{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}}function Bi(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function Ze(n,e,t=!0,i=!0){return ip(n,e,t,i)}function op(n){return n>=56320&&n<57344}function ap(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!ap(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return op(i)?(t-55296<<10)+(i-56320)+65536:t}function ma(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Qt(n){return n<65536?1:2}const Oo=/\r\n?|\n/;var De=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(De||(De={}));class Zt{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t+1];e+=i<0?this.sections[t]:i}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,i=0,s=0;t<this.sections.length;){let r=this.sections[t++],o=this.sections[t++];o<0?(e(i,s,r),s+=r):s+=o,i+=r}}iterChangedRanges(e,t=!1){yo(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let i=this.sections[t++],s=this.sections[t++];s<0?e.push(i,s):e.push(s,i)}return new Zt(e)}composeDesc(e){return this.empty?e:e.empty?this:kh(this,e)}mapDesc(e,t=!1){return e.empty?this:Ao(this,e,t)}mapPos(e,t=-1,i=De.Simple){let s=0,r=0;for(let o=0;o<this.sections.length;){let a=this.sections[o++],l=this.sections[o++],c=s+a;if(l<0){if(c>e)return r+(e-s);r+=a}else{if(i!=De.Simple&&c>=e&&(i==De.TrackDel&&s<e&&c>e||i==De.TrackBefore&&s<e||i==De.TrackAfter&&c>e))return null;if(c>e||c==e&&t<0&&!a)return e==s||t<0?r:r+l;r+=l}s=c}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i<this.sections.length&&s<=t;){let r=this.sections[i++],o=this.sections[i++],a=s+r;if(o>=0&&s<=t&&a>=e)return s<e&&a>t?"cover":!0;s=a}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let i=this.sections[t++],s=this.sections[t++];e+=(e?" ":"")+i+(s>=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Zt(e)}static create(e){return new Zt(e)}}class Re extends Zt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return yo(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Ao(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s<t.length;s+=2){let o=t[s],a=t[s+1];if(a>=0){t[s]=a,t[s+1]=o;let l=s>>1;for(;i.length<l;)i.push(se.empty);i.push(o?e.slice(r,r+o):se.empty)}r+=o}return new Re(t,i)}compose(e){return this.empty?e:e.empty?this:kh(this,e,!0)}map(e,t=!1){return e.empty?this:Ao(this,e,t,!0)}iterChanges(e,t=!1){yo(this,e,t)}get desc(){return Zt.create(this.sections)}filter(e){let t=[],i=[],s=[],r=new Sn(this);e:for(let o=0,a=0;;){let l=o==e.length?1e9:e[o++];for(;a<l||a==l&&r.len==0;){if(r.done)break e;let h=Math.min(r.len,l-a);Xe(s,h,-1);let u=r.ins==-1?-1:r.off==0?r.ins:0;Xe(t,h,u),u>0&&Gt(i,t,r.text),r.forward(h),a+=h}let c=e[o++];for(;a<c;){if(r.done)break e;let h=Math.min(r.len,c-a);Xe(t,h,-1),Xe(s,h,r.ins==-1?-1:r.off==0?r.ins:0),r.forward(h),a+=h}}return{changes:new Re(t,i),filtered:Zt.create(s)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let i=this.sections[t],s=this.sections[t+1];s<0?e.push(i):s==0?e.push([i]):e.push([i].concat(this.inserted[t>>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,a=null;function l(h=!1){if(!h&&!s.length)return;o<t&&Xe(s,t-o,-1);let u=new Re(s,r);a=a?a.compose(u.map(a)):u,s=[],r=[],o=0}function c(h){if(Array.isArray(h))for(let u of h)c(u);else if(h instanceof Re){if(h.length!=t)throw new RangeError(`Mismatched change set length (got ${h.length}, expected ${t})`);l(),a=a?a.compose(h.map(a)):h}else{let{from:u,to:f=u,insert:d}=h;if(u>f||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let p=d?typeof d=="string"?se.of(d.split(i||Oo)):d:se.empty,m=p.length;if(u==f&&m==0)return;u<o&&l(),u>o&&Xe(s,u-o,-1),Xe(s,f-u,m),Gt(r,s,p),o=f}}return c(e),l(!a),a}static empty(e){return new Re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;s<e.length;s++){let r=e[s];if(typeof r=="number")t.push(r,-1);else{if(!Array.isArray(r)||typeof r[0]!="number"||r.some((o,a)=>a&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length<s;)i.push(se.empty);i[s]=se.of(r.slice(1)),t.push(r[0],i[s].length)}}}return new Re(t,i)}static createSet(e,t){return new Re(e,t)}}function Xe(n,e,t,i=!1){if(e==0&&t<=0)return;let s=n.length-2;s>=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function Gt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i<n.length)n[n.length-1]=n[n.length-1].append(t);else{for(;n.length<i;)n.push(se.empty);n.push(t)}}function yo(n,e,t){let i=n.inserted;for(let s=0,r=0,o=0;o<n.sections.length;){let a=n.sections[o++],l=n.sections[o++];if(l<0)s+=a,r+=a;else{let c=s,h=r,u=se.empty;for(;c+=a,h+=l,l&&i&&(u=u.append(i[o-2>>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(s,c,r,h,u),s=c,r=h}}}function Ao(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Sn(n),a=new Sn(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);Xe(s,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len<o.len||a.len==o.len&&!t))){let c=a.len;for(Xe(s,a.ins,-1);c;){let h=Math.min(o.len,c);o.ins>=0&&l<o.i&&o.len<=h&&(Xe(s,0,o.ins),r&&Gt(r,s,o.text),l=o.i),o.forward(h),c-=h}a.next()}else if(o.ins>=0){let c=0,h=o.len;for(;h;)if(a.ins==-1){let u=Math.min(h,a.len);c+=u,h-=u,a.forward(u)}else if(a.ins==0&&a.len<h)h-=a.len,a.next();else break;Xe(s,c,l<o.i?o.ins:0),r&&l<o.i&&Gt(r,s,o.text),l=o.i,o.forward(o.len-h)}else{if(o.done&&a.done)return r?Re.createSet(s,r):Zt.create(s);throw new Error("Mismatched change set lengths")}}}function kh(n,e,t=!1){let i=[],s=t?[]:null,r=new Sn(n),o=new Sn(e);for(let a=!1;;){if(r.done&&o.done)return s?Re.createSet(i,s):Zt.create(i);if(r.ins==0)Xe(i,r.len,0,a),r.next();else if(o.len==0&&!o.done)Xe(i,0,o.ins,a),s&&Gt(s,i,o.text),o.next();else{if(r.done||o.done)throw new Error("Mismatched change set lengths");{let l=Math.min(r.len2,o.len),c=i.length;if(r.ins==-1){let h=o.ins==-1?-1:o.off?0:o.ins;Xe(i,l,h,a),s&&h&&Gt(s,i,o.text)}else o.ins==-1?(Xe(i,r.off?0:r.len,l,a),s&&Gt(s,i,r.textBit(l))):(Xe(i,r.off?0:r.len,o.off?0:o.ins,a),s&&!o.off&&Gt(s,i,o.text));a=(r.ins>l||o.ins>=0&&o.len>l)&&(a||i.length>c),r.forward2(l),o.forward(l)}}}}class Sn{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?se.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?se.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Nt{constructor(e,t,i,s){this.from=e,this.to=t,this.flags=i,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new Nt(i,s,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return A.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return A.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return A.range(e.anchor,e.head)}static create(e,t,i,s){return new Nt(e,t,i,s)}}class A{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:A.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;i<this.ranges.length;i++)if(!this.ranges[i].eq(e.ranges[i],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new A([this.main],0)}addRange(e,t=!0){return A.create([e].concat(this.ranges),t?0:this.mainIndex+1)}replaceRange(e,t=this.mainIndex){let i=this.ranges.slice();return i[t]=e,A.create(i,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new A(e.ranges.map(t=>Nt.fromJSON(t)),e.main)}static single(e,t=e){return new A([A.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;s<e.length;s++){let r=e[s];if(r.empty?r.from<=i:r.from<i)return A.normalized(e.slice(),t);i=r.to}return new A(e,t)}static cursor(e,t=0,i,s){return Nt.create(e,e,(t==0?0:t<0?8:16)|(i==null?7:Math.min(6,i)),s)}static range(e,t,i,s,r){let o=s==null?7:Math.min(6,s);return!r&&e!=t&&(r=t<e?1:-1),r&&(o|=r<0?8:16),t<e?Nt.create(t,e,o|32,i):Nt.create(e,t,o,i)}static undirectionalRange(e,t){return Nt.create(e,t,64,void 0)}static normalized(e,t=0){let i=e[t];e.sort((s,r)=>s.from-r.from),t=e.indexOf(i);for(let s=1;s<e.length;s++){let r=e[s],o=e[s-1];if(r.empty?r.from<=o.to:r.from<o.to){let a=o.from,l=Math.max(r.to,o.to);s<=t&&t--,e.splice(--s,2,r.anchor>r.head?A.range(l,a):A.range(a,l))}}return new A(e,t)}}function Qh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let ga=0;class Z{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=ga++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Oa),!!e.static,e.enables)}of(e){return new As([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new As(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new As(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Oa(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class As{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=ga++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,a=this.type==2,l=!1,c=!1,h=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?c=!0:(((t=e[u.id])!==null&&t!==void 0?t:1)&1)==0&&h.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||c&&(f.docChanged||f.selection)||bo(u,h)){let d=i(u);if(a?!ml(d,u.values[o],s):!s(d,u.values[o]))return u.values[o]=d,1}return 0},reconfigure:(u,f)=>{let d,p=f.config.address[r];if(p!=null){let m=Rs(f,p);if(this.dependencies.every(g=>g instanceof Z?f.facet(g)===u.facet(g):g instanceof Te?f.field(g,!1)==u.field(g,!1):!0)||(a?ml(d=i(u),m,s):s(d=i(u),m)))return u.values[o]=m,0}else d=i(u);return u.values[o]=d,1}}}get extension(){return this}}function ml(n,e,t){if(n.length!=e.length)return!1;for(let i=0;i<n.length;i++)if(!t(n[i],e[i]))return!1;return!0}function bo(n,e){let t=!1;for(let i of e)mn(n,i)&1&&(t=!0);return t}function lp(n,e,t){let i=t.map(l=>n[l.id]),s=t.map(l=>l.type),r=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let c=[];for(let h=0;h<i.length;h++){let u=Rs(l,i[h]);if(s[h]==2)for(let f of u)c.push(f);else c.push(u)}return e.combine(c)}return{create(l){for(let c of i)mn(l,c);return l.values[o]=a(l),1},update(l,c){if(!bo(l,r))return 0;let h=a(l);return e.compare(h,l.values[o])?0:(l.values[o]=h,1)},reconfigure(l,c){let h=bo(l,i),u=c.config.facets[e.id],f=c.facet(e);if(u&&!h&&Oa(t,u))return l.values[o]=f,0;let d=a(l);return e.compare(d,f)?(l.values[o]=f,0):(l.values[o]=d,1)}}}const jn=Z.define({static:!0});class Te{constructor(e,t,i,s,r){this.id=e,this.createF=t,this.updateF=i,this.compareF=s,this.spec=r,this.provides=void 0}static define(e){let t=new Te(ga++,e.create,e.update,e.compare||((i,s)=>i===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(jn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(jn),o=s.facet(jn),a;return(a=r.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(i.values[t]=a.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,jn.of({field:this,create:e})]}get extension(){return this}}const fi={lowest:4,low:3,default:2,high:1,highest:0};function sn(n){return e=>new Ph(e,n)}const oi={highest:sn(fi.highest),high:sn(fi.high),default:sn(fi.default),low:sn(fi.low),lowest:sn(fi.lowest)};class Ph{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class Gi{of(e){return new So(this,e)}reconfigure(e){return Gi.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class So{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class Ts{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length<i.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let f of cp(e,t,o))f instanceof Te?s.push(f):(r[f.facet.id]||(r[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],c=[];for(let f of s)a[f.id]=c.length<<1,c.push(d=>f.slot(d));let h=i?.config.facets;for(let f in r){let d=r[f],p=d[0].facet,m=h&&h[f]||[];if(d.every(g=>g.type==0))if(a[p.id]=l.length<<1|1,Oa(m,d))l.push(i.facet(p));else{let g=p.combine(d.map(y=>y.value));l.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(a[g.id]=l.length<<1|1,l.push(g.value)):(a[g.id]=c.length<<1,c.push(y=>g.dynamicSlot(y)));a[p.id]=c.length<<1,c.push(g=>lp(g,p,d))}}let u=c.map(f=>f(a));return new Ts(e,o,u,a,l,r)}}function cp(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,a){let l=s.get(o);if(l!=null){if(l<=a)return;let c=i[l].indexOf(o);c>-1&&i[l].splice(c,1),o instanceof So&&t.delete(o.compartment)}if(s.set(o,a),Array.isArray(o))for(let c of o)r(c,a);else if(o instanceof So){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;t.set(o.compartment,c),r(c,a)}else if(o instanceof Ph)r(o.inner,o.prec);else if(o instanceof Te)i[a].push(o),o.provides&&r(o.provides,a);else if(o instanceof As)i[a].push(o),o.facet.extensions&&r(o.facet.extensions,fi.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(c==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(c,a)}}return r(n,fi.default),i.reduce((o,a)=>o.concat(a))}function mn(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Rs(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Ch=Z.define(),xo=Z.define({combine:n=>n.some(e=>e),static:!0}),Th=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),Rh=Z.define(),$h=Z.define(),Kh=Z.define(),Zh=Z.define({combine:n=>n.length?n[0]:!1});class zt{constructor(e,t){this.type=e,this.value=t}static define(){return new hp}}class hp{of(e){return new zt(this,e)}}class up{constructor(e){this.map=e}of(e){return new Y(this,e)}}class Y{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new Y(this.type,t)}is(e){return this.type==e}static define(e={}){return new up(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}}Y.reconfigure=Y.define();Y.appendConfig=Y.define();class Pe{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Qh(i,t.newLength),r.some(a=>a.type==Pe.time)||(this.annotations=r.concat(Pe.time.of(Date.now())))}static create(e,t,i,s,r,o){return new Pe(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(Pe.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}Pe.time=zt.define();Pe.userEvent=zt.define();Pe.addToHistory=zt.define();Pe.remote=zt.define();function fp(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i<n.length&&(s==e.length||e[s]>=n[i]))r=n[i++],o=n[i++];else if(s<e.length)r=e[s++],o=e[s++];else return t;!t.length||t[t.length-1]<r?t.push(r,o):t[t.length-1]<o&&(t[t.length-1]=o)}}function Mh(n,e,t){var i;let s,r,o;return t?(s=e.changes,r=Re.empty(e.changes.length),o=n.changes.compose(e.changes)):(s=e.changes.map(n.changes),r=n.changes.mapDesc(e.changes,!0),o=n.changes.compose(s)),{changes:o,selection:e.selection?e.selection.map(r):(i=n.selection)===null||i===void 0?void 0:i.map(s),effects:Y.mapEffects(n.effects,s).concat(Y.mapEffects(e.effects,r)),annotations:n.annotations.length?n.annotations.concat(e.annotations):e.annotations,scrollIntoView:n.scrollIntoView||e.scrollIntoView}}function vo(n,e,t){let i=e.selection,s=Zi(e.annotations);return e.userEvent&&(s=s.concat(Pe.userEvent.of(e.userEvent))),{changes:e.changes instanceof Re?e.changes:Re.of(e.changes||[],t,n.facet(Th)),selection:i&&(i instanceof A?i:A.single(i.anchor,i.head)),effects:Zi(e.effects),annotations:s,scrollIntoView:!!e.scrollIntoView}}function Eh(n,e,t){let i=vo(n,e.length?e[0]:{},n.doc.length);e.length&&e[0].filter===!1&&(t=!1);for(let r=1;r<e.length;r++){e[r].filter===!1&&(t=!1);let o=!!e[r].sequential;i=Mh(i,vo(n,e[r],o?i.changes.newLength:n.doc.length),o)}let s=Pe.create(n,i.changes,i.selection,i.effects,i.annotations,i.scrollIntoView);return pp(t?dp(s):s)}function dp(n){let e=n.startState,t=!0;for(let s of e.facet(Rh)){let r=s(n);if(r===!1){t=!1;break}Array.isArray(r)&&(t=t===!0?r:fp(t,r))}if(t!==!0){let s,r;if(t===!1)r=n.changes.invertedDesc,s=Re.empty(e.doc.length);else{let o=n.changes.filter(t);s=o.changes,r=o.filtered.mapDesc(o.changes).invertedDesc}n=Pe.create(e,s,n.selection&&n.selection.map(r),Y.mapEffects(n.effects,r),n.annotations,n.scrollIntoView)}let i=e.facet($h);for(let s=i.length-1;s>=0;s--){let r=i[s](n);r instanceof Pe?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof Pe?n=r[0]:n=Eh(e,Zi(r),!1)}return n}function pp(n){let e=n.startState,t=e.facet(Kh),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=Mh(i,vo(e,r,n.changes.newLength),!0))}return i==n?n:Pe.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const mp=[];function Zi(n){return n==null?mp:Array.isArray(n)?n:[n]}var ye=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(ye||(ye={}));const gp=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wo;try{wo=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Op(n){if(wo)return wo.test(n);for(let e=0;e<n.length;e++){let t=n[e];if(/\w/.test(t)||t>"€"&&(t.toUpperCase()!=t.toLowerCase()||gp.test(t)))return!0}return!1}function yp(n){return e=>{if(!/\S/.test(e))return ye.Space;if(Op(e))return ye.Word;for(let t=0;t<n.length;t++)if(e.indexOf(n[t])>-1)return ye.Word;return ye.Other}}class J{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let a=0;a<this.config.dynamicSlots.length;a++)mn(this,a<<1);this.computeSlot=null}field(e,t=!0){let i=this.config.address[e.id];if(i==null){if(t)throw new RangeError("Field is not present in this state");return}return mn(this,i),Rs(this,i)}update(...e){return Eh(this,e,!0)}applyTransaction(e){let t=this.config,{base:i,compartments:s}=t;for(let a of e.effects)a.is(Gi.reconfigure)?(t&&(s=new Map,t.compartments.forEach((l,c)=>s.set(c,l)),t=null),s.set(a.value.compartment,a.value.extension)):a.is(Y.reconfigure)?(t=null,i=a.value):a.is(Y.appendConfig)&&(t=null,i=Zi(i).concat(a.value));let r;t?r=e.startState.values.slice():(t=Ts.resolve(i,s,this),r=new J(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(xo)?e.newSelection:e.newSelection.asSingle();new J(t,e.newDoc,o,r,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:A.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Zi(i.effects);for(let a=1;a<t.ranges.length;a++){let l=e(t.ranges[a]),c=this.changes(l.changes),h=c.map(s);for(let f=0;f<a;f++)r[f]=r[f].map(h);let u=s.mapDesc(c,!0);r.push(l.range.map(u)),s=s.compose(h),o=Y.mapEffects(o,h).concat(Y.mapEffects(Zi(l.effects),u))}return{changes:s,selection:A.create(r,t.mainIndex),effects:o}}changes(e=[]){return e instanceof Re?e:Re.of(e,this.doc.length,this.facet(J.lineSeparator))}toText(e){return se.of(e.split(this.facet(J.lineSeparator)||Oo))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(mn(this,t),Rs(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let i in e){let s=e[i];s instanceof Te&&this.config.address[s.id]!=null&&(t[i]=s.spec.toJSON(this.field(e[i]),this))}return t}static fromJSON(e,t={},i){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let s=[];if(i){for(let r in i)if(Object.prototype.hasOwnProperty.call(e,r)){let o=i[r],a=e[r];s.push(o.init(l=>o.spec.fromJSON(a,l)))}}return J.create({doc:e.doc,selection:A.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=Ts.resolve(e.extensions||[],new Map),i=e.doc instanceof se?e.doc:se.of((e.doc||"").split(t.staticFacet(J.lineSeparator)||Oo)),s=e.selection?e.selection instanceof A?e.selection:A.single(e.selection.anchor,e.selection.head):A.single(0);return Qh(s,i.length),t.staticFacet(xo)||(s=s.asSingle()),new J(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(J.tabSize)}get lineBreak(){return this.facet(J.lineSeparator)||` +`}get readOnly(){return this.facet(Zh)}phrase(e,...t){for(let i of this.facet(J.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(Ch))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return yp(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,a=e-i;for(;o>0;){let l=Ze(t,o,!1);if(r(t.slice(l,o))!=ye.Word)break;o=l}for(;a<s;){let l=Ze(t,a);if(r(t.slice(a,l))!=ye.Word)break;a=l}return o==a?null:A.range(o+i,a+i)}}J.allowMultipleSelections=xo;J.tabSize=Z.define({combine:n=>n.length?n[0]:4});J.lineSeparator=Th;J.readOnly=Zh;J.phrases=Z.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});J.languageData=Ch;J.changeFilter=Rh;J.transactionFilter=$h;J.transactionExtender=Kh;Gi.reconfigure=Y.define();function yt(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],a=i[r];if(a===void 0)i[r]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](a,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}class ei{eq(e){return this==e}range(e,t=e){return ko.create(e,t,this)}}ei.prototype.startSide=ei.prototype.endSide=0;ei.prototype.point=!1;ei.prototype.mapMode=De.TrackDel;function ya(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}let ko=class Uh{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new Uh(e,t,i)}};function Qo(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class Aa{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,a=r.length;;){if(o==a)return o;let l=o+a>>1,c=r[l]-e||(i?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);r<o;r++)if(s(this.from[r]+e,this.to[r]+e,this.value[r])===!1)return!1}map(e,t){let i=[],s=[],r=[],o=-1,a=-1;for(let l=0;l<this.value.length;l++){let c=this.value[l],h=this.from[l]+e,u=this.to[l]+e,f,d;if(h==u){let p=t.mapPos(h,c.startSide,c.mapMode);if(p==null||(f=d=p,c.startSide!=c.endSide&&(d=t.mapPos(h,c.endSide),d<f)))continue}else if(f=t.mapPos(h,c.startSide),d=t.mapPos(u,c.endSide),f>d||f==d&&c.startSide>0&&c.endSide<=0)continue;(d-f||c.endSide-c.startSide)<0||(o<0&&(o=f),c.point&&(a=Math.max(a,d-f)),i.push(c),s.push(f-o),r.push(d-o))}return{mapped:i.length?new Aa(s,r,i,a):null,pos:o}}}class H{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new H(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Qo)),this.isEmpty)return t.length?H.of(t):this;let a=new Fh(this,null,-1).goto(0),l=0,c=[],h=new It;for(;a.value||l<t.length;)if(l<t.length&&(a.from-t[l].from||a.startSide-t[l].value.startSide)>=0){let u=t[l++];h.addInner(u.from,u.to,u.value)||c.push(u)}else a.rangeIndex==1&&a.chunkIndex<this.chunk.length&&(l==t.length||this.chunkEnd(a.chunkIndex)<t[l].from)&&(!o||s>this.chunkEnd(a.chunkIndex)||r<this.chunkPos[a.chunkIndex])&&h.addChunk(this.chunkPos[a.chunkIndex],this.chunk[a.chunkIndex])?a.nextChunk():((!o||s>a.to||r<a.from||o(a.from,a.to,a.value))&&(h.addInner(a.from,a.to,a.value)||c.push(ko.create(a.from,a.to,a.value))),a.next());return h.finishInner(this.nextLayer.isEmpty&&!c.length?H.empty:this.nextLayer.update({add:c,filter:o,filterFrom:s,filterTo:r}))}map(e){if(e.empty||this.isEmpty)return this;let t=[],i=[],s=-1;for(let o=0;o<this.chunk.length;o++){let a=this.chunkPos[o],l=this.chunk[o],c=e.touchesRange(a,a+l.length);if(c===!1)s=Math.max(s,l.maxPoint),t.push(l),i.push(e.mapPos(a));else if(c===!0){let{mapped:h,pos:u}=l.map(a,e);h&&(s=Math.max(s,h.maxPoint),t.push(h),i.push(u))}}let r=this.nextLayer.map(e);return t.length==0?r:new H(i,t,r||H.empty,s)}between(e,t,i){if(!this.isEmpty){for(let s=0;s<this.chunk.length;s++){let r=this.chunkPos[s],o=this.chunk[s];if(t>=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return xn.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return xn.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),l=gl(o,a,i),c=new rn(o,l,r),h=new rn(a,l,r);i.iterGaps((u,f,d)=>Ol(c,u,h,f,d,s)),i.empty&&i.length==0&&Ol(c,0,h,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),o=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let a=gl(r,o),l=new rn(r,a,0).goto(i),c=new rn(o,a,0).goto(i);for(;;){if(l.to!=c.to||!Po(l.active,c.active)||l.point&&(!c.point||!ya(l.point,c.point)))return!1;if(l.to>s)return!0;l.next(),c.next()}}static spans(e,t,i,s,r=-1){let o=new rn(e,null,r).goto(t),a=t,l=o.openStart;for(;;){let c=Math.min(o.to,i);if(o.point){let h=o.activeForPoint(o.to),u=o.pointFrom<t?h.length+1:o.point.startSide<0?h.length:Math.min(h.length,l);s.point(a,c,o.point,h,u,o.pointRank),l=Math.min(o.openEnd(c),h.length)}else c>a&&(s.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>i)return l+(o.point&&o.to>i?1:0);a=o.to,o.next()}}static of(e,t=!1){let i=new It;for(let s of e instanceof ko?[e]:t?Ap(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return H.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=H.empty;s=s.nextLayer)t=new H(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}}H.empty=new H([],[],null,-1);function Ap(n){if(n.length>1)for(let e=n[0],t=1;t<n.length;t++){let i=n[t];if(Qo(e,i)>0)return n.slice().sort(Qo);e=i}return n}H.empty.nextLayer=H.empty;class It{finishChunk(e){this.chunks.push(new Aa(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new It)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(H.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=H.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function gl(n,e,t){let i=new Map;for(let r of n)for(let o=0;o<r.chunk.length;o++)r.chunk[o].maxPoint<=0&&i.set(r.chunk[o],r.chunkPos[o]);let s=new Set;for(let r of e)for(let o=0;o<r.chunk.length;o++){let a=i.get(r.chunk[o]);a!=null&&(t?t.mapPos(a):a)==r.chunkPos[o]&&!t?.touchesRange(a,a+r.chunk[o].length)&&s.add(r.chunk[o])}return s}class Fh{constructor(e,t,i,s=0){this.layer=e,this.skip=t,this.minPoint=i,this.rank=s}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(e,t=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(e,t,!1),this}gotoInner(e,t,i){for(;this.chunkIndex<this.layer.chunk.length;){let s=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(s)||this.layer.chunkEnd(this.chunkIndex)<e||s.maxPoint<this.minPoint))break;this.chunkIndex++,i=!1}if(this.chunkIndex<this.layer.chunk.length){let s=this.layer.chunk[this.chunkIndex].findIndex(e-this.layer.chunkPos[this.chunkIndex],t,!0);(!i||this.rangeIndex<s)&&this.setRangeIndex(s)}this.next()}forward(e,t){(this.to-e||this.endSide-t)<0&&this.gotoInner(e,t,!0)}next(){for(;;)if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}else{let e=this.layer.chunkPos[this.chunkIndex],t=this.layer.chunk[this.chunkIndex],i=e+t.from[this.rangeIndex];if(this.from=i,this.to=e+t.to[this.rangeIndex],this.value=t.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=e}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(e){return this.from-e.from||this.startSide-e.startSide||this.rank-e.rank||this.to-e.to||this.endSide-e.endSide}}class xn{constructor(e){this.heap=e}static from(e,t=null,i=-1){let s=[];for(let r=0;r<e.length;r++)for(let o=e[r];!o.isEmpty;o=o.nextLayer)o.maxPoint>=i&&s.push(new Fh(o,t,i,r));return s.length==1?s[0]:new xn(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Kr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Kr(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Kr(this.heap,0)}}}function Kr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1<n.length&&s.compare(n[i+1])>=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}class rn{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=xn.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Yn(this.active,e),Yn(this.activeTo,e),Yn(this.activeRank,e),this.minActive=yl(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t<this.activeRank.length&&(r-this.activeRank[t]||s-this.activeTo[t])>0;)t++;Nn(this.active,t,i),Nn(this.activeTo,t,s),Nn(this.activeRank,t,r),e&&Nn(e,t,this.cursor.from),this.minActive=yl(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&Yn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)this.cursor.next();else{this.point=r,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=r.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}}else{this.to=this.endSide=1e9;break}}if(i){this.openStart=0;for(let s=i.length-1;s>=0&&i[s]<e;s--)this.openStart++}}activeForPoint(e){if(!this.active.length)return this.active;let t=[];for(let i=this.active.length-1;i>=0&&!(this.activeRank[i]<this.pointRank);i--)(this.activeTo[i]>e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function Ol(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,a=i,l=i-e,c=!!r.boundChange;for(let h=!1;;){let u=n.to+l-t.to,f=u||n.endSide-t.endSide,d=f<0?n.to+l:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&ya(n.point,t.point)&&Po(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(a,p,n.point,t.point),h=!1):(h&&r.boundChange(a),p>a&&!Po(n.active,t.active)&&r.compareRange(a,p,n.active,t.active),c&&p<o&&(u||n.openEnd(d)!=t.openEnd(d))&&(h=!0)),d>o)break;a=d,f<=0&&n.next(),f>=0&&t.next()}}function Po(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!=e[t]&&!ya(n[t],e[t]))return!1;return!0}function Yn(n,e){for(let t=e,i=n.length-1;t<i;t++)n[t]=n[t+1];n.pop()}function Nn(n,e,t){for(let i=n.length-1;i>=e;i--)n[i+1]=n[i];n[e]=t}function yl(n,e){let t=-1,i=1e9;for(let s=0;s<e.length;s++)(e[s]-i||n[s].endSide-n[t].endSide)<0&&(t=s,i=e[s]);return t}function _i(n,e,t=n.length){let i=0;for(let s=0;s<t&&s<n.length;)n.charCodeAt(s)==9?(i+=e-i%e,s++):(i++,s=Ze(n,s));return i}function Co(n,e,t,i){for(let s=0,r=0;;){if(r>=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=Ze(n,s)}return i===!0?-1:n.length}const To="ͼ",Al=typeof Symbol>"u"?"__"+To:Symbol.for(To),Ro=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),bl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class ti{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,a,l,c){let h=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let d in a){let p=a[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,l);else if(p&&typeof p=="object"){if(!u)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,h,f)}else p!=null&&h.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(h.length||f)&&l.push((i&&!u&&!c?o.map(i):o).join(", ")+" {"+h.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=bl[Al]||1;return bl[Al]=e+1,To+e.toString(36)}static mount(e,t,i){let s=e[Ro],r=i&&i.nonce;s?r&&s.setNonce(r):s=new bp(e,r),s.mount(Array.isArray(t)?t:[t],e)}}let Sl=new Map;class bp{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=Sl.get(i);if(r)return e[Ro]=r;this.sheet=new s.CSSStyleSheet,Sl.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Ro]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o<e.length;o++){let a=e[o],l=this.modules.indexOf(a);if(l<r&&l>-1&&(this.modules.splice(l,1),r--,l=-1),l==-1){if(this.modules.splice(r++,0,a),i)for(let c=0;c<a.rules.length;c++)i.insertRule(a.rules[c],s++)}else{for(;r<l;)s+=this.modules[r++].rules.length;s+=a.rules.length,r++}}if(i)t.adoptedStyleSheets.indexOf(this.sheet)<0&&(t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets]);else{let o="";for(let l=0;l<this.modules.length;l++)o+=this.modules[l].getRules()+` +`;this.styleTag.textContent=o;let a=t.head||t;this.styleTag.parentNode!=a&&a.insertBefore(this.styleTag,a.firstChild)}}setNonce(e){this.styleTag&&this.styleTag.getAttribute("nonce")!=e&&this.styleTag.setAttribute("nonce",e)}}var ii={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",229:"q"},vn={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"',229:"Q"},xl=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),Sp=typeof navigator<"u"&&/Apple Computer/.test(navigator.vendor),xp=typeof navigator<"u"&&/Gecko\/\d+/.test(navigator.userAgent),vl=typeof navigator<"u"&&/Mac/.test(navigator.platform),vp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),wp=xl&&(vl||+xl[1]<57)||xp&&vl;for(var Fe=0;Fe<10;Fe++)ii[48+Fe]=ii[96+Fe]=String(Fe);for(var Fe=1;Fe<=24;Fe++)ii[Fe+111]="F"+Fe;for(var Fe=65;Fe<=90;Fe++)ii[Fe]=String.fromCharCode(Fe+32),vn[Fe]=String.fromCharCode(Fe);for(var Zr in ii)vn.hasOwnProperty(Zr)||(vn[Zr]=ii[Zr]);function kp(n){var e=wp&&(n.ctrlKey||n.altKey||n.metaKey)||(Sp||vp)&&n.shiftKey&&n.key&&n.key.length==1,t=!e&&n.key||(n.shiftKey?vn:ii)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function he(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e<arguments.length;e++)Dh(n,arguments[e]);return n}function Dh(n,e){if(typeof e=="string")n.appendChild(document.createTextNode(e));else if(e!=null)if(e.nodeType!=null)n.appendChild(e);else if(Array.isArray(e))for(var t=0;t<e.length;t++)Dh(n,e[t]);else throw new RangeError("Unsupported child node: "+e)}let qe=typeof navigator<"u"?navigator:{userAgent:"",vendor:"",platform:""},$o=typeof document<"u"?document:{documentElement:{style:{}}};const Ko=/Edge\/(\d+)/.exec(qe.userAgent),Lh=/MSIE \d/.test(qe.userAgent),Zo=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(qe.userAgent),fr=!!(Lh||Zo||Ko),wl=!fr&&/gecko\/(\d+)/i.test(qe.userAgent),Mr=!fr&&/Chrome\/(\d+)/.exec(qe.userAgent),kl="webkitFontSmoothing"in $o.documentElement.style,Mo=!fr&&/Apple Computer/.test(qe.vendor),Ql=Mo&&(/Mobile\/\w+/.test(qe.userAgent)||qe.maxTouchPoints>2);var $={mac:Ql||/Mac/.test(qe.platform),windows:/Win/.test(qe.platform),linux:/Linux|X11/.test(qe.platform),ie:fr,ie_version:Lh?$o.documentMode||6:Zo?+Zo[1]:Ko?+Ko[1]:0,gecko:wl,gecko_version:wl?+(/Firefox\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,chrome:!!Mr,chrome_version:Mr?+Mr[1]:0,ios:Ql,android:/Android\b/.test(qe.userAgent),webkit:kl,webkit_version:kl?+(/\bAppleWebKit\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,safari:Mo,safari_version:Mo?+(/\bVersion\/(\d+(\.\d+)?)/.exec(qe.userAgent)||[0,0])[1]:0,tabSize:$o.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function ba(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}const $s=Object.create(null);function Sa(n,e,t){if(n==e)return!0;n||(n=$s),e||(e=$s);let i=Object.keys(n),s=Object.keys(e);if(i.length-0!=s.length-0)return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function Qp(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function Pl(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function Pp(n){let e=Object.create(null);for(let t=0;t<n.attributes.length;t++){let i=n.attributes[t];e[i.name]=i.value}return e}class Ut{eq(e){return!1}updateDOM(e,t,i){return!1}compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(e){return!0}coordsAt(e,t,i){return null}get isHidden(){return!1}get editable(){return!1}destroy(e){}}var Le=(function(n){return n[n.Text=0]="Text",n[n.WidgetBefore=1]="WidgetBefore",n[n.WidgetAfter=2]="WidgetAfter",n[n.WidgetRange=3]="WidgetRange",n})(Le||(Le={}));class I extends ei{constructor(e,t,i,s){super(),this.startSide=e,this.endSide=t,this.widget=i,this.spec=s}get heightRelevant(){return!1}static mark(e){return new Fn(e)}static widget(e){let t=Math.max(-1e4,Math.min(1e4,e.side||0)),i=!!e.block;return t+=i&&!e.inlineOrder?t>0?3e8:-4e8:t>0?1e8:-1e8,new Ai(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Xh(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Ai(e,i,s,t,e.widget||null,!0)}static line(e){return new Dn(e)}static set(e,t=!1){return H.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}I.none=H.empty;class Fn extends I{constructor(e){let{start:t,end:i}=Xh(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?ba(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||$s}eq(e){return this==e||e instanceof Fn&&this.tagName==e.tagName&&Sa(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Fn.prototype.point=!1;class Dn extends I{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Dn&&this.spec.class==e.spec.class&&Sa(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Dn.prototype.mapMode=De.TrackBefore;Dn.prototype.point=!0;class Ai extends I{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?De.TrackBefore:De.TrackAfter:De.TrackDel}get type(){return this.startSide!=this.endSide?Le.WidgetRange:this.startSide<=0?Le.WidgetBefore:Le.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof Ai&&Cp(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Ai.prototype.point=!0;function Xh(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function Cp(n,e){return n==e||!!(n&&e&&n.compare(e))}function Mi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}class wn extends ei{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof wn&&this.tagName==e.tagName&&Sa(this.attributes,e.attributes)}static create(e){return new wn(e.tagName,e.attributes||$s,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return H.of(e,t)}}wn.prototype.startSide=wn.prototype.endSide=-1;function kn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Eo(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function gn(n,e){if(!e.anchorNode)return!1;try{return Eo(n,e.anchorNode)}catch{return!1}}function bs(n){return n.nodeType==3?Qn(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function On(n,e,t,i){return t?Cl(n,e,t,i,-1)||Cl(n,e,t,i,1):!1}function ni(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Ks(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function Cl(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:Wt(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=ni(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?Wt(n):0}else return!1}}function Wt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Zs(n,e){let{left:t,right:i}=n;if(t==i)return n;let s=e?t:i;return{left:s,right:s,top:n.top,bottom:n.bottom}}function Tp(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Bh(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Rp(n,e,t,i,s,r,o,a){let l=n.ownerDocument,c=l.defaultView||window;for(let h=n,u=!1;h&&!u;)if(h.nodeType==1){let f,d=h==l.body,p=1,m=1;if(d)f=Tp(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(h).position)&&(u=!0),h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let x=h.getBoundingClientRect();({scaleX:p,scaleY:m}=Bh(h,x)),f={left:x.left,right:x.left+h.clientWidth*p,top:x.top,bottom:x.top+h.clientHeight*m}}let g=0,y=0;if(s=="nearest")e.top<f.top+o?(y=e.top-(f.top+o),t>0&&e.bottom>f.bottom+y&&(y=e.bottom-f.bottom+o)):e.bottom>f.bottom-o&&(y=e.bottom-f.bottom+o,t<0&&e.top-y<f.top&&(y=e.top-(f.top+o)));else{let x=e.bottom-e.top,b=f.bottom-f.top;y=(s=="center"&&x<=b?e.top+x/2-b/2:s=="start"||s=="center"&&t<0?e.top-o:e.bottom-b+o)-f.top}if(i=="nearest"?e.left<f.left+r?(g=e.left-(f.left+r),t>0&&e.right>f.right+g&&(g=e.right-f.right+r)):e.right>f.right-r&&(g=e.right-f.right+r,t<0&&e.left<f.left+g&&(g=e.left-(f.left+r))):g=(i=="center"?e.left+(e.right-e.left)/2-(f.right-f.left)/2:i=="start"==a?e.left-r:e.right-(f.right-f.left)+r)-f.left,g||y)if(d)c.scrollBy(g,y);else{let x=0,b=0;if(y){let C=h.scrollTop;h.scrollTop+=y/m,b=(h.scrollTop-C)*m}if(g){let C=h.scrollLeft;h.scrollLeft+=g/p,x=(h.scrollLeft-C)*p}e={left:e.left-x,top:e.top-b,right:e.right-x,bottom:e.bottom-b},x&&Math.abs(x-g)<1&&(i="nearest"),b&&Math.abs(b-y)<1&&(s="nearest")}if(d)break;(e.top<f.top||e.bottom>f.bottom||e.left<f.left||e.right>f.right)&&(e={left:Math.max(e.left,f.left),right:Math.min(e.right,f.right),top:Math.max(e.top,f.top),bottom:Math.min(e.bottom,f.bottom)}),h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function Ih(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}class $p{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?Wt(t):0),i,Math.min(e.focusOffset,i?Wt(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}}function Wh(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function qh(n,e=!0){for(let{node:t,left:i,top:s}of n)e&&t.scrollTop!=s&&(t.scrollTop=s),t.scrollLeft!=i&&(t.scrollLeft=i)}let ui=null;$.safari&&$.safari_version>=26&&(ui=!1);function zh(n){if(n.setActive)return n.setActive();if(ui)return n.focus(ui);let e=Wh(n);n.focus(ui==null?{get preventScroll(){return ui={preventScroll:!0},!0}}:void 0),ui||(ui=!1,qh(e))}let Tl;function Qn(n,e,t=e){let i=Tl||(Tl=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function Ei(n,e,t,i){let s={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=i);let r=new KeyboardEvent("keydown",s);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function Kp(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function Zp(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,Wt(t));;)if(i){if(t.nodeType!=1)return!1;let s=t.childNodes[i-1];s.contentEditable=="false"?i--:(t=s,i=Wt(t))}else{if(t==n)return!0;i=ni(t),t=t.parentNode}}function Vh(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function jh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=Wt(t)}else if(t.parentNode&&!Ks(t))i=ni(t),t=t.parentNode;else return null}}function Yh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i<t.nodeValue.length)return{node:t,offset:i};if(t.nodeType==1&&i<t.childNodes.length){if(t.contentEditable=="false")return null;t=t.childNodes[i],i=0}else if(t.parentNode&&!Ks(t))i=ni(t)+1,t=t.parentNode;else return null}}class pt{constructor(e,t,i=!0){this.node=e,this.offset=t,this.precise=i}static before(e,t){return new pt(e.parentNode,ni(e),t)}static after(e,t){return new pt(e.parentNode,ni(e)+1,t)}}var fe=(function(n){return n[n.LTR=0]="LTR",n[n.RTL=1]="RTL",n})(fe||(fe={}));const bi=fe.LTR,xa=fe.RTL;function Nh(n){let e=[];for(let t=0;t<n.length;t++)e.push(1<<+n[t]);return e}const Mp=Nh("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),Ep=Nh("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),Uo=Object.create(null),St=[];for(let n of["()","[]","{}"]){let e=n.charCodeAt(0),t=n.charCodeAt(1);Uo[e]=t,Uo[t]=-e}function Hh(n){return n<=247?Mp[n]:1424<=n&&n<=1524?2:1536<=n&&n<=1785?Ep[n-1536]:1774<=n&&n<=2220?4:8192<=n&&n<=8204?256:64336<=n&&n<=65023?4:1}const Up=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;class Ct{get dir(){return this.level%2?xa:bi}constructor(e,t,i){this.from=e,this.to=t,this.level=i}side(e,t){return this.dir==t==e?this.to:this.from}forward(e,t){return e==(this.dir==t)}static find(e,t,i,s){let r=-1;for(let o=0;o<e.length;o++){let a=e[o];if(a.from<=t&&a.to>=t){if(a.level==i)return o;(r<0||(s!=0?s<0?a.from<t:a.to>t:e[r].level>a.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}function Gh(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++){let i=n[t],s=e[t];if(i.from!=s.from||i.to!=s.to||i.direction!=s.direction||!Gh(i.inner,s.inner))return!1}return!0}const ue=[];function Fp(n,e,t,i,s){for(let r=0;r<=i.length;r++){let o=r?i[r-1].to:e,a=r<i.length?i[r].from:t,l=r?256:s;for(let c=o,h=l,u=l;c<a;c++){let f=Hh(n.charCodeAt(c));f==512?f=h:f==8&&u==4&&(f=16),ue[c]=f==4?2:f,f&7&&(u=f),h=f}for(let c=o,h=l,u=l;c<a;c++){let f=ue[c];if(f==128)c<a-1&&h==ue[c+1]&&h&24?f=ue[c]=h:ue[c]=256;else if(f==64){let d=c+1;for(;d<a&&ue[d]==64;)d++;let p=c&&h==8||d<t&&ue[d]==8?u==1?1:8:256;for(let m=c;m<d;m++)ue[m]=p;c=d-1}else f==8&&u==1&&(ue[c]=1);h=f,f&7&&(u=f)}}}function Dp(n,e,t,i,s){let r=s==1?2:1;for(let o=0,a=0,l=0;o<=i.length;o++){let c=o?i[o-1].to:e,h=o<i.length?i[o].from:t;for(let u=c,f,d,p;u<h;u++)if(d=Uo[f=n.charCodeAt(u)])if(d<0){for(let m=a-3;m>=0;m-=3)if(St[m+1]==-d){let g=St[m+2],y=g&2?s:g&4?g&1?r:s:0;y&&(ue[u]=ue[St[m]]=y),a=m;break}}else{if(St.length==189)break;St[a++]=u,St[a++]=f,St[a++]=l}else if((p=ue[u])==2||p==1){let m=p==s;l=m?0:1;for(let g=a-3;g>=0;g-=3){let y=St[g+2];if(y&2)break;if(m)St[g+2]|=2;else{if(y&4)break;St[g+2]|=4}}}}}function Lp(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,a=s<t.length?t[s].from:e;for(let l=o;l<a;){let c=ue[l];if(c==256){let h=l+1;for(;;)if(h==a){if(s==t.length)break;h=t[s++].to,a=s<t.length?t[s].from:e}else if(ue[h]==256)h++;else break;let u=r==1,f=(h<e?ue[h]:i)==1,d=u==f?u?1:2:i;for(let p=h,m=s,g=m?t[m-1].to:n;p>l;)p==g&&(p=t[--m].from,g=m?t[m-1].to:n),ue[--p]=d;l=h}else r=c,l++}}}function Fo(n,e,t,i,s,r,o){let a=i%2?2:1;if(i%2==s%2)for(let l=e,c=0;l<t;){let h=!0,u=!1;if(c==r.length||l<r[c].from){let m=ue[l];m!=a&&(h=!1,u=m==16)}let f=!h&&a==1?[]:null,d=h?i:i+1,p=l;e:for(;;)if(c<r.length&&p==r[c].from){if(u)break e;let m=r[c];if(!h)for(let g=m.to,y=c+1;;){if(g==t)break e;if(y<r.length&&r[y].from==g)g=r[y++].to;else{if(ue[g]==a)break e;break}}if(c++,f)f.push(m);else{m.from>l&&o.push(new Ct(l,m.from,d));let g=m.direction==bi!=!(d%2);Do(n,g?i+1:i,s,m.inner,m.from,m.to,o),l=m.to}p=m.to}else{if(p==t||(h?ue[p]!=a:ue[p]==a))break;p++}f?Fo(n,l,p,i+1,s,f,o):l<p&&o.push(new Ct(l,p,d)),l=p}else for(let l=t,c=r.length;l>e;){let h=!0,u=!1;if(!c||l>r[c-1].to){let m=ue[l-1];m!=a&&(h=!1,u=m==16)}let f=!h&&a==1?[]:null,d=h?i:i+1,p=l;e:for(;;)if(c&&p==r[c-1].to){if(u)break e;let m=r[--c];if(!h)for(let g=m.from,y=c;;){if(g==e)break e;if(y&&r[y-1].to==g)g=r[--y].from;else{if(ue[g-1]==a)break e;break}}if(f)f.push(m);else{m.to<l&&o.push(new Ct(m.to,l,d));let g=m.direction==bi!=!(d%2);Do(n,g?i+1:i,s,m.inner,m.from,m.to,o),l=m.from}p=m.from}else{if(p==e||(h?ue[p-1]!=a:ue[p-1]==a))break;p--}f?Fo(n,p,l,i+1,s,f,o):p<l&&o.push(new Ct(p,l,d)),l=p}}function Do(n,e,t,i,s,r,o){let a=e%2?2:1;Fp(n,s,r,i,a),Dp(n,s,r,i,a),Lp(s,r,i,a),Fo(n,s,r,e,t,i,o)}function Xp(n,e,t){if(!n)return[new Ct(0,0,e==xa?1:0)];if(e==bi&&!t.length&&!Up.test(n))return _h(n.length);if(t.length)for(;n.length>ue.length;)ue[ue.length]=256;let i=[],s=e==bi?0:1;return Do(n,s,s,t,0,n.length,i),i}function _h(n){return[new Ct(0,n,0)]}let Jh="";function Bp(n,e,t,i,s){var r;let o=i.head-n.from,a=Ct.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),l=e[a],c=l.side(s,t);if(o==c){let f=a+=s?1:-1;if(f<0||f>=e.length)return null;l=e[a=f],o=l.side(!s,t),c=l.side(s,t)}let h=Ze(n.text,o,l.forward(s,t));(h<l.from||h>l.to)&&(h=c),Jh=n.text.slice(Math.min(o,h),Math.max(o,h));let u=a==(s?e.length-1:0)?null:e[a+(s?1:-1)];return u&&h==c&&u.level+(s?0:1)<l.level?A.cursor(u.side(!s,t)+n.from,u.forward(s,t)?1:-1,u.level):A.cursor(h+n.from,l.forward(s,t)?-1:1,l.level)}function Ip(n,e,t){for(let i=e;i<t;i++){let s=Hh(n.charCodeAt(i));if(s==1)return bi;if(s==2||s==4)return xa}return bi}const eu=Z.define(),tu=Z.define(),iu=Z.define(),nu=Z.define(),Lo=Z.define(),su=Z.define(),ru=Z.define(),va=Z.define(),wa=Z.define(),ou=Z.define({combine:n=>n.some(e=>e)}),au=Z.define({combine:n=>n.some(e=>e)}),lu=Z.define();class Ui{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new Ui(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Ui(A.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Hn=Y.define({map:(n,e)=>n.map(e)}),cu=Y.define();function ze(n,e,t){let i=n.facet(nu);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const Lt=Z.define({combine:n=>n.length?n[0]:!0});let Wp=0;const Ti=Z.define({combine(n){return n.filter((e,t)=>{for(let i=0;i<t;i++)if(n[i].plugin==e.plugin)return!1;return!0})}});class xe{constructor(e,t,i,s,r){this.id=e,this.create=t,this.domEventHandlers=i,this.domEventObservers=s,this.baseExtensions=r(this),this.extension=this.baseExtensions.concat(Ti.of({plugin:this,arg:void 0}))}of(e){return this.baseExtensions.concat(Ti.of({plugin:this,arg:e}))}static define(e,t){const{eventHandlers:i,eventObservers:s,provide:r,decorations:o}=t||{};return new xe(Wp++,e,i,s,a=>{let l=[];return o&&l.push(dr.of(c=>{let h=c.plugin(a);return h?o(h):I.none})),r&&l.push(r(a)),l})}static fromClass(e,t){return xe.define((i,s)=>new e(i,s),t)}}class Er{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ze(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ze(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ze(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const hu=Z.define(),ka=Z.define(),dr=Z.define(),uu=Z.define(),Qa=Z.define(),Ln=Z.define(),fu=Z.define();function Rl(n,e){let t=n.state.facet(fu);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return H.spans(i,e.from,e.to,{point(){},span(r,o,a,l){let c=r-e.from,h=o-e.from,u=s;for(let f=a.length-1;f>=0;f--,l--){let d=a[f].spec.bidiIsolate,p;if(d==null&&(d=Ip(e.text,c,h)),l>0&&u.length&&(p=u[u.length-1]).to==c&&p.direction==d)p.to=h,u=p.inner;else{let m={from:c,to:h,direction:d,inner:[]};u.push(m),u=m.inner}}}}),s}const du=Z.define();function Pa(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(du)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}const hn=Z.define();class ct{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new ct(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toA<i.fromA)break;i=i.join(s),e.splice(t-1,1)}}return e.splice(t,0,i),e}static extendWithRanges(e,t){if(t.length==0)return e;let i=[];for(let s=0,r=0,o=0;;){let a=s<e.length?e[s].fromB:1e9,l=r<t.length?t[r]:1e9,c=Math.min(a,l);if(c==1e9)break;let h=c+o,u=c,f=h;for(;;)if(r<t.length&&t[r]<=u){let d=t[r+1];r+=2,u=Math.max(u,d);for(let p=s;p<e.length&&e[p].fromB<=u;p++)o=e[p].toA-e[p].toB;f=Math.max(f,d+o)}else if(s<e.length&&e[s].fromB<=u){let d=e[s++];u=Math.max(u,d.toB),f=Math.max(f,d.toA),o=d.toA-d.toB}else break;i.push(new ct(h,f,c,u))}return i}}class Ms{constructor(e,t,i){this.view=e,this.state=t,this.transactions=i,this.flags=0,this.startState=e.state,this.changes=Re.empty(this.startState.doc.length);for(let r of i)this.changes=this.changes.compose(r.changes);let s=[];this.changes.iterChangedRanges((r,o,a,l)=>s.push(new ct(r,o,a,l))),this.changedRanges=s}static create(e,t,i){return new Ms(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const qp=[];class Se{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return qp}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Qp(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=ni(this.dom),s=this.length?e>0:t>0;return new pt(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof mr)return e;return null}static get(e){return e.cmTile}}class pr extends Se{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=a.dom&&(r.written=!0),a.dom.parentNode==t)for(;s&&s!=a.dom;)s=$l(s);else t.insertBefore(a.dom,s);i=a.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=$l(s);this.length=o}}function $l(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class mr extends pr{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Se.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof Xt)t.push(s),i=o,s=0;else{let a=r+o.length,l=e(o,r);if(l!==void 0)return l;r=a+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&t>=-1&&t<=1){if(a.flags&32)return!0;a.flags&16&&(i=void 0)}(l<e||e==c&&(t<-1?a.length:a.covers(1)))&&(!i||!a.isWidget()&&i.isWidget())&&(i=a,s=e-l),(c>e||e==l&&(t>1?a.length:a.covers(-1)))&&(!r||!a.isWidget()&&r.isWidget())&&(r=a,o=e-l)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}}class Xt extends pr{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new Xt(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class Ii extends pr{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new Ii(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,a=-1;function l(h,u){for(let f=0,d=0;f<h.children.length&&d<=u;f++){let p=h.children[f],m=d+p.length;m>=u&&(p.isComposite()?l(p,u-d):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Vp(o,p)))&&(m>u||p.flags&32&&t<=1)?(o=p,a=u-d):(d<u||p.flags&16&&!p.isHidden&&t>=-1)&&(s=p,r=u-d)),d=m}}l(this,e);let c=(t<0?s:o)||s||o;return c?{tile:c,offset:c==s?r:a}:null}coordsIn(e,t,i){let s=this.resolveInline(e,t,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),t,i):zp(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:s,offset:r}=i;if(this.dom.contains(s.dom))return s.isText()?new pt(s.dom,Math.min(s.dom.nodeValue.length,r)):s.domPosFor(r,s.flags&16?1:s.flags&32?-1:t);let o=i.tile.parent,a=!1;for(let l of o.children){if(a)return new pt(l.dom,0);l==i.tile&&(a=!0)}}return new pt(this.dom,0)}}function zp(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=bs(e);return t[t.length-1]||null}function Vp(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.top<t.bottom}class Ge extends pr{constructor(e,t){super(e),this.mark=t}get domAttrs(){return this.mark.attrs}static of(e,t){let i=new Ge(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class pi extends Se{constructor(e,t){super(e,t.length),this.text=t}sync(e){this.flags&2||(super.sync(e),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text))}isText(){return!0}toString(){return JSON.stringify(this.text)}coordsIn(e,t,i){let s=this.dom.nodeValue.length;e>s&&(e=s);let r=e,o=e,a=0;e==0&&t<0||e==s&&t>=0?$.chrome||$.gecko||(e?(r--,a=1):o<s&&(o++,a=-1)):t<0?r--:o<s&&o++;let l=Qn(this.dom,r,o).getClientRects();if(!l.length)return null;let c=l[(a?a<0:t>=0)?0:l.length-1];return $.safari&&!a&&c.width==0&&(c=Array.prototype.find.call(l,h=>h.width)||c),i==null?c:Zs(c,(a?a>0:t<0)==i)}static of(e,t){let i=new pi(t||document.createTextNode(e),e);return t||(i.flags|=2),i}}class Si extends Se{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return Zs(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?r.length-1:0;o=r[l],!(e>0?l==0:l==r.length-1||o.top<o.bottom);l+=a?-1:1);return Zs(o,!a)}}get overrideDOMText(){if(!this.length)return se.empty;let{root:e}=this;if(!e)return se.empty;let t=this.posAtStart;return e.view.state.doc.slice(t,t+this.length)}destroy(){super.destroy(),this.widget.destroy(this.dom)}static of(e,t,i,s,r){return r||(r=e.toDOM(t),e.editable||(r.contentEditable="false")),new Si(r,i,e,s)}}class Es extends Se{constructor(e){let t=document.createElement("img");t.className="cm-widgetBuffer",t.setAttribute("aria-hidden","true"),super(t,0,e)}get isHidden(){return!0}get overrideDOMText(){return se.empty}coordsIn(e,t,i){let s=this.dom.getBoundingClientRect();return i==null?s:Zs(s,t>0==i)}}class jp{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:s,index:r,beforeBreak:o,parents:a}=this;for(;e||t>0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!a.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=a.pop(),r++}else{let l=s.children[r],c=l.breakAfter;(t>0?l.length<=e:l.length<e)&&(!i||i.skip(l,0,l.length)!==!1||!l.isComposite)?(o=!!c,r++,e-=l.length):(a.push({tile:s,index:r}),s=l,r=0,i&&l.isComposite()&&i.enter(l))}else{let l=s.length;if(r<l&&e){let c=Math.min(e,l-r);i&&i.skip(s,r,r+c),e-=c,r+=c}if(r==l)o=!!s.breakAfter,{tile:s,index:r}=a.pop(),r++;else if(!e)break}return this.tile=s,this.index=r,this.beforeBreak=o,this}get root(){return this.parents.length?this.parents[0].tile:this.tile}}class Yp{constructor(e,t,i,s){this.from=e,this.to=t,this.wrapper=i,this.rank=s}}class Np{constructor(e,t,i){this.cache=e,this.root=t,this.blockWrappers=i,this.curLine=null,this.lastBlock=null,this.afterWidget=null,this.pos=0,this.wrappers=[],this.wrapperPos=0}addText(e,t,i,s){var r;this.flushBuffer();let o=this.ensureMarks(t,i),a=o.lastChild;if(a&&a.isText()&&!(a.flags&8)&&a.length+e.length<512){this.cache.reused.set(a,2);let l=o.children[o.children.length-1]=new pi(a.dom,a.text+e);l.parent=o}else o.append(s||pi.of(e,(r=this.cache.find(pi))===null||r===void 0?void 0:r.dom));this.pos+=e.length,this.afterWidget=null}addComposition(e,t){let i=this.curLine;i.dom!=t.line.dom&&(i.setDOM(this.cache.reused.has(t.line)?Ur(t.line.dom):t.line.dom),this.cache.reused.set(t.line,2));let s=i;for(let a=t.marks.length-1;a>=0;a--){let l=t.marks[a],c=s.lastChild;if(c instanceof Ge&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(Ur(l.dom)),s=c;else{if(this.cache.reused.get(l)){let u=Se.get(l.dom);u&&u.setDOM(Ur(l.dom))}let h=Ge.of(l.mark,l.dom);s.append(h),s=h}this.cache.reused.set(l,2)}let r=Se.get(e.text);r&&this.cache.reused.set(r,2);let o=new pi(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=pu);let s=Ii.start(e,t||((i=this.cache.find(Ii))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],a;if(t>0&&(a=s.lastChild)&&a instanceof Ge&&a.mark.eq(o))s=a,t--;else{let l=Ge.of(o,(i=this.cache.find(Ge,c=>c.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(l),s=l,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Kl(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!($.ios&&Kl(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Fr,0,32)||new Si(Fr.toDOM(),0,Fr,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to<this.pos&&this.wrappers.splice(e,1);for(let e=this.blockWrappers;e.value&&e.from<=this.pos;e.next())if(e.to>=this.pos){let t=e.rank*102+e.value.rank,i=new Yp(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.from<this.pos&&s instanceof Xt&&s.wrapper.eq(i.wrapper))t=s;else{let r=Xt.of(i.wrapper,(e=this.cache.find(Xt,o=>o.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(Es,void 0,1);return i&&(i.flags=t),i||new Es(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class Hp{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let a=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,a)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}}const Us=[Si,Ii,pi,Ge,Es,Xt,mr];for(let n=0;n<Us.length;n++)Us[n].bucket=n;class Gp{constructor(e){this.view=e,this.buckets=Us.map(()=>[]),this.index=Us.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let a=0;a<r.length;a++){let l=(a+o)%r.length,c=r[l];if((!t||t(c))&&!this.reused.has(c))return r.splice(l,1),l<o&&this.index[s]--,this.reused.set(c,i),c}return null}findWidget(e,t,i){let s=this.buckets[0];if(s.length)for(let r=0,o=0;;r++){if(r==s.length){if(o)return null;o=1,r=0}let a=s[r];if(!this.reused.has(a)&&(o==0?a.widget.compare(e):a.widget.constructor==e.constructor&&e.updateDOM(a.dom,this.view,a.widget)))return s.splice(r,1),r<this.index[0]&&this.index[0]--,a.widget==e&&a.length==t&&(a.flags&497)==i?(this.reused.set(a,1),a):(this.reused.set(a,2),new Si(a.dom,t,e,a.flags&-498|i))}}reuse(e){return this.reused.set(e,1),e}maybeReuse(e,t=2){if(!this.reused.has(e))return this.reused.set(e,t),e.dom}clear(){for(let e=0;e<this.buckets.length;e++)this.buckets[e].length=this.index[e]=0}}class _p{constructor(e,t,i,s,r){this.view=e,this.decorations=s,this.disallowBlockEffectsFor=r,this.openWidget=!1,this.openMarks=0,this.cache=new Gp(e),this.text=new Hp(e.state.doc),this.builder=new Np(this.cache,new mr(e,e.contentDOM),H.iter(i)),this.cache.reused.set(t,2),this.old=new jp(t),this.reuseWalker={skip:(o,a,l)=>{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let a=o<e.length?e[o++]:null,l=a?a.fromA:this.old.root.length;if(l>s){let c=l-s;this.preserve(c,!o,!a),s=l,r+=c}if(!a)break;t&&a.fromA<=t.range.fromA&&a.toA>=t.range.toA?(this.forward(a.fromA,t.range.fromA,t.range.fromA<t.range.toA?1:-1),this.emit(r,t.range.fromB),this.builder.flushBuffer(),this.cache.clear(),this.builder.addComposition(t,i),this.text.skip(t.range.toB-t.range.fromB),this.forward(t.range.fromA,a.toA),this.emit(t.range.toB,a.toB)):(this.forward(a.fromA,a.toA),this.emit(r,a.toB)),r=a.toB,s=a.toA}return this.builder.curLine&&this.builder.endLine(),this.builder.root}preserve(e,t,i){let s=tm(this.old),r=this.openMarks;this.old.advance(e,i?1:-1,{skip:(o,a,l)=>{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a<o.length?Si.of(o.widget,this.view,l-a,o.flags&496,this.cache.maybeReuse(o)):this.cache.reuse(o);c.flags&256?(c.flags&=-2,this.builder.addBlockWidget(c)):(this.builder.ensureLine(null),this.builder.addInlineWidget(c,s,r),r=s.length)}else if(o.isText())this.builder.ensureLine(null),!a&&l==o.length&&!this.cache.reused.has(o)?this.builder.addText(o.text,s,r,this.cache.reuse(o)):(this.cache.add(o),this.builder.addText(o.text.slice(a,l),s,r)),r=s.length;else if(o.isLine())o.flags&=-2,this.cache.reused.set(o,1),this.builder.addLine(o);else if(o instanceof Es)this.cache.add(o);else if(o instanceof Ge)this.builder.ensureLine(null),this.builder.addMark(o,s,r),this.cache.reused.set(o,1),r=s.length;else return!1;this.openWidget=!1},enter:o=>{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Ge&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof Ge&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=-1,o=H.spans(this.decorations,e,t,{point:(a,l,c,h,u,f)=>{if(c instanceof Ai){if(this.disallowBlockEffectsFor[f]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=h.length,u>h.length)s.continueWidget(l-a);else{let d=c.widget||(c.block?Wi.block:Wi.inline),p=Jp(c),m=this.cache.findWidget(d,l-a,p)||Si.of(d,this.view,l-a,p);c.block?(c.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,h,u))}i=null}else i=em(i,c);l>a&&this.text.skip(l-a)},span:(a,l,c,h)=>{for(let u=a;u<l;){let f=this.text.next(Math.min(512,l-u));f==null?(s.addLineStartIfNotCovered(i),s.addBreak(),u++):(s.ensureLine(i),s.addText(f,c,u==a?h:c.length),u+=f.length),i=null}r=c.length}});r>-1&&(this.openWidget=o>r),this.openWidget||s.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=Se.get(s);if(s==this.view.contentDOM)break;r instanceof Ge?t.push(r):r?.isLine()?i=r:r instanceof Xt||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new Ii(s,pu):i||t.push(Ge.of(new Fn({tagName:s.nodeName.toLowerCase(),attributes:Pp(s)}),s)))}return{line:i,marks:t}}}function Kl(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Jp(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}const pu={class:"cm-line"};function em(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&ba(t,n),i&&(n.class+=" "+i)),n}function tm(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof Ge&&e.push(i.mark)}return e}function Ur(n){let e=Se.get(n);return e&&e.setDOM(n.cloneNode()),n}class Wi extends Ut{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}Wi.inline=new Wi("span");Wi.block=new Wi("div");const Fr=new class extends Ut{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class Zl{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=I.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new mr(e,e.contentDOM),this.updateInner([new ct(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:h,toA:u})=>u<this.minWidthFrom||h>this.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!hm(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?nm(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:h,to:u}=this.hasComposition;i=new ct(h,u,e.changes.mapPos(h,-1),e.changes.mapPos(u,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,($.ie||$.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=om(o,this.decorations,e.changes);l.length&&(i=ct.extendWithRanges(i,l));let c=lm(a,this.blockWrappers,e.changes);return c.length&&(i=ct.extendWithRanges(i,c)),r&&!i.some(h=>h.fromA<=r.range.fromA&&h.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,a=new _p(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Se.get(t.text)&&a.cache.reused.set(Se.get(t.text),2),this.tile=a.run(e,t),Xo(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=$.chrome||$.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let r of this.tile.children)r.isWidget()&&r.widget instanceof Dr&&s.push(r.dom);i.updateGaps(s)}updateEditContextFormatting(e){this.editContextFormatting=this.editContextFormatting.map(e.changes);for(let t of e.transactions)for(let i of t.effects)i.is(cu)&&(this.editContextFormatting=i.value)}updateSelection(e=!1,t=!1){(e||!this.view.observer.selectionRange.focusNode)&&this.view.observer.readSelectionRange();let{dom:i}=this.tile,s=this.view.root.activeElement,r=s==i,o=!r&&!(this.view.state.facet(Lt)||i.tabIndex>-1)&&gn(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,h;if(l.empty?h=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(h=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),$.gecko&&l.empty&&!this.hasComposition&&im(c)){let f=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(f,c.node.childNodes[c.offset]||null)),c=h=new pt(f,0),a=!0}let u=this.view.observer.selectionRange;(a||!u.focusNode||(!On(c.node,c.offset,u.anchorNode,u.anchorOffset)||!On(h.node,h.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,l))&&(this.view.observer.ignore(()=>{$.android&&$.chrome&&i.contains(u.focusNode)&&cm(u.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let f=kn(this.view.root);if(f)if(l.empty){if($.gecko){let d=sm(c.node,c.offset);if(d&&d!=3){let p=(d==1?jh:Yh)(c.node,c.offset);p&&(c=new pt(p.node,p.offset))}}f.collapse(c.node,c.offset),l.bidiLevel!=null&&f.caretBidiLevel!==void 0&&(f.caretBidiLevel=l.bidiLevel)}else if(f.extend){f.collapse(c.node,c.offset);try{f.extend(h.node,h.offset)}catch{}}else{let d=document.createRange();l.anchor>l.head&&([c,h]=[h,c]),d.setEnd(h.node,h.offset),d.setStart(c.node,c.offset),f.removeAllRanges(),f.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(c,h)),this.impreciseAnchor=c.precise?null:new pt(u.anchorNode,u.anchorOffset),this.impreciseHead=h.precise?null:new pt(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&On(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=kn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!l||!c||l.bottom>c.top)return;let h=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(h.node,h.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=Wt(e)==0?0:t==0?-1:1;for(;;){let a=e.parentNode;if(a==i.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!Se.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,a=s;;o++){let l=i.children[o];if(l.dom==r)return a;a+=l.length+l.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(s,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,h)=>{if(c.isWidget()){if(c.flags&32&&h>=e)return!0;c.flags&16&&(r=!0)}else{let u=h+c.length;if(h<=e&&(i=c,s=e-h,r=u<e),u>=e&&!o&&(o=c,a=e-h,l=h>e),h>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:l&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(a,t))}coordsAt(e,t,i){let{tile:s,offset:r}=this.tile.resolveBlock(e,t);return s.isWidget()?s.widget instanceof Dr?null:s.coordsInWidget(r,t,!0):s.coordsIn(r,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let a of r.children){if(a.length>=o){let l=s(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(r.isText()&&o<r.length){let a=Ze(r.text,o);if(a==o)return null;let l=Qn(r.dom,o,a).getClientRects();for(let c=0;c<l.length;c++){let h=l[c];if(c==l.length-1||h.top<h.bottom&&h.left<h.right)return h}}return null}return s(t,i)}measureVisibleLineHeights(e){let t=[],{from:i,to:s}=e,r=this.view.contentDOM.clientWidth,o=r>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==fe.LTR,c=0,h=(u,f,d)=>{for(let p=0;p<u.children.length&&!(f>s);p++){let m=u.children[p],g=f+m.length,y=m.dom.getBoundingClientRect(),{height:x}=y;if(d&&!p&&(c+=y.top-d.top),m instanceof Xt)g>i&&h(m,f,y);else if(f>=i&&(c>0&&t.push(-c),t.push(x+c),c=0,o)){let b=m.dom.lastChild,C=b?bs(b):[];if(C.length){let Q=C[C.length-1],P=l?Q.right-y.left:y.right-Q.left;P>a&&(a=P,this.minWidth=r,this.minWidthFrom=f,this.minWidthTo=g)}}d&&p==u.children.length-1&&(c+=d.bottom-y.bottom),f=g+m.breakAfter}};return h(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?fe.RTL:fe.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let h=bs(c.dom);if(h.length!=1)return;a+=h[0].width,l=h[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=bs(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(I.replace({widget:new Dr(a),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return I.set(e)}updateDeco(){let e=1,t=this.view.state.facet(dr).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(Qa).map((r,o)=>{let a=typeof r=="function";return a&&(i=!0),a?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(H.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];e<this.decorations.length;)this.dynamicDecorationMap[e++]=!1;this.blockWrappers=this.view.state.facet(uu).map(r=>typeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(lu))try{if(c(this.view,e.range,e))return!0}catch(h){ze(this.view.state,h,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=Pa(this.view),o={left:i.left-r.left,top:i.top-r.top,right:i.right+r.right,bottom:i.bottom+r.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;if(Rp(this.view.scrollDOM,o,t.head<t.anchor?-1:1,e.x,e.y,Math.max(Math.min(e.xMargin,a),-a),Math.max(Math.min(e.yMargin,l),-l),this.view.textDirection==fe.LTR),window.visualViewport&&window.innerHeight-window.visualViewport.height>1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottom<window.visualViewport.offsetTop)){let c=this.view.docView.lineAt(t.head,1);if(c){let h=Wh(c.dom);c.dom.scrollIntoView({block:"nearest"}),qh(h,!1)}}}lineHasWidget(e){let t=i=>i.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){Xo(this.tile)}}function Xo(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)Xo(i,e)}}function im(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function mu(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=jh(t.focusNode,t.focusOffset),s=Yh(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let a=Se.get(s.node);if(!a||a.isText()&&a.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let l=Se.get(i.node);!l||l.isText()&&l.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function nm(n,e,t){let i=mu(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,a=s.nodeValue;if(/[\n\r]/.test(a)||n.state.doc.sliceString(i.from,i.to)!=a)return null;let l=e.invertedDesc;return{range:new ct(l.mapPos(r),l.mapPos(o),r,o),text:s}}function sm(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e<n.childNodes.length&&n.childNodes[e].contentEditable=="false"?2:0)}let rm=class{constructor(){this.changes=[]}compareRange(e,t){Mi(e,t,this.changes)}comparePoint(e,t){Mi(e,t,this.changes)}boundChange(e){Mi(e,e,this.changes)}};function om(n,e,t){let i=new rm;return H.compare(n,e,t,i),i.changes}class am{constructor(){this.changes=[]}compareRange(e,t){Mi(e,t,this.changes)}comparePoint(){}boundChange(e){Mi(e,e,this.changes)}}function lm(n,e,t){let i=new am;return H.compare(n,e,t,i),i.changes}function cm(n,e){for(let t=n;t&&t!=e;t=t.assignedSlot||t.parentNode)if(t.nodeType==1&&t.contentEditable=="false")return!0;return!1}function hm(n,e){let t=!1;return e&&n.iterChangedRanges((i,s)=>{i<e.to&&s>e.from&&(t=!0)}),t}class Dr extends Ut{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function um(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return A.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,a=r;t<0?o=Ze(s.text,r,!1):a=Ze(s.text,r);let l=i(s.text.slice(o,a));for(;o>0;){let c=Ze(s.text,o,!1);if(i(s.text.slice(c,o))!=l)break;o=c}for(;a<s.length;){let c=Ze(s.text,a);if(i(s.text.slice(a,c))!=l)break;a=c}return A.undirectionalRange(o+s.from,a+s.from)}function fm(n,e,t,i,s){let r=Math.round((i-e.left)*n.defaultCharacterWidth);if(n.lineWrapping&&t.height>n.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((s-t.top-(n.defaultLineHeight-a)*.5)/a);r+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Co(o,r,n.state.tabSize)}function Bo(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.to<e)){if(r.from<e&&r.to>e)return r;(!s||r.type==Le.Text&&(s.type!=r.type||(t<0?r.from<e:r.to>e)))&&(s=r)}}return s||i}return i}function dm(n,e,t,i){let s=Bo(n,e.head,e.assoc||-1),r=!i||s.type!=Le.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(s.from),l=n.posAtCoords({x:t==(a==fe.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(l!=null)return A.cursor(l,t?-1:1)}return A.cursor(t?s.to:s.from,t?-1:1)}function Ml(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let a=e,l=null;;){let c=Bp(s,r,o,a,t),h=Jh;if(!c){if(s.number==(t?n.state.doc.lines:1))return a;h=` +`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),c=n.visualLineSide(s,!t)}if(l){if(!l(h))return a}else{if(!i)return c;l=i(h)}a=c}}function pm(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==ye.Space&&(s=o),s==o}}function mm(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return A.cursor(s,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),c=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),h=n.documentTop;if(c)o==null&&(o=c.left-l.left),a=r<0?c.top:c.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(s-p.from))),a=(r<0?p.top:p.bottom)+h}let u=l.left+o,f=n.viewState.heightOracle.textHeight>>1,d=i??f;for(let p=0;;p+=f){let m=a+(d+p)*r,g=Io(n,{x:u,y:m},!1,r);if(t?m>l.bottom:m<l.top)return A.cursor(g.pos,g.assoc);let y=n.coordsAtPos(g.pos,g.assoc),x=y?(y.top+y.bottom)/2:0;if(!y||(t?x>a:x<a))return A.cursor(g.pos,g.assoc,void 0,o)}}function yn(n,e,t){for(;;){let i=0;for(let s of n)s.between(e-1,e+1,(r,o,a)=>{if(e>r&&e<o){let l=i||t||(e-r<o-e?-1:1);e=l<0?r:o,i=l}});if(!i)return e}}function gu(n,e){let t=null;for(let i=0;i<e.ranges.length;i++){let s=e.ranges[i],r=null;if(s.empty){let o=yn(n,s.from,0);o!=s.from&&(r=A.cursor(o,-1))}else{let o=yn(n,s.from,-1),a=yn(n,s.to,1);(o!=s.from||a!=s.to)&&(s.undirectional?r=A.undirectionalRange(s.from,s.to):r=A.range(s.from==s.anchor?o:a,s.from==s.head?o:a))}r&&(t||(t=e.ranges.slice()),t[i]=r)}return t?A.create(t,e.mainIndex):e}function Lr(n,e,t){let i=yn(n.state.facet(Ln).map(s=>s(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:A.cursor(i,i<t.from?1:-1)}class Pt{constructor(e,t){this.pos=e,this.assoc=t}}function Io(n,e,t,i){let s=n.contentDOM.getBoundingClientRect(),r=s.top+n.viewState.paddingTop,{x:o,y:a}=e,l=a-r,c;for(;;){if(l<0)return new Pt(0,1);if(l>n.viewState.docHeight)return new Pt(n.state.doc.length,-1);if(c=n.elementAtHeight(l),i==null)break;if(c.type==Le.Text){if(i<0?c.to<n.viewport.from:c.from>n.viewport.to)break;let f=n.docView.coordsAt(i<0?c.from:c.to,i>0?-1:1);if(f&&(i<0?f.top<=l+r:f.bottom>=l+r))break}let u=n.viewState.heightOracle.textHeight/2;l=i>0?c.bottom+u:c.top-u}if(n.viewport.from>=c.to||n.viewport.to<=c.from){if(t)return null;if(c.type==Le.Text){let u=fm(n,s,c,o,a);return new Pt(u,u==c.from?1:-1)}}if(c.type!=Le.Text)return l<(c.top+c.bottom)/2?new Pt(c.from,1):new Pt(c.to,-1);let h=n.docView.lineAt(c.from,2);return(!h||h.length!=c.length)&&(h=n.docView.lineAt(c.from,-2)),new gm(n,o,a,n.textDirectionAt(c.from)).scanTile(h,c.from)}class gm{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to<e)&&(this.line=this.view.state.doc.lineAt(e),this.spans=this.view.bidiSpans(this.line)),this}baseDirAt(e,t){let{line:i,spans:s}=this.bidiSpansAt(e);return s[Ct.find(s,e-i.from,-1,t)].level==this.baseDir}dirAt(e,t){let{line:i,spans:s}=this.bidiSpansAt(e);return s[Ct.find(s,e-i.from,-1,t)].dir}bidiIn(e,t){let{spans:i,line:s}=this.bidiSpansAt(e);return i.length>1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from<t)}scan(e,t,i=!1){let s=0,r=e.length-1,o=new Set,a=this.bidiIn(e[0],e[r]),l,c,h=-1,u=1e9,f;e:for(;s<r;){let p=r-s,m=s+r>>1;t:if(o.has(m)){for(let x=1;x<p;x++){let b=m+x;if(b>=r&&(b-=p),!o.has(b)){m=b;break t}}break e}o.add(m);let g=t(m),y=0;if(g)for(let x=0;x<g.length;x++){let b=g[x];if(!(b.width==0&&g.length>1))if(b.bottom<this.y)(!l||l.bottom<b.bottom)&&(l=b),y=1;else if(b.top>this.y)(!c||c.top>b.top)&&(c=b),y=-1;else{let C=b.left>this.x?this.x-b.left:b.right<this.x?this.x-b.right:0,Q=Math.abs(C);Q<u&&(h=m,u=Q,f=b),C&&(y=C<0==(this.baseDir==fe.LTR)?-1:1)}}y==-1&&(!a||this.baseDirAt(e[m],1))?r=m:y==1&&(!a||this.baseDirAt(e[m+1],-1))&&(s=m+1)}if(!f){if(!c&&!l)return{i:e[0],after:!1};let p=l&&(!c||this.y-l.bottom<c.top-this.y)?l:c;return this.y=(p.top+p.bottom)/2,this.scan(e,t,!0)}if(u&&!i){let{top:p,bottom:m}=f;if(l&&l.bottom>(p+p+m)/3)return this.y=l.bottom-1,this.scan(e,t,!0);if(c&&c.top<(p+m+m)/3)return this.y=c.top+1,this.scan(e,t,!0)}let d=(a?this.dirAt(e[h],1):this.baseDir)==fe.LTR;return{i:h,after:this.x>(f.left+f.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r<e.length;r=Ze(e.text,r))i.push(t+r);i.push(t+e.length);let s=this.scan(i,r=>{let o=i[r]-t,a=i[r+1]-t;return Qn(e.dom,o,a).getClientRects()});return s.after?new Pt(i[s.i+1],-1):new Pt(i[s.i],1)}scanTile(e,t){if(!e.length)return new Pt(t,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,t);if(a.isComposite())return this.scanTile(a,t)}let i=[t];for(let a=0,l=t;a<e.children.length;a++)i.push(l+=e.children[a].length);let s=this.scan(i,a=>{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:Qn(l.dom,0,l.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Pt(i[s.i+1],-1):new Pt(o,1)}}const ki="￿";class Om{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(J.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=ki}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=Se.get(s),a=s.nextSibling;if(a==t){o?.breakAfter&&!a&&i!=this.view.contentDOM&&this.lineBreak();break}let l=Se.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:Ks(s))||Ks(a)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!Am(a,t)&&this.lineBreak(),s=a}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,a;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(a=s.exec(t))&&(r=a.index,o=a[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);i=r+o}}readNode(e){let t=Se.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(ym(e,i.node,i.offset)?t:0))}}function ym(n,e,t){for(;;){if(!e||t<Wt(e))return!1;if(e==n)return!0;t=ni(e)+1,e=e.parentNode}}function Am(n,e){let t;for(;!(n==e||!n);n=n.nextSibling){let i=Se.get(n);if(!i?.isWidget())return!1;i&&(t||(t=[])).push(i)}if(t)for(let i of t){let s=i.overrideDOMText;if(s?.length)return!1}return!0}class El{constructor(e,t){this.node=e,this.offset=t,this.pos=-1}}class bm{constructor(e,t,i,s){this.typeOver=s,this.bounds=null,this.text="",this.domChanged=t>-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Ou(e.docView.tile,t,i,0))){let l=r||o?[]:xm(e),c=new Om(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=vm(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!Eo(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),h=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Eo(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),u=e.viewport;if(($.ios||$.chrome)&&c!=h&&Math.min(c,h)<=a.main.from&&Math.max(c,h)>=a.main.to&&(u.from>0||u.to<e.state.doc.length)){let f=Math.min(c,h),d=Math.max(c,h),p=u.from-f,m=u.to-d;(p==0||p==1||f==0)&&(m==0||m==-1||d==e.state.doc.length)&&(c=0,h=e.state.doc.length)}if(e.inputState.composing>-1&&a.ranges.length>1)this.newSel=a.replaceRange(A.range(h,c));else if(e.lineWrapping&&h==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let f=e.coordsAtPos(c,-1),d=0;f&&(d=e.inputState.lastTouchY<=f.bottom?-1:1),this.newSel=A.create([A.cursor(c,d)])}else this.newSel=A.single(h,c)}}}function Ou(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,a=-1;for(let l=0,c=i,h=i;l<n.children.length;l++){let u=n.children[l],f=c+u.length;if(c<e&&f>t)return Ou(u,e,t,c);if(f>=e&&s==-1&&(s=l,r=c),c>t&&u.dom.parentNode==n.dom){o=l,a=h;break}h=f,c=f+u.breakAfter}return{from:r,to:a<0?i+n.length:a,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o<n.children.length&&o>=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function yu(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=r.from,h=null;(o===8||$.android&&e.text.length<l-a)&&(c=r.to,h="end");let u=s.doc.sliceString(a,l,ki),f,d;!r.empty&&r.from>=a&&r.to<=l&&(e.typeOver||u!=e.text)&&u.slice(0,r.from-a)==e.text.slice(0,r.from-a)&&u.slice(r.to-a)==e.text.slice(f=e.text.length-(u.length-(r.to-a)))?t={from:r.from,to:r.to,insert:se.of(e.text.slice(r.from-a,f).split(ki))}:(d=Au(u,e.text,c-a,h))&&($.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==ki+ki&&d.toB--,t={from:a+d.from,to:a+d.toA,insert:se.of(e.text.slice(d.from,d.toB).split(ki))})}else i&&(!n.hasFocus&&s.facet(Lt)||Fs(i,r))&&(i=null);if(!t&&!i)return!1;if(($.mac||$.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:se.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).to<r.to&&n.docView.lineHasWidget(r.to)&&n.inputState.insertingTextAt>Date.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:$.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:se.of([" "])}),t)return Ca(n,t,i,o);if(i&&!Fs(i,r)){let a=!1,l="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(a=!0),l=n.inputState.lastSelectionOrigin,l=="select.pointer"&&(i=gu(s.facet(Ln).map(c=>c(n)),i))),n.dispatch({selection:i,scrollIntoView:a,userEvent:l}),!0}else return!1}function Ca(n,e,t,i=-1){if($.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if($.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Ei(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.length<e.to-e.from&&e.to>s.head)&&Ei(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&Ei(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,a=()=>o||(o=Sm(n,e,t));return n.state.facet(su).some(l=>l(n,e.from,e.to,r,a))||n.dispatch(a()),!0}function Sm(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.from<r.from||e.from>r.to){let l=e.from<r.from?-1:1,c=l<0?r.from:r.to,h=yn(s.facet(Ln).map(u=>u(n)),c,l);e.from==h&&(o=h)}if(o>-1)i={changes:e,selection:A.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let l=r.from<e.from?s.sliceDoc(r.from,e.from):"",c=r.to>e.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(l+e.insert.sliceString(0,void 0,n.state.lineBreak)+c))}else{let l=s.changes(e),c=t&&t.main.to<=l.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let h=n.state.sliceDoc(e.from,e.to),u,f=t&&mu(n,t.main.head);if(f){let p=e.insert.length-(e.to-e.from);u={from:f.from,to:f.to-p}}else u=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:l,range:c||p.map(l)};let m=p.to-d,g=m-h.length;if(n.state.sliceDoc(g,m)!=h||m>=u.from&&g<=u.to)return{range:p};let y=s.changes({from:g,to:m,insert:e.insert}),x=p.to-r.to;return{changes:y,range:c?A.range(Math.max(0,c.anchor+x),Math.max(0,c.head+x)):p.map(y)}})}else i={changes:l,selection:c&&s.selection.replaceRange(c)}}let a="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:a,scrollIntoView:!0})}function Au(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r<s&&n.charCodeAt(r)==e.charCodeAt(r);)r++;if(r==s&&n.length==e.length)return null;let o=n.length,a=e.length;for(;o>0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(i=="end"){let l=Math.max(0,r-Math.min(o,a));t-=o+l-r}if(o<r&&n.length<e.length){let l=t<=r&&t>=o?r-t:0;r-=l,a=r+(a-o),o=r}else if(a<r){let l=t<=r&&t>=a?r-t:0;r-=l,o=r+(o-a),a=r}return{from:r,toA:o,toB:a}}function xm(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new El(t,i)),(s!=t||r!=i)&&e.push(new El(s,r))),e}function vm(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?A.single(t+e,i+e):null}function Fs(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}class wm{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,$.safari&&e.contentDOM.addEventListener("input",()=>null),$.gecko&&Xm(e.contentDOM.ownerDocument)}handleEvent(e){!Zm(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Qm(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,a=i[r];a&&o!=!a.handlers.length&&(s.removeEventListener(r,this.handleEvent),a=null),a||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Su.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),$.android&&$.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if($.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(bu.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||Pm.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&$.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&km(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from<e.to&&/^\S+$/.test(e.insert.toString())?!1:(this.pendingIOSKey=void 0,Ei(this.view.contentDOM,t.key,t.keyCode,t.mods))}ignoreDuringComposition(e){return!/^key/.test(e.type)||e.synthetic?!1:this.composing>0?!0:$.safari&&!$.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function km(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Ul(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ze(t.state,s)}}}function Qm(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let a in r){let l=r[a];l&&t(a).handlers.push(Ul(i.value,l))}if(o)for(let a in o){let l=o[a];l&&t(a).observers.push(Ul(i.value,l))}}for(let i in Ot)t(i).handlers.push(Ot[i]);for(let i in je)t(i).observers.push(je[i]);return e}const bu=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Pm="dthko",Su=[16,17,18,20,91,92,224,225],Gn=6;function _n(n){return Math.max(0,n)*.7+8}function Cm(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class Tm{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Ih(e.contentDOM),this.atoms=e.state.facet(Ln).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(J.allowMultipleSelections)&&Rm(e,t),this.dragging=Km(e,t)&&wu(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Cm(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=Pa(this.view);e.clientX-l.left<=s+Gn?t=-_n(s-e.clientX):e.clientX+l.right>=o-Gn&&(t=_n(e.clientX-o)),e.clientY-l.top<=r+Gn?i=-_n(r-e.clientY):e.clientY+l.bottom>=a-Gn&&(i=_n(e.clientY-a)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=gu(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function Rm(n,e){let t=n.state.facet(eu);return t.length?t[0](e):$.mac?e.metaKey:e.ctrlKey}function $m(n,e){let t=n.state.facet(tu);return t.length?t[0](e):$.mac?!e.altKey:!e.ctrlKey}function Km(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=kn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r<s.length;r++){let o=s[r];if(o.left<=e.clientX&&o.right>=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Zm(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=Se.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}const Ot=Object.create(null),je=Object.create(null),xu=$.ie&&$.ie_version<15||$.ios&&$.webkit_version<604;function Mm(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),vu(n,t.value)},50)}function gr(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function vu(n,e){e=gr(n.state,va,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(Wo!=null&&t.selection.ranges.every(l=>l.empty)&&Wo==r.toString()){let l=-1;i=t.changeByRange(c=>{let h=t.doc.lineAt(c.from);if(h.from==l)return{range:c};l=h.from;let u=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:u},range:A.cursor(c.from+u.length)}})}else o?i=t.changeByRange(l=>{let c=r.line(s++);return{changes:{from:l.from,to:l.to,insert:c.text},range:A.cursor(l.from+c.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}je.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,$.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};je.wheel=je.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ot.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);je.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};je.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};je.touchend=(n,e)=>{n.inputState.touchActive=!1};Ot.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(iu))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=Um(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new Tm(n,e,t,i)),i&&n.observer.ignore(()=>{zh(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Fl(n,e,t,i){if(i==1)return A.cursor(e,t);if(i==2)return um(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,a=s?s.posAtEnd:r.to;return a<n.state.doc.length&&a==r.to&&a++,A.undirectionalRange(o,a)}}const Em=$.ie&&$.ie_version<=11;let Dl=null,Ll=0,Xl=0;function wu(n){if(!Em)return n.detail;let e=Dl,t=Xl;return Dl=n,Xl=Date.now(),Ll=!e||t>Date.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Ll+1)%3:1}function Um(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=wu(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,a){let l=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),c,h=Fl(n,l.pos,l.assoc,i);if(t.pos!=l.pos&&!o){let u=Fl(n,t.pos,t.assoc,i),f=Math.min(u.from,h.from),d=Math.max(u.to,h.to);h=f<h.from?A.range(f,d,h.assoc):A.range(d,f,h.assoc)}return o?s.replaceRange(s.main.extend(h.from,h.to,h.assoc)):a&&i==1&&s.ranges.length>1&&(c=Fm(s,l.pos))?c:a?s.addRange(h):A.create([h])}}}function Fm(n,e){for(let t=0;t<n.ranges.length;t++){let{from:i,to:s}=n.ranges[t];if(i<=e&&s>=e)return A.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ot.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=A.undirectionalRange(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",gr(n.state,wa,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ot.dragend=n=>(n.inputState.draggedContent=null,!1);function Bl(n,e,t,i){if(t=gr(n.state,va,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&$m(n,e)?{from:r.from,to:r.to}:null,a={from:s,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ot.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Bl(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o<t.length;o++){let a=new FileReader;a.onerror=r,a.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(i[o]=a.result),r()},a.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Bl(n,e,i,!0),!0}return!1};Ot.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=xu?null:e.clipboardData;return t?(vu(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Mm(n),!1)};function Dm(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Lm(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:gr(n,wa,e.join(n.lineBreak)),ranges:t,linewise:i}}let Wo=null;Ot.copy=Ot.cut=(n,e)=>{if(!gn(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=Lm(n.state);if(!t&&!s)return!1;Wo=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=xu?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(Dm(n,t),!1)};const ku=zt.define();function Qu(n,e){let t=[];for(let i of n.facet(ru)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:ku.of(!0)}):null}function Pu(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=Qu(n.state,e);t?n.dispatch(t):n.update([])}},10)}je.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),Pu(n)};je.blur=n=>{n.observer.clearSelectionRange(),Pu(n)};je.compositionstart=je.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};je.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,$.chrome&&$.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};je.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ot.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let a=o[0],l=n.posAtDOM(a.startContainer,a.startOffset),c=n.posAtDOM(a.endContainer,a.endOffset);return Ca(n,{from:l,to:c,insert:n.state.toText(r)},null),!0}}let s;if($.chrome&&$.android&&(s=bu.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return $.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),$.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>je.compositionend(n,e),20),!1};const Il=new Set;function Xm(n){Il.has(n)||(Il.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const Wl=["pre-wrap","normal","pre-line","break-spaces"];let qi=!1;function ql(){qi=!1}class Bm{constructor(e){this.lineWrapping=e,this.doc=se.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Wl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i<e.length;i++){let s=e[i];s<0?i++:this.heightSamples[Math.floor(s*10)]||(t=!0,this.heightSamples[Math.floor(s*10)]=!0)}return t}refresh(e,t,i,s,r,o){let a=Wl.indexOf(e)>-1,l=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,l){this.heightSamples={};for(let c=0;c<o.length;c++){let h=o[c];h<0?c++:this.heightSamples[Math.floor(h*10)]=!0}}return l}}class Im{constructor(e,t){this.from=e,this.heights=t,this.index=0}get more(){return this.index<this.heights.length}}class dt{constructor(e,t,i,s,r){this.from=e,this.length=t,this.top=i,this.height=s,this._content=r}get type(){return typeof this._content=="number"?Le.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof Ai?this._content.widget:null}get widgetLineBreaks(){return typeof this._content=="number"?this._content:0}join(e){let t=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(e._content)?e._content:[e]);return new dt(this.from,this.length+e.length,this.top,this.height+e.height,t)}}var pe=(function(n){return n[n.ByPos=0]="ByPos",n[n.ByHeight=1]="ByHeight",n[n.ByPosNoHeight=2]="ByPosNoHeight",n})(pe||(pe={}));const Ss=.001;class Ve{constructor(e,t,i=2){this.length=e,this.height=t,this.flags=i}get outdated(){return(this.flags&2)>0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Ss&&(qi=!0),this.height=e)}replace(e,t,i){return Ve.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let a=s.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:h,toB:u}=s[a],f=r.lineAt(l,pe.ByPosNoHeight,i.setDoc(t),0,0),d=f.to>=c?f:r.lineAt(c,pe.ByPosNoHeight,i,0,0);for(u+=d.to-c,c=d.to;a>0&&f.from<=s[a-1].toA;)l=s[a-1].fromA,h=s[a-1].fromB,a--,l<f.from&&(f=r.lineAt(l,pe.ByPosNoHeight,i,0,0));h+=f.from-l,l=f.from;let p=Ta.build(i.setDoc(o),e,h,u);r=Ds(r,r.replace(l,c,p))}return r.updateHeight(i,0)}static empty(){return new ot(0,0,0)}static of(e){if(e.length==1)return e[0];let t=0,i=e.length,s=0,r=0;for(;;)if(t==i)if(s>r*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),i+=1+a.break,s-=a.size}else if(r>s*2){let a=e[i];a.break?e.splice(i,1,a.left,null,a.right):e.splice(i,1,a.left,a.right),i+=2+a.break,r-=a.size}else break;else if(s<r){let a=e[t++];a&&(s+=a.size)}else{let a=e[--i];a&&(r+=a.size)}let o=0;return e[t-1]==null?(o=1,t--):e[t]==null&&(o=1,i++),new qm(Ve.of(e.slice(0,t)),o,Ve.of(e.slice(i)))}}function Ds(n,e){return n==e?n:(n.constructor!=e.constructor&&(qi=!0),e)}Ve.prototype.size=1;const Wm=I.replace({});class Cu extends Ve{constructor(e,t,i){super(e,t),this.deco=i,this.spaceAbove=0}mainBlock(e,t){return new dt(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.deco||0)}blockAt(e,t,i,s){return this.spaceAbove&&e<i+this.spaceAbove?new dt(s,0,i,this.spaceAbove,Wm):this.mainBlock(i,s)}lineAt(e,t,i,s,r){let o=this.mainBlock(s,r);return this.spaceAbove?this.blockAt(0,i,s,r).join(o):o}forEachLine(e,t,i,s,r,o){e<=r+this.length&&t>=r&&o(this.lineAt(0,pe.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}}class ot extends Cu{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new dt(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof ot||s instanceof Ee&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof Ee?s=new ot(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Ve.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class Ee extends Ve{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*r);o=l/r,this.length>r+1&&(a=(this.height-l)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:a}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,s);if(t.lineWrapping){let c=s+(e<t.lineHeight?0:Math.round(Math.max(0,Math.min(1,(e-i)/this.height))*this.length)),h=t.doc.lineAt(c),u=a+h.length*l,f=Math.max(i,e-u/2);return new dt(h.from,h.length,f,u,0)}else{let c=Math.max(0,Math.min(o-r,Math.floor((e-i)/a))),{from:h,length:u}=t.doc.line(r+c);return new dt(h,u,i+a*c,a,0)}}lineAt(e,t,i,s,r){if(t==pe.ByHeight)return this.blockAt(e,i,s,r);if(t==pe.ByPosNoHeight){let{from:d,to:p}=i.doc.lineAt(e);return new dt(d,p-d,0,0,0)}let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(i,r),c=i.doc.lineAt(e),h=a+c.length*l,u=c.number-o,f=s+a*u+l*(c.from-r-u);return new dt(c.from,c.length,Math.max(s,Math.min(f,s+this.height-h)),h,0)}forEachLine(e,t,i,s,r,o){e=Math.max(e,r),t=Math.min(t,r+this.length);let{firstLine:a,perLine:l,perChar:c}=this.heightMetrics(i,r);for(let h=e,u=s;h<=t;){let f=i.doc.lineAt(h);if(h==e){let p=f.number-a;u+=l*p+c*(e-r-p)}let d=l+c*f.length;o(new dt(f.from,f.length,u,d,0)),u+=d,h=f.to+1}}replace(e,t,i){let s=this.length-t;if(s>0){let r=i[i.length-1];r instanceof Ee?i[i.length-1]=new Ee(r.length+s):i.push(null,new Ee(s-1))}if(e>0){let r=i[0];r instanceof Ee?i[0]=new Ee(e+r.length):i.unshift(new Ee(e-1),null)}return Ve.of(i)}decomposeLeft(e,t){t.push(new Ee(e-1),null)}decomposeRight(e,t){t.push(null,new Ee(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],a=Math.max(t,s.from),l=-1;for(s.from>t&&o.push(new Ee(s.from-t-1).updateHeight(e,t));a<=r&&s.more;){let h=e.doc.lineAt(a).length;o.length&&o.push(null);let u=s.heights[s.index++],f=0;u<0&&(f=-u,u=s.heights[s.index++]),l==-1?l=u:Math.abs(u-l)>=Ss&&(l=-2);let d=new ot(h,u,f);d.outdated=!1,o.push(d),a+=h+1}a<=r&&o.push(null,new Ee(r-a).updateHeight(e,a));let c=Ve.of(o);return(l<0||Math.abs(c.height-this.height)>=Ss||Math.abs(l-this.heightMetrics(e,t).perLine)>=Ss)&&(qi=!0),Ds(this,c)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class qm extends Ve{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return e<r?this.left.blockAt(e,t,i,s):this.right.blockAt(e,t,r,s+this.left.length+this.break)}lineAt(e,t,i,s,r){let o=s+this.left.height,a=r+this.left.length+this.break,l=t==pe.ByHeight?e<o:e<a,c=l?this.left.lineAt(e,t,i,s,r):this.right.lineAt(e,t,i,o,a);if(this.break||(l?c.to<a:c.from>a))return c;let h=t==pe.ByPosNoHeight?pe.ByPosNoHeight:pe.ByPos;return l?c.join(this.right.lineAt(a,h,i,o,a)):this.left.lineAt(a,h,i,s,r).join(c)}forEachLine(e,t,i,s,r,o){let a=s+this.left.height,l=r+this.left.length+this.break;if(this.break)e<l&&this.left.forEachLine(e,t,i,s,r,o),t>=l&&this.right.forEachLine(e,t,i,a,l,o);else{let c=this.lineAt(l,pe.ByPos,i,s,r);e<c.from&&this.left.forEachLine(e,c.from-1,i,s,r,o),c.to>=e&&c.from<=t&&o(c),t>c.to&&this.right.forEachLine(c.to+1,t,i,a,l,o)}}replace(e,t,i){let s=this.left.length+this.break;if(t<s)return this.balanced(this.left.replace(e,t,i),this.right);if(e>this.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let a of i)r.push(a);if(e>0&&zl(r,o-1),t<this.length){let a=r.length;this.decomposeRight(t,r),zl(r,a)}return Ve.of(r)}decomposeLeft(e,t){let i=this.left.length;if(e<=i)return this.left.decomposeLeft(e,t);t.push(this.left),this.break&&(i++,e>=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e<i&&this.left.decomposeRight(e,t),this.break&&e<s&&t.push(null),t.push(this.right)}balanced(e,t){return e.size>2*t.size||t.size>2*e.size?Ve.of(this.break?[e,null,t]:[e,t]):(this.left=Ds(this.left,e),this.right=Ds(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,a=t+r.length+this.break,l=null;return s&&s.from<=t+r.length&&s.more?l=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=a+o.length&&s.more?l=o=o.updateHeight(e,a,i,s):o.updateHeight(e,a,i),l?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function zl(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof Ee&&(i=n[e+1])instanceof Ee&&n.splice(e-1,3,new Ee(t.length+1+i.length))}const zm=5;class Ta{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof ot?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new ot(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e<t||i.heightRelevant){let s=i.widget?i.widget.estimatedHeight:0,r=i.widget?i.widget.lineBreaks:0;s<0&&(s=this.oracle.lineHeight);let o=t-e;i.block?this.addBlock(new Cu(o,s,i)):(o||r||s>=zm)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenTo<e&&((this.writtenTo<e-1||this.nodes[this.nodes.length-1]==null)&&this.nodes.push(this.blankContent(this.writtenTo,e-1)),this.nodes.push(null)),this.pos>e&&this.nodes.push(new ot(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new Ee(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ot)return e;let t=new ot(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ot)&&!this.isCovered?this.nodes.push(new ot(0,-1,0)):(this.writtenTo<this.pos||t==null)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos));let i=e;for(let s of this.nodes)s instanceof ot&&s.updateHeight(this.oracle,i),i+=s?s.length:1;return this.nodes}static build(e,t,i,s){let r=new Ta(i,e);return H.spans(t,i,s,r,0),r.finish(i)}}function Vm(n,e,t){let i=new jm;return H.compare(n,e,t,i,0),i.changes}class jm{constructor(){this.changes=[]}compareRange(){}comparePoint(e,t,i,s){(e<t||i&&i.heightRelevant||s&&s.heightRelevant)&&Mi(e,t,this.changes,5)}}function Ym(n,e){let t=n.getBoundingClientRect(),i=n.ownerDocument,s=i.defaultView||window,r=Math.max(0,t.left),o=Math.min(s.innerWidth,t.right),a=Math.max(0,t.top),l=Math.min(s.innerHeight,t.bottom);for(let c=n.parentNode;c&&c!=i.body;)if(c.nodeType==1){let h=c,u=window.getComputedStyle(h);if((h.scrollHeight>h.clientHeight||h.scrollWidth>h.clientWidth)&&u.overflow!="visible"){let f=h.getBoundingClientRect();r=Math.max(r,f.left),o=Math.min(o,f.right),a=Math.max(a,f.top),l=Math.min(c==n.parentNode?s.innerHeight:l,f.bottom)}c=u.position=="absolute"||u.position=="fixed"?h.offsetParent:h.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function Nm(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left<t.innerWidth&&e.right>0&&e.top<t.innerHeight&&e.bottom>0}function Hm(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class Xr{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;i<e.length;i++){let s=e[i],r=t[i];if(s.from!=r.from||s.to!=r.to||s.size!=r.size)return!1}return!0}draw(e,t){return I.replace({widget:new Gm(this.displaySize*(t?e.scaleY:e.scaleX),t)}).range(this.from,this.to)}}class Gm extends Ut{constructor(e,t){super(),this.size=e,this.vertical=t}eq(e){return e.size==this.size&&e.vertical==this.vertical}toDOM(){let e=document.createElement("div");return this.vertical?e.style.height=this.size+"px":(e.style.width=this.size+"px",e.style.height="2px",e.style.display="inline-block"),e}get estimatedHeight(){return this.vertical?this.size:-1}}class Vl{constructor(e,t){this.view=e,this.state=t,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scaleX=1,this.scaleY=1,this.scrollOffset=0,this.scrolledToBottom=!1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=jl,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=fe.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let i=t.facet(ka).some(s=>typeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new Bm(i),this.stateDeco=Yl(t),this.heightMap=Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle.setDoc(t.doc),[new ct(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=I.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Jn(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?jl:new Ra(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(un(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=Yl(this.state);let s=e.changedRanges,r=ct.extendWithRanges(s,Vm(i,this.stateDeco,e?e.changes:Re.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);ql(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||qi)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.head<l.from||t.range.head>l.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(au)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?fe.RTL:fe.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,h=0;if(a.width&&a.height){let{scaleX:Q,scaleY:P}=Bh(t,a);(Q>.005&&Math.abs(this.scaleX-Q)>.005||P>.005&&Math.abs(this.scaleY-P)>.005)&&(this.scaleX=Q,this.scaleY=P,c|=16,o=l=!0)}let u=(parseInt(i.paddingTop)||0)*this.scaleY,f=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=f)&&(this.paddingTop=u,this.paddingBottom=f,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let d=Ih(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=Vh(this.scrollParent||e.win);let m=(this.printing?Hm:Ym)(t,this.paddingTop),g=m.top-this.pixelViewport.top,y=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let x=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(x!=this.inView&&(this.inView=x,x&&(l=!0)),!this.inView&&!this.scrollTarget&&!Nm(e.dom))return 0;let b=a.width;if((this.contentDOMWidth!=b||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let Q=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(Q)&&(o=!0),o||s.lineWrapping&&Math.abs(b-this.contentDOMWidth)>s.charWidth){let{lineHeight:P,charWidth:w,textHeight:L}=e.docView.measureTextSize();o=P>0&&s.refresh(r,P,w,L,Math.max(5,b/w),Q),o&&(e.docView.minWidth=0,c|=16)}g>0&&y>0?h=Math.max(g,y):g<0&&y<0&&(h=Math.min(g,y)),ql();for(let P of this.viewports){let w=P.from==this.viewport.from?Q:e.docView.measureVisibleLineHeights(P);this.heightMap=(o?Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle,[new ct(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Im(P.from,w))}qi&&(c|=2)}let C=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return C&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(h,this.scrollTarget),c|=this.updateForViewport()),(c&2||C)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new Jn(s.lineAt(o-i*1e3,pe.ByHeight,r,0,0).from,s.lineAt(a+(1-i)*1e3,pe.ByHeight,r,0,0).to);if(t){let{head:c}=t.range;if(c<l.from||c>l.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=s.lineAt(c,pe.ByPos,r,0,0),f;t.y=="center"?f=(u.top+u.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&c<l.from?f=u.top:f=u.bottom-h,l=new Jn(s.lineAt(f-1e3/2,pe.ByHeight,r,0,0).from,s.lineAt(f+h+1e3/2,pe.ByHeight,r,0,0).to)}}return l}mapViewport(e,t){let i=t.mapPos(e.from,-1),s=t.mapPos(e.to,1);return new Jn(this.heightMap.lineAt(i,pe.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(s,pe.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:e,to:t},i=0){if(!this.inView)return!0;let{top:s}=this.heightMap.lineAt(e,pe.ByPos,this.heightOracle,0,0),{bottom:r}=this.heightMap.lineAt(t,pe.ByPos,this.heightOracle,0,0),{visibleTop:o,visibleBottom:a}=this;return(e==0||s<=o-Math.max(10,Math.min(-i,250)))&&(t==this.state.doc.length||r>=a+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r<a+2*1e3}mapLineGaps(e,t){if(!e.length||t.empty)return e;let i=[];for(let s of e)t.touchesRange(s.from,s.to)||i.push(new Xr(t.mapPos(s.from),t.mapPos(s.to),s.size,s.displaySize));return i}ensureLineGaps(e,t){let i=this.heightOracle.lineWrapping,s=i?1e4:2e3,r=s>>1,o=s<<1;if(this.defaultTextDirection!=fe.LTR&&!i)return[];let a=[],l=(h,u,f,d)=>{if(u-h<r)return;let p=this.state.selection.main,m=[p.from];p.empty||m.push(p.to);for(let y of m)if(y>h&&y<u){l(h,y-10,f,d),l(y+10,u,f,d);return}let g=Jm(e,y=>y.from>=f.from&&y.to<=f.to&&Math.abs(y.from-h)<r&&Math.abs(y.to-u)<r&&!m.some(x=>y.from<x&&y.to>x));if(!g){if(u<f.to&&t&&i&&t.visibleRanges.some(b=>b.from<=u&&b.to>=u)){let b=t.moveToLineBoundary(A.cursor(u),!1,!0).head;b>h&&(u=b)}let y=this.gapSize(f,h,u,d),x=i||y<2e6?y:2e6;g=new Xr(h,u,y,x)}a.push(g)},c=h=>{if(h.length<o||h.type!=Le.Text)return;let u=_m(h.from,h.to,this.stateDeco);if(u.total<o)return;let f=this.scrollTarget?this.scrollTarget.range.head:null,d,p;if(i){let m=s/this.heightOracle.lineLength*this.heightOracle.lineHeight,g,y;if(f!=null){let x=ts(u,f),b=((this.visibleBottom-this.visibleTop)/2+m)/h.height;g=x-b,y=x+b}else g=(this.visibleTop-h.top-m)/h.height,y=(this.visibleBottom-h.top+m)/h.height;d=es(u,g),p=es(u,y)}else{let m=u.total*this.heightOracle.charWidth,g=s*this.heightOracle.charWidth,y=0;if(m>2e6)for(let P of e)P.from>=h.from&&P.from<h.to&&P.size!=P.displaySize&&P.from*this.heightOracle.charWidth+y<this.pixelViewport.left&&(y=P.size-P.displaySize);let x=this.pixelViewport.left+y,b=this.pixelViewport.right+y,C,Q;if(f!=null){let P=ts(u,f),w=((b-x)/2+g)/m;C=P-w,Q=P+w}else C=(x-g)/m,Q=(b+g)/m;d=es(u,C),p=es(u,Q)}d>h.from&&l(h.from,d,h,u),p<h.to&&l(p,h.to,h,u)};for(let h of this.viewportLines)Array.isArray(h.type)?h.type.forEach(c):c(h);return a}gapSize(e,t,i,s){let r=ts(s,i)-ts(s,t);return this.heightOracle.lineWrapping?e.height*r:s.total*this.heightOracle.charWidth*r}updateLineGaps(e){Xr.same(e,this.lineGaps)||(this.lineGaps=e,this.lineGapDeco=I.set(e.map(t=>t.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];H.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r<i.length&&!(s&8);r++){let o=this.visibleRanges[r],a=i[r];(o.from!=a.from||o.to!=a.to)&&(s|=4,e&&e.mapPos(o.from,-1)==a.from&&e.mapPos(o.to,1)==a.to||(s|=8))}return this.visibleRanges=i,s}lineBlockAt(e){return e>=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||un(this.heightMap.lineAt(e,pe.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||un(this.heightMap.lineAt(this.scaler.fromDOM(e),pe.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return un(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Jn{constructor(e,t){this.from=e,this.to=t}}function _m(n,e,t){let i=[],s=n,r=0;return H.spans(t,n,e,{span(){},point(o,a){o>s&&(i.push({from:s,to:o}),r+=o-s),s=a}},20),s<e&&(i.push({from:s,to:e}),r+=e-s),{total:r,ranges:i}}function es({total:n,ranges:e},t){if(t<=0)return e[0].from;if(t>=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],a=o-r;if(i<=a)return r+i;i-=a}}function ts(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Jm(n,e){for(let t of n)if(e(t))return t}const jl={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function Yl(n){let e=n.facet(dr).filter(i=>typeof i!="function"),t=n.facet(Qa).filter(i=>typeof i!="function");return t.length&&e.push(H.join(t)),e}class Ra{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:a,to:l})=>{let c=t.lineAt(a,pe.ByPos,e,0,0).top,h=t.lineAt(l,pe.ByPos,e,0,0).bottom;return s+=h-c,{from:a,to:l,top:c,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let a of this.viewports)a.domTop=o+(a.top-r)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),r=a.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=t<this.viewports.length?this.viewports[t]:null;if(!r||e<r.top)return s+(e-i)*this.scale;if(e<=r.bottom)return r.domTop+(e-r.top);i=r.bottom,s=r.domBottom}}fromDOM(e){for(let t=0,i=0,s=0;;t++){let r=t<this.viewports.length?this.viewports[t]:null;if(!r||e<r.domTop)return i+(e-s)/this.scale;if(e<=r.domBottom)return r.top+(e-r.domTop);i=r.bottom,s=r.domBottom}}eq(e){return e instanceof Ra?this.scale==e.scale&&this.viewports.length==e.viewports.length&&this.viewports.every((t,i)=>t.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}}function un(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new dt(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>un(s,e)):n._content)}const is=Z.define({combine:n=>n.join(" ")}),qo=Z.define({combine:n=>n.indexOf(!0)>-1}),zo=ti.newName(),Tu=ti.newName(),Ru=ti.newName(),$u={"&light":"."+Tu,"&dark":"."+Ru};function Vo(n,e,t){return new ti(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}const eg=Vo("."+zo,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},$u),tg={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Br=$.ie&&$.ie_version<=11;class ig{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new $p,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);($.ie&&$.ie_version<=11||$.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&$.android&&e.constructor.EDIT_CONTEXT!==!1&&!($.chrome&&$.chrome_version<126)&&(this.editContext=new sg(e),e.state.facet(Lt)&&(e.contentDOM.editContext=this.editContext.editContext)),Br&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()}),this.resizeScroll.observe(e.scrollDOM)),this.addWindowListeners(this.win=e.win),this.start(),typeof IntersectionObserver=="function"&&(this.intersection=new IntersectionObserver(t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(Lt)?i.root.activeElement!=this.dom:!gn(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}($.ie&&$.ie_version<=11||$.android&&$.chrome)&&!i.state.selection.main.empty&&s.focusNode&&On(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=kn(e.root);if(!t)return!1;let i=$.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&ng(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=gn(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime<Date.now()-300&&Zp(this.dom,i)?(this.view.inputState.lastFocusTime=0,e.docView.updateSelection(),!1):(this.selectionRange.setRange(i),s&&(this.selectionChanged=!0),!0)}setSelectionRange(e,t){this.selectionRange.set(e.node,e.offset,t.node,t.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let e=0,t=null;for(let i=this.dom;i;)if(i.nodeType==1)!t&&e<this.scrollTargets.length&&this.scrollTargets[e]==i?e++:t||(t=this.scrollTargets.slice(0,e)),t&&t.push(i),i=i.assignedSlot||i.parentNode;else if(i.nodeType==11)i=i.host;else break;if(e<this.scrollTargets.length&&!t&&(t=this.scrollTargets.slice(0,e)),t){for(let i of this.scrollTargets)i.removeEventListener("scroll",this.onScroll);for(let i of this.scrollTargets=t)i.addEventListener("scroll",this.onScroll)}}ignore(e){if(!this.active)return e();try{return this.stop(),e()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,tg),Br&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),Br&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(e,t){var i;if(!this.delayedAndroidKey){let s=()=>{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&Ei(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange<Date.now()-50||!!(!((i=this.delayedAndroidKey)===null||i===void 0)&&i.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame(()=>{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&gn(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new bm(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=yu(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Fs(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Nl(t,e.previousSibling||e.target.previousSibling,-1),s=Nl(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Lt)!=e.state.facet(Lt)&&(e.view.contentDOM.editContext=e.state.facet(Lt)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function Nl(n,e,t){for(;e;){let i=Se.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Hl(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return On(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function ng(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return Hl(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?Hl(n,t):null}class sg{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,a=this.toEditorPos(i.updateRangeStart),l=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>i.text.length;a==this.from&&r<this.from?a=r:l==this.to&&r>this.to&&(l=r);let h=Au(e.state.sliceDoc(a,l),i.text,(c?s.from:s.to)-a,c?"end":null);if(!h){let f=A.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Fs(f,s)||e.dispatch({selection:f,userEvent:"select"});return}let u={from:h.from+a,to:h.toA+a,insert:se.of(i.text.slice(h.from,h.toB).split(` +`))};if(($.mac||$.android)&&u.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(u={from:a,to:l,insert:se.of([i.text.replace("."," ")])}),this.pendingContextChange=u,!e.state.readOnly){let f=this.to-this.from+(u.to-u.from+u.insert.length);Ca(e,u,A.single(this.toEditorPos(i.selectionStart,f),this.toEditorPos(i.selectionEnd,f)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from<u.to&&!u.insert.length&&e.inputState.composing>=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),a=this.toEditorPos(i.rangeEnd);o<a;o++){let l=e.coordsForChar(o);r=l&&new DOMRect(l.left,l.top,l.right-l.left,l.bottom-l.top)||r||new DOMRect,s.push(r)}t.updateCharacterBounds(i.rangeStart,s)},this.handlers.textformatupdate=i=>{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,a=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(r.rangeStart),c=this.toEditorPos(r.rangeEnd);if(l<c){let h=`text-decoration: underline ${/^[a-z]/.test(o)?o+" ":o=="Dashed"?"dashed ":o=="Squiggle"?"wavy ":""}${/thin/i.test(a)?1:2}px`;s.push(I.mark({attributes:{style:h}}).range(l,c))}}}e.dispatch({effects:cu.of(I.set(s))})},this.handlers.compositionstart=()=>{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let s=kn(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,a,l,c)=>{if(i)return;let h=c.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(c)){s=this.pendingContextChange=null,t+=h,this.to+=h;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=h,this.to+=h;else if(r<this.to){if(r<this.from||o>this.to||this.to-this.from+c.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),c.toString()),this.to+=h}t+=h}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to<e.doc.length&&this.to-t<500||this.to-this.from>1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class K{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Kp(e.parent)||document,this.viewState=new Vl(this,e.state||J.create(e)),e.scrollTo&&e.scrollTo.is(Hn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ti).map(s=>new Er(s));for(let s of this.plugins)s.update(this);this.observer=new ig(this),this.inputState=new wm(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Zl(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof Pe?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let f of e){if(f.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=f.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,a=0,l=null;e.some(f=>f.annotation(ku))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=Qu(r,o),l||(a=1));let c=this.observer.delayedAndroidKey,h=null;if(c?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(h=null)):this.observer.clear(),r.facet(J.phrases)!=this.state.facet(J.phrases))return this.setState(r);s=Ms.create(this,r,e),s.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(u&&(u=u.map(f.changes)),f.scrollIntoView){let{main:d}=f.state.selection,{x:p,y:m}=this.state.facet(K.cursorScrollMargin);u=new Ui(d.empty?d:A.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of f.effects)d.is(Hn)&&(u=d.value.clip(this.state))}this.viewState.update(s,u),this.bidiCache=Ls.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(hn)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(is)!=s.state.facet(is)&&(this.viewState.mustMeasureContent=!0),(t||i||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let f of this.state.facet(Lo))try{f(s)}catch(d){ze(this.state,d,"update listener")}(l||h)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),h&&!yu(this,h)&&c.force&&Ei(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Vl(this,e),this.plugins=e.facet(Ti).map(i=>new Er(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new Zl(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ti),i=e.state.facet(Ti);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Er(r));else{let a=this.plugins[o];a.mustUpdate=e,s.push(a)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s<this.plugins.length;s++)this.plugins[s].update(this);t!=i&&this.inputState.ensureHandlers(this.plugins)}docViewUpdate(){for(let e of this.plugins){let t=e.value;if(t&&t.docViewUpdate)try{t.docViewUpdate(this)}catch(i){ze(this.state,i,"doc view update listener")}}}measure(e=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(Vh(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let h=c.map(d=>{try{return d.read(this)}catch(p){return ze(this.state,p),Gl}}),u=Ms.create(this,this.state,[]),f=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),f=this.docView.update(u),f&&this.docViewUpdate());for(let d=0;d<c.length;d++)if(h[d]!=Gl)try{let p=c[d];p.write&&p.write(h[d],this)}catch(p){ze(this.state,p)}if(f&&this.docView.updateSelection(!0),!u.viewportChanged&&this.measureRequests.length==0){if(this.viewState.editorHeight)if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,o=-1;continue}else{let p=((r<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(r).top)-o)/this.scaleY;if((p>1||p<-1)&&!($.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Lo))a(t)}get themeClasses(){return zo+" "+(this.state.facet(qo)?Ru:Tu)+" "+this.state.facet(is)}updateAttrs(){let e=_l(this,hu,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Lt)?"true":"false",class:"cm-content",style:`${$.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),_l(this,ka,t);let i=this.observer.ignore(()=>{let s=Pl(this.contentDOM,this.contentAttrs,t),r=Pl(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(K.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(hn);let e=this.state.facet(K.cspNonce);ti.mount(this.root,this.styleModules.concat(eg).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;t<this.measureRequests.length;t++)if(this.measureRequests[t].key===e.key){this.measureRequests[t]=e;return}}this.measureRequests.push(e)}}plugin(e){let t=this.pluginMap.get(e);return(t===void 0||t&&t.plugin!=e)&&this.pluginMap.set(e,t=this.plugins.find(i=>i.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Lr(this,e,Ml(this,e,t,i))}moveByGroup(e,t){return Lr(this,e,Ml(this,e,t,i=>pm(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return A.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return dm(this,e,t,i)}moveVertically(e,t,i){return Lr(this,e,mm(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=Io(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),Io(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),r=s[Ct.find(s,e-i.from,-1,t)];return this.docView.coordsAt(e,t,r.dir==fe.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(ou)||e<this.viewport.from||e>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>rg)return _h(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||Gh(r.isolates,i=Rl(this,e))))return r.order;i||(i=Rl(this,e));let s=Xp(e.text,t,i);return this.bidiCache.push(new Ls(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||$.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{zh(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return Hn.of(new Ui(typeof e=="number"?A.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Hn.of(new Ui(A.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return xe.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return xe.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=ti.newName(),s=[is.of(i),hn.of(Vo(`.${i}`,e))];return t&&t.dark&&s.push(qo.of(!0)),s}static baseTheme(e){return oi.lowest(hn.of(Vo("."+zo,e,$u)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&Se.get(i)||Se.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}}K.styleModule=hn;K.inputHandler=su;K.clipboardInputFilter=va;K.clipboardOutputFilter=wa;K.scrollHandler=lu;K.focusChangeEffect=ru;K.perLineTextDirection=ou;K.exceptionSink=nu;K.updateListener=Lo;K.editable=Lt;K.mouseSelectionStyle=iu;K.dragMovesSelection=tu;K.clickAddsSelectionRange=eu;K.decorations=dr;K.blockWrappers=uu;K.outerDecorations=Qa;K.atomicRanges=Ln;K.bidiIsolatedRanges=fu;K.cursorScrollMargin=Z.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});K.scrollMargins=du;K.darkTheme=qo;K.cspNonce=Z.define({combine:n=>n.length?n[0]:""});K.contentAttributes=ka;K.editorAttributes=hu;K.lineWrapping=K.contentAttributes.of({class:"cm-lineWrapping"});K.announce=Y.define();const rg=4096,Gl={};class Ls{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:fe.LTR;for(let r=Math.max(0,e.length-10);r<e.length;r++){let o=e[r];o.dir==s&&!t.touchesRange(o.from,o.to)&&i.push(new Ls(t.mapPos(o.from,1),t.mapPos(o.to,-1),o.dir,o.isolates,!1,o.order))}return i}}function _l(n,e,t){for(let i=n.state.facet(e),s=i.length-1;s>=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&ba(o,t)}return t}const og=$.mac?"mac":$.windows?"win":$.linux?"linux":"key";function ag(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,a;for(let l=0;l<t.length-1;++l){const c=t[l];if(/^(cmd|meta|m)$/i.test(c))a=!0;else if(/^a(lt)?$/i.test(c))s=!0;else if(/^(c|ctrl|control)$/i.test(c))r=!0;else if(/^s(hift)?$/i.test(c))o=!0;else if(/^mod$/i.test(c))e=="mac"?a=!0:r=!0;else throw new Error("Unrecognized modifier name: "+c)}return s&&(i="Alt-"+i),r&&(i="Ctrl-"+i),a&&(i="Meta-"+i),o&&(i="Shift-"+i),i}function ns(n,e,t){return e.altKey&&(n="Alt-"+n),e.ctrlKey&&(n="Ctrl-"+n),e.metaKey&&(n="Meta-"+n),t!==!1&&e.shiftKey&&(n="Shift-"+n),n}const lg=oi.default(K.domEventHandlers({keydown(n,e){return Zu(Ku(e.state),n,e,"editor")}})),Or=Z.define({enables:lg}),Jl=new WeakMap;function Ku(n){let e=n.facet(Or),t=Jl.get(e);return t||Jl.set(e,t=ug(e.reduce((i,s)=>i.concat(s),[]))),t}function cg(n,e,t){return Zu(Ku(n.state),e,n,t)}let Ht=null;const hg=4e3;function ug(n,e=og){let t=Object.create(null),i=Object.create(null),s=(o,a)=>{let l=i[o];if(l==null)i[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,a,l,c,h)=>{var u,f;let d=t[o]||(t[o]=Object.create(null)),p=a.split(/ (?!$)/).map(y=>ag(y,e));for(let y=1;y<p.length;y++){let x=p.slice(0,y).join(" ");s(x,!0),d[x]||(d[x]={preventDefault:!0,stopPropagation:!1,run:[b=>{let C=Ht={view:b,prefix:x,scope:o};return setTimeout(()=>{Ht==C&&(Ht=null)},hg),!0}]})}let m=p.join(" ");s(m,!1);let g=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((f=(u=d._any)===null||u===void 0?void 0:u.run)===null||f===void 0?void 0:f.slice())||[]});l&&g.run.push(l),c&&(g.preventDefault=!0),h&&(g.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let h=t[c]||(t[c]=Object.create(null));h._any||(h._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:u}=o;for(let f in h)h[f].run.push(d=>u(d,jo))}let l=o[e]||o.key;if(l)for(let c of a)r(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}let jo=null;function Zu(n,e,t,i){jo=e;let s=kp(e),r=Ne(s,0),o=Qt(r)==s.length&&s!=" ",a="",l=!1,c=!1,h=!1;Ht&&Ht.view==t&&Ht.scope==i&&(a=Ht.prefix+" ",Su.indexOf(e.keyCode)<0&&(c=!0,Ht=null));let u=new Set,f=g=>{if(g){for(let y of g.run)if(!u.has(y)&&(u.add(y),y(t)))return g.stopPropagation&&(h=!0),!0;g.preventDefault&&(g.stopPropagation&&(h=!0),c=!0)}return!1},d=n[i],p,m;return d&&(f(d[a+ns(s,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!($.windows&&e.ctrlKey&&e.altKey)&&!($.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=ii[e.keyCode])&&p!=s?(f(d[a+ns(p,e,!0)])||e.shiftKey&&(m=vn[e.keyCode])!=s&&m!=p&&f(d[a+ns(m,e,!1)]))&&(l=!0):o&&e.shiftKey&&f(d[a+ns(s,e,!0)])&&(l=!0),!l&&f(d._any)&&(l=!0)),c&&(l=!0),l&&h&&e.stopPropagation(),jo=null,l}class gi{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=Mu(e);return[new gi(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return fg(e,t,i)}}function Mu(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==fe.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function ec(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,a=n.posAtCoords({x:r.left+1,y:o}),l=n.posAtCoords({x:r.right-1,y:o});return a==null||l==null?i:{from:Math.max(i.from,Math.min(a,l)),to:Math.min(i.to,Math.max(a,l))}}function fg(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==fe.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=Mu(n),c=o.querySelector(".cm-line"),h=c&&window.getComputedStyle(c),u=a.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),f=a.right-(h?parseInt(h.paddingRight):0),d=Bo(n,i,1),p=Bo(n,s,-1),m=d.type==Le.Text?d:null,g=p.type==Le.Text?p:null;if(m&&(n.lineWrapping||d.widgetLineBreaks)&&(m=ec(n,i,1,m)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=ec(n,s,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return x(b(t.from,t.to,m));{let Q=m?b(t.from,null,m):C(d,!1),P=g?b(null,t.to,g):C(p,!0),w=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&Q.bottom+n.defaultLineHeight/2<P.top?w.push(y(u,Q.bottom,f,P.top)):Q.bottom<P.top&&n.elementAtHeight((Q.bottom+P.top)/2).type==Le.Text&&(Q.bottom=P.top=(Q.bottom+P.top)/2),x(Q).concat(w).concat(x(P))}function y(Q,P,w,L){return new gi(e,Q-l.left,P-l.top,Math.max(0,w-Q),L-P)}function x({top:Q,bottom:P,horizontal:w}){let L=[];for(let D=0;D<w.length;D+=2)L.push(y(w[D],Q,w[D+1],P));return L}function b(Q,P,w){let L=1e9,D=-1e9,W=[];function F(v,M,k,z,re){let N=n.coordsAtPos(v,v==w.to?-2:2),ee=n.coordsAtPos(k,k==w.from?2:-2);!N||!ee||(L=Math.min(N.top,ee.top,L),D=Math.max(N.bottom,ee.bottom,D),re==fe.LTR?W.push(r&&M?u:N.left,r&&z?f:ee.right):W.push(!r&&z?u:ee.left,!r&&M?f:N.right))}let U=Q??w.from,T=P??w.to;for(let v of n.visibleRanges)if(v.to>U&&v.from<T)for(let M=Math.max(v.from,U),k=Math.min(v.to,T);;){let z=n.state.doc.lineAt(M);for(let re of n.bidiSpans(z)){let N=re.from+z.from,ee=re.to+z.from;if(N>=k)break;ee>M&&F(Math.max(N,M),Q==null&&N<=U,Math.min(ee,k),P==null&&ee>=T,re.dir)}if(M=z.to+1,M>=k)break}return W.length==0&&F(U,Q==null,T,P==null,n.textDirection),{top:L,bottom:D,horizontal:W}}function C(Q,P){let w=a.top+(P?Q.top:Q.bottom);return{top:w,bottom:w,horizontal:[]}}}function dg(n,e){return n.constructor==e.constructor&&n.eq(e)}class pg{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(xs)!=e.state.facet(xs)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(xs);for(;t<i.length&&i[t]!=this.layer;)t++;this.dom.style.zIndex=String((this.layer.above?150:-1)-t)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:e,scaleY:t}=this.view;(e!=this.scaleX||t!=this.scaleY)&&(this.scaleX=e,this.scaleY=t,this.dom.style.transform=`scale(${1/e}, ${1/t})`)}draw(e){if(e.length!=this.drawn.length||e.some((t,i)=>!dg(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,$.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const xs=Z.define();function Eu(n){return[xe.define(e=>new pg(e,n)),xs.of(n)]}const zi=Z.define({combine(n){return yt(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function mg(n={}){return[zi.of(n),gg,Og,Ag,au.of(!0)]}function Uu(n){return n.startState.facet(zi)!=n.state.facet(zi)}const gg=Eu({above:!0,markers(n){let{state:e}=n,t=e.facet(zi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&$.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=s.empty?s:A.cursor(s.head,s.assoc);for(let l of gi.forRange(n,o,a))i.push(l)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Uu(n);return t&&tc(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){tc(e.state,n)},class:"cm-cursorLayer"});function tc(n,e){e.style.animationDuration=n.facet(zi).cursorBlinkRate+"ms"}const Og=Eu({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of gi.forRange(n,"cm-selectionBackground",s))e.push(r);if($.ios&&!t.empty&&n.state.facet(zi).iosSelectionHandles){for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-start",A.cursor(t.from,1)))e.push(s);for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-end",A.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Uu(n)},class:"cm-selectionLayer"}),yg=$.gecko&&$.gecko_version==153?"#ffffff01":"transparent",Ag=oi.highest(K.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${yg} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Fu=Y.define({map(n,e){return n==null?null:e.mapPos(n)}}),fn=Te.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(Fu)?i.value:t,n)}}),bg=xe.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(fn);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(fn)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(fn),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(fn)!=n&&this.view.dispatch({effects:Fu.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Sg(){return[fn,bg]}function ic(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,a;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;a=e.exec(r.value);)s(o+a.index,a)}function xg(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}class vg{constructor(e){const{regexp:t,decoration:i,decorate:s,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,s)this.addMatch=(a,l,c,h)=>s(h,c,c+a[0].length,a,l);else if(typeof i=="function")this.addMatch=(a,l,c,h)=>{let u=i(a,l,c);u&&h(c,c+a[0].length,u)};else if(i)this.addMatch=(a,l,c,h)=>h(c,c+a[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new It,i=t.add.bind(t);for(let{from:s,to:r}of xg(e,this.maxLength))ic(e.state.doc,this.regexp,s,r,(o,a)=>this.addMatch(a,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,a,l)=>{l>=e.view.viewport.from&&a<=e.view.viewport.to&&(i=Math.min(a,i),s=Math.max(l,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),a=Math.min(r.to,s);if(a>=o){let l=e.state.doc.lineAt(o),c=l.to<a?e.state.doc.lineAt(a):l,h=Math.max(r.from,l.from),u=Math.min(r.to,c.to);if(this.boundary){for(;o>l.from;o--)if(this.boundary.test(l.text[o-1-l.from])){h=o;break}for(;a<c.to;a++)if(this.boundary.test(c.text[a-c.from])){u=a;break}}let f=[],d,p=(m,g,y)=>f.push(y.range(m,g));if(l==c)for(this.regexp.lastIndex=h-l.from;(d=this.regexp.exec(l.text))&&d.index<u-l.from;)this.addMatch(d,e,d.index+l.from,p);else ic(e.state.doc,this.regexp,h,u,(m,g)=>this.addMatch(g,e,m,p));t=t.update({filterFrom:h,filterTo:u,filter:(m,g)=>m<h||g>u,add:f})}}return t}}const Yo=/x/.unicode!=null?"gu":"g",wg=new RegExp(`[\0-\b +--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,Yo),kg={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Ir=null;function Qg(){var n;if(Ir==null&&typeof document<"u"&&document.body){let e=document.body.style;Ir=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Ir||!1}const vs=Z.define({combine(n){let e=yt(n,{render:null,specialChars:wg,addSpecialChars:null});return(e.replaceTabs=!Qg())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Yo)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Yo)),e}});function Pg(n={}){return[vs.of(n),Cg()]}let nc=null;function Cg(){return nc||(nc=xe.fromClass(class{constructor(n){this.view=n,this.decorations=I.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(vs)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new vg({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=Ne(e[0],0);if(r==9){let o=s.lineAt(i),a=t.state.tabSize,l=_i(o.text,a,i-o.from);return I.replace({widget:new Kg((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=I.replace({widget:new $g(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(vs);n.startState.facet(vs)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const Tg="•";function Rg(n){return n>=32?Tg:n==10?"␤":String.fromCharCode(9216+n)}class $g extends Ut{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=Rg(this.code),i=e.state.phrase("Control character")+" "+(kg[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}}class Kg extends Ut{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Zg(){return Eg}const Mg=I.line({class:"cm-activeLine"}),Eg=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(Mg.range(s.from)),e=s.from)}return I.set(t)}},{decorations:n=>n.decorations}),No=2e3;function Ug(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>No||t.off>No||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=i;l<=s;l++){let c=n.doc.line(l);c.length<=a&&r.push(A.range(c.from+o,c.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=i;l<=s;l++){let c=n.doc.line(l),h=Co(c.text,o,n.tabSize,!0);if(h<0)r.push(A.cursor(c.to));else{let u=Co(c.text,a,n.tabSize);r.push(A.range(c.from+h,c.from+u))}}}return r}function Fg(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function sc(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>No?-1:s==i.length?Fg(n,e.clientX):_i(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function Dg(n,e){let t=sc(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let a=sc(n,s);if(!a)return i;let l=Ug(n.state,t,a);return l.length?o?A.create(l.concat(i.ranges)):A.create(l):i}}:null}function Lg(n){let e=(t=>t.altKey&&t.button==0);return K.mouseSelectionStyle.of((t,i)=>e(i)?Dg(t,i):null)}const Xg={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},Bg={style:"cursor: crosshair"};function Ig(n={}){let[e,t]=Xg[n.key||"Alt"],i=xe.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,K.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?Bg:null})]}const ss="-10000px";class Du{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(l=>l);if(s===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;l<r.length;l++){let c=r[l],h=-1;if(c){for(let u=0;u<this.tooltips.length;u++){let f=this.tooltips[u];f&&f.create==c.create&&(h=u)}if(h<0)o[l]=this.createTooltipView(c,l?o[l-1]:null),a&&(a[l]=!!c.above);else{let u=o[l]=this.tooltipViews[h];a&&(a[l]=t[h]),u.update&&u.update(e)}}}for(let l of this.tooltipViews)o.indexOf(l)<0&&(this.removeTooltipView(l),(i=l.destroy)===null||i===void 0||i.call(l));return t&&(a.forEach((l,c)=>t[c]=l),t.length=a.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}}function Wg(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const Wr=Z.define({combine:n=>{var e,t,i;return{position:$.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||Wg}}}),rc=new WeakMap,$a=xe.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Wr);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new Du(n,yr,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Wr);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=ss,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if($.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=Pa(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let a=this.manager.tooltipViews[o];return a.getCoords?a.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Wr).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let a=0;a<this.manager.tooltips.length;a++){let l=this.manager.tooltips[a],c=this.manager.tooltipViews[a],{dom:h}=c,u=n.pos[a],f=n.size[a];if(!u||l.clip!==!1&&(u.bottom<=Math.max(t.top,i.top)||u.top>=Math.min(t.bottom,i.bottom)||u.right<Math.max(t.left,i.left)-.1||u.left>Math.min(t.right,i.right)+.1)){h.style.top=ss;continue}let d=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=f.right-f.left,g=(e=rc.get(c))!==null&&e!==void 0?e:f.bottom-f.top,y=c.offset||zg,x=this.view.textDirection==fe.LTR,b=f.width>i.right-i.left?x?i.left:i.right-f.width:x?Math.max(i.left,Math.min(u.left-(d?14:0)+y.x,i.right-m)):Math.min(Math.max(i.left,u.left-m+(d?14:0)-y.x),i.right-m),C=this.above[a];!l.strictSide&&(C?u.top-g-p-y.y<i.top:u.bottom+g+p+y.y>i.bottom)&&C==i.bottom-u.bottom>u.top-i.top&&(C=this.above[a]=!C);let Q=(C?u.top-i.top:i.bottom-u.bottom)-p;if(Q<g&&c.resize!==!1){if(Q<this.view.defaultLineHeight){h.style.top=ss;continue}rc.set(c,g),h.style.height=(g=Q)/r+"px"}else h.style.height&&(h.style.height="");let P=C?u.top-g-p-y.y:u.bottom+p+y.y,w=b+m;if(c.overlap!==!0)for(let L of o)L.left<w&&L.right>b&&L.top<P+g&&L.bottom>P&&(P=C?L.top-g-2-p:L.bottom+p+2);if(this.position=="absolute"?(h.style.top=(P-n.parent.top)/r+"px",oc(h,(b-n.parent.left)/s)):(h.style.top=P/r+"px",oc(h,b/s)),d){let L=u.left+(x?y.x:-y.x)-(b+14-7);d.style.left=L/s+"px"}c.overlap!==!0&&o.push({left:b,top:P,right:w,bottom:P+g}),h.classList.toggle("cm-tooltip-above",C),h.classList.toggle("cm-tooltip-below",!C),c.positioned&&c.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=ss}},{eventObservers:{scroll(){this.maybeMeasure()}}});function oc(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}const qg=K.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),zg={x:0,y:0},yr=Z.define({enables:[$a,qg]}),Xs=Z.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])});class Ar{static create(e){return new Ar(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Du(e,Xs,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Vg=yr.compute([Xs],n=>{let e=n.facet(Xs);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:Ar.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),jg=Z.define();class Yg{constructor(e,t,i,s,r,o){this.view=e,this.source=t,this.field=i,this.locked=s,this.setHover=r,this.hoverTime=o,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;e<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-e):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:e,lastMove:t}=this,i=e.docView.tile.nearest(t.target);if(!i)return;let s,r=1;if(i.isWidget())s=i.posAtStart;else{if(s=e.posAtCoords(t),s==null)return;let o=e.coordsAtPos(s);if(!o||t.y<o.top||t.y>o.bottom||t.x<o.left-e.defaultCharacterWidth||t.x>o.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(s)).find(c=>c.from<=s&&c.to>=s),l=a&&a.dir==fe.RTL?-1:1;r=t.x<o.left?-l:l}this.activateHover(e,s,r)}activateHover(e,t,i,s){let r=this.source(e,t,i),o=a=>{if(a&&!(Array.isArray(a)&&!a.length)){let l=Array.isArray(a)?a:[a];s&&this.locked.set(l,s),e.dispatch({effects:this.setHover.of(l)})}};if(r&&"then"in r){let a=this.pending={pos:t};r.then(l=>{this.pending==a&&(this.pending=null,o(l))},l=>ze(e.state,l,"hover tooltip"))}else o(r)}get tooltip(){let e=this.view.plugin($a),t=e?e.manager.tooltips.findIndex(i=>i.create==Ar.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:s,tooltip:r}=this;if(s.length&&!this.locked.has(s)&&r&&!Ng(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,a=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==a?this.view.posAtCoords(this.lastMove)!=o:!Hg(this.view,o,a,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t);let{active:s}=this;s.length&&!this.locked.has(s)&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const rs=4;function Ng(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let a=o.getBoundingClientRect();s=Math.min(a.top,s),r=Math.max(a.bottom,r)}return e.clientX>=t-rs&&e.clientX<=i+rs&&e.clientY>=s-rs&&e.clientY<=r+rs}function Hg(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),a=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.right<i||o.top>s||Math.min(o.bottom,a)<s)return!1;let l=n.posAtCoords({x:i,y:s},!1);return l>=e&&l<=t}function Lu(n,e={}){let t=Y.define(),i=new WeakMap,s=Te.define({create(){return[]},update(o,a){let l=i.get(o);if(o.length&&(e.hideOnChange&&(a.docChanged||a.selection)?o=[]:l&&l(a)?o=[]:e.hideOn&&(o=o.filter(c=>!e.hideOn(a,c)))),a.docChanged&&o.length){let c=[];for(let h of o){let u=a.changes.mapPos(h.pos,-1,De.TrackDel);if(u!=null){let f=Object.assign(Object.create(null),h);f.pos=u,f.end!=null&&(f.end=a.changes.mapPos(f.end)),c.push(f)}}o=c}for(let c of a.effects)c.is(t)&&(o=c.value,l=void 0),(c.is(Gg)&&!c.value||c.value==s)&&(o=[]);return o.length&&l&&i.set(o,l),o},provide:o=>Xs.from(o)});const r=xe.define(o=>new Yg(o,n,s,i,t,e.hoverTime||300));return{active:s,extension:[s,r,jg.of(r),Vg]}}function Xu(n,e){let t=n.plugin($a);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const Gg=Y.define(),ac=Z.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Bu(n,e){let t=n.plugin(Iu),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Iu=xe.fromClass(class{constructor(n){this.input=n.state.facet(Vi),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(ac);this.top=new os(n,!0,e.topContainer),this.bottom=new os(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(ac);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new os(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new os(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Vi);if(t!=this.input){let i=t.filter(l=>l),s=[],r=[],o=[],a=[];for(let l of i){let c=this.specs.indexOf(l),h;c<0?(h=l(n.view),a.push(h)):(h=this.panels[c],h.update&&h.update(n)),s.push(h),(h.top?r:o).push(h)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>K.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class os{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=lc(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=lc(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function lc(n){let e=n.nextSibling;return n.remove(),e}const Vi=Z.define({enables:Iu});function _g(n,e){let t,i=new Promise(o=>t=o),s=o=>Jg(o,e,t);n.state.field(qr,!1)?n.dispatch({effects:Wu.of(s)}):n.dispatch({effects:Y.appendConfig.of(qr.init(()=>[s]))});let r=qu.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(l=>n.win.setTimeout(l,10)))(()=>{n.state.field(qr).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}const qr=Te.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(Wu)?n=[t.value].concat(n):t.is(qu)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>Vi.computeN([n],e=>e.field(n))}),Wu=Y.define(),qu=Y.define();function Jg(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=he("form"),e.input){let a=he("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),i.appendChild(he("label",(e.label||"")+": ",a))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(he("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let a=0;a<s.length;a++){let l=s[a];l.addEventListener("keydown",c=>{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let r=he("div",i,he("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(a){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(a)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=i.querySelector(e.focus):a=i.querySelector("input")||i.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}class Mt extends ei{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Mt.prototype.elementClass="";Mt.prototype.toDOM=void 0;Mt.prototype.mapMode=De.TrackBefore;Mt.prototype.startSide=Mt.prototype.endSide=-1;Mt.prototype.point=!0;const ws=Z.define(),eO=Z.define(),tO={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>H.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},An=Z.define();function zu(n){return[Vu(),An.of({...tO,...n})]}const cc=Z.define({combine:n=>n.some(e=>e)});function Vu(n){return[iO]}const iO=xe.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(An).map(e=>new uc(n,e)),this.fixed=!n.state.facet(cc);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(cc)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=H.iter(this.view.state.facet(ws),this.view.viewport.from),i=[],s=this.gutters.map(r=>new nO(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let a of r.type)if(a.type==Le.Text&&o){Ho(t,i,a.from);for(let l of s)l.line(this.view,a,i);o=!1}else if(a.widget)for(let l of s)l.widget(this.view,a)}else if(r.type==Le.Text){Ho(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(An),t=n.state.facet(An),i=n.docChanged||n.heightChanged||n.viewportChanged||!H.eq(n.startState.facet(ws),n.state.facet(ws),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new uc(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>K.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==fe.LTR?{left:i,right:s}:{right:i,left:s}})});function hc(n){return Array.isArray(n)?n:[n]}function Ho(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class nO{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=H.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let a=new ju(e,o,r,i);s.elements.push(a),s.dom.appendChild(a.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Ho(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(eO)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class uc{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let l=r.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=s.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,a,s)&&s.preventDefault()});this.markers=hc(t.markers(e)),t.initialSpacer&&(this.spacer=new ju(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=hc(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!H.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class ju{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),sO(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let a=o,l=r<t.length?t[r++]:null,c=!1;if(l){let h=l.elementClass;h&&(i+=" "+h);for(let u=o;u<this.markers.length;u++)if(this.markers[u].compare(l)){a=u,c=!0;break}}else a=this.markers.length;for(;o<a;){let h=this.markers[o++];if(h.toDOM){h.destroy(s);let u=s.nextSibling;s.remove(),s=u}}if(!l)break;l.toDOM&&(c?s=s.nextSibling:this.dom.insertBefore(l.toDOM(e),s)),c&&o++}this.dom.className=i,this.markers=t}destroy(){this.setMarkers(null,[])}}function sO(n,e){if(n.length!=e.length)return!1;for(let t=0;t<n.length;t++)if(!n[t].compare(e[t]))return!1;return!0}const rO=Z.define(),oO=Z.define(),Ri=Z.define({combine(n){return yt(n,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(e,t){let i=Object.assign({},e);for(let s in t){let r=i[s],o=t[s];i[s]=r?(a,l,c)=>r(a,l,c)||o(a,l,c):o}return i}})}});class zr extends Mt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function Vr(n,e){return n.state.facet(Ri).formatNumber(e,n.state)}const aO=An.compute([Ri],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(rO)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new zr(Vr(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(oO)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(Ri)!=e.state.facet(Ri),initialSpacer(e){return new zr(Vr(e,fc(e.state.doc.lines)))},updateSpacer(e,t){let i=Vr(t.view,fc(t.view.state.doc.lines));return i==e.number?e:new zr(i)},domEventHandlers:n.facet(Ri).domEventHandlers,side:"before"}));function lO(n={}){return[Ri.of(n),Vu(),aO]}function fc(n){let e=9;for(;e<n;)e=e*10+9;return e}const cO=new class extends Mt{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},hO=ws.compute(["selection"],n=>{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(cO.range(s)))}return H.of(e)});function uO(){return hO}const Yu=1024;let fO=0;class jr{constructor(e,t){this.from=e,this.to=t}}class _{constructor(e={}){this.id=fO++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=et.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}_.closedBy=new _({deserialize:n=>n.split(" ")});_.openedBy=new _({deserialize:n=>n.split(" ")});_.group=new _({deserialize:n=>n.split(" ")});_.isolate=new _({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});_.contextHash=new _({perNode:!0});_.lookAhead=new _({perNode:!0});_.mounted=new _({perNode:!0});class bn{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[_.mounted.id]}}const dO=Object.create(null);class et{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):dO,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new et(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(_.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(_.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}}et.none=new et("",Object.create(null),0,8);class Ka{constructor(e){this.types=e;for(let t=0;t<e.length;t++)if(e[t].id!=t)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...e){let t=[];for(let i of this.types){let s=null;for(let r of e){let o=r(i);if(o){s||(s=Object.assign({},i.props));let a=o[1],l=o[0];l.combine&&l.id in s&&(a=l.combine(s[l.id],a)),s[l.id]=a}}t.push(s?new et(i.name,s,i.id,i.flags):i)}return new Ka(t)}}const as=new WeakMap,dc=new WeakMap;var be;(function(n){n[n.ExcludeBuffers=1]="ExcludeBuffers",n[n.IncludeAnonymous=2]="IncludeAnonymous",n[n.IgnoreMounts=4]="IgnoreMounts",n[n.IgnoreOverlays=8]="IgnoreOverlays",n[n.EnterBracketed=16]="EnterBracketed"})(be||(be={}));class ke{constructor(e,t,i,s,r){if(this.type=e,this.children=t,this.positions=i,this.length=s,this.props=null,r&&r.length){this.props=Object.create(null);for(let[o,a]of r)this.props[typeof o=="number"?o:o.id]=a}}toString(){let e=bn.get(this);if(e&&!e.overlay)return e.tree.toString();let t="";for(let i of this.children){let s=i.toString();s&&(t&&(t+=","),t+=s)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(t.length?"("+t+")":""):t}cursor(e=0){return new _o(this.topNode,e)}cursorAt(e,t=0,i=0){let s=as.get(this)||this.topNode,r=new _o(s);return r.moveTo(e,t),as.set(this,r._tree),r}get topNode(){return new Je(this,0,0,null)}resolve(e,t=0){let i=Pn(as.get(this)||this.topNode,e,t,!1);return as.set(this,i),i}resolveInner(e,t=0){let i=Pn(dc.get(this)||this.topNode,e,t,!0);return dc.set(this,i),i}resolveStack(e,t=0){return gO(this,e,t)}iterate(e){let{enter:t,leave:i,from:s=0,to:r=this.length}=e,o=e.mode||0,a=(o&be.IncludeAnonymous)>0;for(let l=this.cursor(o|be.IncludeAnonymous);;){let c=!1;if(l.from<=r&&l.to>=s&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&i&&(a||!l.type.isAnonymous)&&i(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Ea(et.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new ke(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new ke(et.none,t,i,s)))}static build(e){return OO(e)}}ke.empty=new ke(et.none,[],[],0);class Za{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Za(this.buffer,this.index)}}class si{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return et.none}toString(){let e=[];for(let t=0;t<this.buffer.length;)e.push(this.childString(t)),t=this.buffer[t+3];return e.join(",")}childString(e){let t=this.buffer[e],i=this.buffer[e+3],s=this.set.types[t],r=s.name;if(/\W/.test(r)&&!s.isError&&(r=JSON.stringify(r)),e+=4,i==e)return r;let o=[];for(;e<i;)o.push(this.childString(e)),e=this.buffer[e+3];return r+"("+o.join(",")+")"}findChild(e,t,i,s,r){let{buffer:o}=this,a=-1;for(let l=e;l!=t&&!(Nu(r,s,o[l+1],o[l+2])&&(a=l,i>0));l=o[l+3]);return a}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let a=e,l=0;a<t;){r[l++]=s[a++],r[l++]=s[a++]-i;let c=r[l++]=s[a++]-i;r[l++]=s[a++]-e,o=Math.max(o,c)}return new si(r,o,this.set)}}function Nu(n,e,t,i){switch(n){case-2:return t<e;case-1:return i>=e&&t<e;case 0:return t<e&&i>e;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Pn(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to<e);){let o=!i&&n instanceof Je&&n.index<0?null:n.parent;if(!o)return n;n=o}let r=i?0:be.IgnoreOverlays;if(i)for(let o=n,a=o.parent;a;o=a,a=o.parent)o instanceof Je&&o.index<0&&((s=a.enter(e,t,r))===null||s===void 0?void 0:s.from)!=o.from&&(n=a);for(;;){let o=n.enter(e,t,r);if(!o)return n;n=o}}class Hu{cursor(e=0){return new _o(this,e)}getChild(e,t=null,i=null){let s=pc(this,e,t,i);return s.length?s[0]:null}getChildren(e,t=null,i=null){return pc(this,e,t,i)}resolve(e,t=0){return Pn(this,e,t,!1)}resolveInner(e,t=0){return Pn(this,e,t,!0)}matchContext(e){return Go(this.parent,e)}enterUnfinishedNodesBefore(e){let t=this.childBefore(e),i=this;for(;t;){let s=t.lastChild;if(!s||s.to!=t.to)break;s.type.isError&&s.from==s.to?(i=t,t=s.prevSibling):t=s}return i}get node(){return this}get next(){return this.parent}}class Je extends Hu{constructor(e,t,i,s){super(),this._tree=e,this.from=t,this.index=i,this._parent=s}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(e,t,i,s,r=0){for(let o=this;;){for(let{children:a,positions:l}=o._tree,c=t>0?a.length:-1;e!=c;e+=t){let h=a[e],u=l[e]+o.from,f;if(!(!(r&be.EnterBracketed&&h instanceof ke&&(f=bn.get(h))&&!f.overlay&&f.bracketed&&i>=u&&i<=u+h.length)&&!Nu(s,i,u,u+h.length))){if(h instanceof si){if(r&be.ExcludeBuffers)continue;let d=h.findChild(0,h.buffer.length,t,i-u,s);if(d>-1)return new Tt(new pO(o,h,e,u),null,d)}else if(r&be.IncludeAnonymous||!h.type.isAnonymous||Ma(h)){let d;if(!(r&be.IgnoreMounts)&&(d=bn.get(h))&&!d.overlay)return new Je(d.tree,u,e,o);let p=new Je(h,u,e,o);return r&be.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?h.children.length-1:0,t,i,s,r)}}}if(r&be.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&be.IgnoreOverlays)&&(s=bn.get(this._tree))&&s.overlay){let r=e-this.from,o=i&be.EnterBracketed&&s.bracketed;for(let{from:a,to:l}of s.overlay)if((t>0||o?a<=r:a<r)&&(t<0||o?l>=r:l>r))return new Je(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function pc(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function Go(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class pO{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}}class Tt extends Hu{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new Tt(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&be.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new Tt(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Tt(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new Tt(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new ke(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function Gu(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;r<n.length;r++){let o=n[r];(o.from>t.from||o.to<t.to)&&(t=o,e=r)}let i=t instanceof Je&&t.index<0?null:t.parent,s=n.slice();return i?s[e]=i:s.splice(e,1),new mO(s,t)}class mO{constructor(e,t){this.heads=e,this.node=t}get next(){return Gu(this.heads)}}function gO(n,e,t){let i=n.resolveInner(e,t),s=null;for(let r=i instanceof Je?i:i.context.parent;r;r=r.parent)if(r.index<0){let o=r.parent;(s||(s=[i])).push(o.resolve(e,t)),r=o}else{let o=bn.get(r.tree);if(o&&o.overlay&&o.overlay[0].from<=e&&o.overlay[o.overlay.length-1].to>=e){let a=new Je(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(Pn(a,e,t,!1))}}return s?Gu(s):i}class _o{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~be.EnterBracketed,e instanceof Je)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof Je?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&be.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&be.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&be.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index<s.buffer.buffer.length)return!1}else for(let r=0;r<this.index;r++)if(s.buffer.buffer[r+3]<this.index)return!1;({index:t,parent:i}=s)}else({index:t,_parent:i}=this._tree);for(;i;{index:t,_parent:i}=i)if(t>-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let a=i._tree.children[r];if(this.mode&be.IncludeAnonymous||a instanceof si||!a.type.isAnonymous||Ma(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to<e))&&this.parent(););for(;this.enterChild(1,e,t););return this}get node(){if(!this.buffer)return this._tree;let e=this.bufferNode,t=null,i=0;if(e&&e.context==this.buffer)e:for(let s=this.index,r=this.stack.length;r>=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s<this.stack.length;s++)t=new Tt(this.buffer,t,this.stack[s]);return this.bufferNode=new Tt(this.buffer,t,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(e,t){for(let i=0;;){let s=!1;if(this.type.isAnonymous||e(this)!==!1){if(this.firstChild()){i++;continue}this.type.isAnonymous||(s=!0)}for(;;){if(s&&t&&t(this),s=this.type.isAnonymous,!i)return;if(this.nextSibling())break;this.parent(),i--,s=!0}}}matchContext(e){if(!this.buffer)return Go(this.node.parent,e);let{buffer:t}=this.buffer,{types:i}=t.set;for(let s=e.length-1,r=this.stack.length-1;s>=0;r--){if(r<0)return Go(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}}function Ma(n){return n.children.some(e=>e instanceof si||!e.type.isAnonymous||Ma(e))}function OO(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=Yu,reused:r=[],minRepeatType:o=i.types.length}=n,a=Array.isArray(t)?new Za(t,t.length):t,l=i.types,c=0,h=0;function u(Q,P,w,L,D,W){let{id:F,start:U,end:T,size:v}=a,M=h,k=c;if(v<0)if(a.next(),v==-1){let q=r[F];w.push(q),L.push(U-Q);return}else if(v==-3){c=F;return}else if(v==-4){h=F;return}else throw new RangeError(`Unrecognized record size: ${v}`);let z=l[F],re,N,ee=U-Q;if(T-U<=s&&(N=g(a.pos-P,D))){let q=new Uint16Array(N.size-N.skip),G=a.pos-N.size,ce=q.length;for(;a.pos>G;)ce=y(N.start,q,ce);re=new si(q,T-N.start,i),ee=N.start-Q}else{let q=a.pos-v;a.next();let G=[],ce=[],V=F>=o?F:-1,te=0,oe=T;for(;a.pos>q;)V>=0&&a.id==V&&a.size>=0?(a.end<=oe-s&&(p(G,ce,U,te,a.end,oe,V,M,k),te=G.length,oe=a.end),a.next()):W>2500?f(U,q,G,ce):u(U,q,G,ce,V,W+1);if(V>=0&&te>0&&te<G.length&&p(G,ce,U,te,U,oe,V,M,k),G.reverse(),ce.reverse(),V>-1&&te>0){let Me=d(z,k);re=Ea(z,G,ce,0,G.length,0,T-U,Me,Me)}else re=m(z,G,ce,T-U,M-T,k)}w.push(re),L.push(ee)}function f(Q,P,w,L){let D=[],W=0,F=-1;for(;a.pos>P;){let{id:U,start:T,end:v,size:M}=a;if(M>4)a.next();else{if(F>-1&&T<F)break;F<0&&(F=v-s),D.push(U,T,v),W++,a.next()}}if(W){let U=new Uint16Array(W*4),T=D[D.length-2];for(let v=D.length-3,M=0;v>=0;v-=3)U[M++]=D[v],U[M++]=D[v+1]-T,U[M++]=D[v+2]-T,U[M++]=M;w.push(new si(U,D[2]-T,i)),L.push(T-Q)}}function d(Q,P){return(w,L,D)=>{let W=0,F=w.length-1,U,T;if(F>=0&&(U=w[F])instanceof ke){if(!F&&U.type==Q&&U.length==D)return U;(T=U.prop(_.lookAhead))&&(W=L[F]+U.length+T)}return m(Q,w,L,D,W,P)}}function p(Q,P,w,L,D,W,F,U,T){let v=[],M=[];for(;Q.length>L;)v.push(Q.pop()),M.push(P.pop()+w-D);Q.push(m(i.types[F],v,M,W-D,U-W,T)),P.push(D-w)}function m(Q,P,w,L,D,W,F){if(W){let U=[_.contextHash,W];F=F?[U].concat(F):[U]}if(D>25){let U=[_.lookAhead,D];F=F?[U].concat(F):[U]}return new ke(Q,P,w,L,F)}function g(Q,P){let w=a.fork(),L=0,D=0,W=0,F=w.end-s,U={size:0,start:0,skip:0};e:for(let T=w.pos-Q;w.pos>T;){let v=w.size;if(w.id==P&&v>=0){U.size=L,U.start=D,U.skip=W,W+=4,L+=4,w.next();continue}let M=w.pos-v;if(v<0||M<T||w.start<F)break;let k=w.id>=o?4:0,z=w.start;for(w.next();w.pos>M;){if(w.size<0)if(w.size==-3||w.size==-4)k+=4;else break e;else w.id>=o&&(k+=4);w.next()}D=z,L+=v,W+=k}return(P<0||L==Q)&&(U.size=L,U.start=D,U.skip=W),U.size>4?U:void 0}function y(Q,P,w){let{id:L,start:D,end:W,size:F}=a;if(a.next(),F>=0&&L<o){let U=w;if(F>4){let T=a.pos-(F-4);for(;a.pos>T;)w=y(Q,P,w)}P[--w]=U,P[--w]=W-Q,P[--w]=D-Q,P[--w]=L}else F==-3?c=L:F==-4&&(h=L);return w}let x=[],b=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,x,b,-1,0);let C=(e=n.length)!==null&&e!==void 0?e:x.length?b[0]+x[0].length:0;return new ke(l[n.topID],x.reverse(),b.reverse(),C)}const mc=new WeakMap;function ks(n,e){if(!n.isAnonymous||e instanceof si||e.type!=n)return 1;let t=mc.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof ke)){t=1;break}t+=ks(n,i)}mc.set(e,t)}return t}function Ea(n,e,t,i,s,r,o,a,l){let c=0;for(let p=i;p<s;p++)c+=ks(n,e[p]);let h=Math.ceil(c*1.5/8),u=[],f=[];function d(p,m,g,y,x){for(let b=g;b<y;){let C=b,Q=m[b],P=ks(n,p[b]);for(b++;b<y;b++){let w=ks(n,p[b]);if(P+w>=h)break;P+=w}if(b==C+1){if(P>h){let w=p[C];d(w.children,w.positions,0,w.children.length,m[C]+x);continue}u.push(p[C])}else{let w=m[b-1]+p[b-1].length-Q;u.push(Ea(n,p,m,C,b,Q,w,null,l))}f.push(Q+x-r)}}return d(e,t,i,s,0),(a||l)(u,f,o)}class yO{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Tt?this.setBuffer(e.context.buffer,e.index,t):e instanceof Je&&this.map.set(e.tree,t)}get(e){return e instanceof Tt?this.getBuffer(e.context.buffer,e.index):e instanceof Je?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Oi{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new Oi(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let h=a<t.length?t[a]:null,u=h?h.fromA:1e9;if(u-l>=i)for(;o&&o.from<u;){let f=o;if(l>=f.from||u<=f.to||c){let d=Math.max(f.from,l)-c,p=Math.min(f.to,u)-c;f=d>=p?null:new Oi(d,p,f.tree,f.offset+c,a>0,!!h)}if(f&&s.push(f),o.to>u)break;o=r<e.length?e[r++]:null}if(!h)break;l=h.toA,c=h.toA-h.toB}return s}}class _u{startParse(e,t,i){return typeof e=="string"&&(e=new AO(e)),i=i?i.length?i.map(s=>new jr(s.from,s.to)):[new jr(0,0)]:[new jr(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}}class AO{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new _({perNode:!0});let bO=0;class lt{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=bO++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof lt&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new lt(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new Bs(e);return i=>i.modified.indexOf(t)>-1?i:Bs.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}}let SO=0;class Bs{constructor(e){this.name=e,this.instances=[],this.id=SO++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(a=>a.base==e&&xO(t,a.modified));if(i)return i;let s=[],r=new lt(e.name,s,e,t);for(let a of t)a.instances.push(r);let o=vO(t);for(let a of e.set)if(!a.modified.length)for(let l of o)s.push(Bs.get(a,l));return r}}function xO(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function vO(n){let e=[[]];for(let t=0;t<n.length;t++)for(let i=0,s=e.length;i<s;i++)e.push(e[i].concat(n[t]));return e.sort((t,i)=>i.length-t.length)}function Ju(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,a=s;for(let u=0;;){if(a=="..."&&u>0&&u+3==s.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!f)throw new RangeError("Invalid path: "+s);if(r.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),u+=f[0].length,u==s.length)break;let d=s[u++];if(u==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);a=s.slice(u)}let l=r.length-1,c=r[l];if(!c)throw new RangeError("Invalid path: "+s);let h=new Cn(i,o,l>0?r.slice(0,l):null);e[c]=h.sort(e[c])}}return ef.add(e)}const ef=new _({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Cn(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}});class Cn{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth<this.depth?(this.next=e,this):(e.next=this.sort(e.next),e)}get depth(){return this.context?this.context.length:0}}Cn.empty=new Cn([],2,null);function tf(n,e){let t=Object.create(null);for(let r of n)if(!Array.isArray(r.tag))t[r.tag.id]=r.class;else for(let o of r.tag)t[o.id]=r.class;let{scope:i,all:s=null}=e||{};return{style:r=>{let o=s;for(let a of r)for(let l of a.set){let c=t[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:i}}function wO(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function kO(n,e,t,i=0,s=n.length){let r=new QO(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}class QO{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:a,to:l}=e;if(a>=i||l<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let c=s,h=PO(e)||Cn.empty,u=wO(r,h.tags);if(u&&(c&&(c+=" "),c+=u,h.mode==1&&(s+=(s?" ":"")+u)),this.startSpan(Math.max(t,a),c),h.opaque)return;let f=e.tree&&e.tree.prop(_.mounted);if(f&&f.overlay){let d=e.node.enter(f.overlay[0].from+a,1),p=this.highlighters.filter(g=>!g.scope||g.scope(f.tree.type)),m=e.firstChild();for(let g=0,y=a;;g++){let x=g<f.overlay.length?f.overlay[g]:null,b=x?x.from+a:l,C=Math.max(t,y),Q=Math.min(i,b);if(C<Q&&m)for(;e.from<Q&&(this.highlightRange(e,C,Q,s,r),this.startSpan(Math.min(Q,e.to),c),!(e.to>=b||!e.nextSibling())););if(!x||b>i)break;y=x.to+a,y>t&&(this.highlightRange(d.cursor(),Math.max(t,x.from+a),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),c))}m&&e.parent()}else if(e.firstChild()){f&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),c)}while(e.nextSibling());e.parent()}}}function PO(n){let e=n.type.prop(ef);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const R=lt.define,ls=R(),jt=R(),gc=R(jt),Oc=R(jt),Yt=R(),cs=R(Yt),Yr=R(Yt),wt=R(),ci=R(wt),xt=R(),vt=R(),Jo=R(),on=R(Jo),hs=R(),O={comment:ls,lineComment:R(ls),blockComment:R(ls),docComment:R(ls),name:jt,variableName:R(jt),typeName:gc,tagName:R(gc),propertyName:Oc,attributeName:R(Oc),className:R(jt),labelName:R(jt),namespace:R(jt),macroName:R(jt),literal:Yt,string:cs,docString:R(cs),character:R(cs),attributeValue:R(cs),number:Yr,integer:R(Yr),float:R(Yr),bool:R(Yt),regexp:R(Yt),escape:R(Yt),color:R(Yt),url:R(Yt),keyword:xt,self:R(xt),null:R(xt),atom:R(xt),unit:R(xt),modifier:R(xt),operatorKeyword:R(xt),controlKeyword:R(xt),definitionKeyword:R(xt),moduleKeyword:R(xt),operator:vt,derefOperator:R(vt),arithmeticOperator:R(vt),logicOperator:R(vt),bitwiseOperator:R(vt),compareOperator:R(vt),updateOperator:R(vt),definitionOperator:R(vt),typeOperator:R(vt),controlOperator:R(vt),punctuation:Jo,separator:R(Jo),bracket:on,angleBracket:R(on),squareBracket:R(on),paren:R(on),brace:R(on),content:wt,heading:ci,heading1:R(ci),heading2:R(ci),heading3:R(ci),heading4:R(ci),heading5:R(ci),heading6:R(ci),contentSeparator:R(wt),list:R(wt),quote:R(wt),emphasis:R(wt),strong:R(wt),link:R(wt),monospace:R(wt),strikethrough:R(wt),inserted:R(),deleted:R(),changed:R(),invalid:R(),meta:hs,documentMeta:R(hs),annotation:R(hs),processingInstruction:R(hs),definition:lt.defineModifier("definition"),constant:lt.defineModifier("constant"),function:lt.defineModifier("function"),standard:lt.defineModifier("standard"),local:lt.defineModifier("local"),special:lt.defineModifier("special")};for(let n in O){let e=O[n];e instanceof lt&&(e.name=n)}tf([{tag:O.link,class:"tok-link"},{tag:O.heading,class:"tok-heading"},{tag:O.emphasis,class:"tok-emphasis"},{tag:O.strong,class:"tok-strong"},{tag:O.keyword,class:"tok-keyword"},{tag:O.atom,class:"tok-atom"},{tag:O.bool,class:"tok-bool"},{tag:O.url,class:"tok-url"},{tag:O.labelName,class:"tok-labelName"},{tag:O.inserted,class:"tok-inserted"},{tag:O.deleted,class:"tok-deleted"},{tag:O.literal,class:"tok-literal"},{tag:O.string,class:"tok-string"},{tag:O.number,class:"tok-number"},{tag:[O.regexp,O.escape,O.special(O.string)],class:"tok-string2"},{tag:O.variableName,class:"tok-variableName"},{tag:O.local(O.variableName),class:"tok-variableName tok-local"},{tag:O.definition(O.variableName),class:"tok-variableName tok-definition"},{tag:O.special(O.variableName),class:"tok-variableName2"},{tag:O.definition(O.propertyName),class:"tok-propertyName tok-definition"},{tag:O.typeName,class:"tok-typeName"},{tag:O.namespace,class:"tok-namespace"},{tag:O.className,class:"tok-className"},{tag:O.macroName,class:"tok-macroName"},{tag:O.propertyName,class:"tok-propertyName"},{tag:O.operator,class:"tok-operator"},{tag:O.comment,class:"tok-comment"},{tag:O.meta,class:"tok-meta"},{tag:O.invalid,class:"tok-invalid"},{tag:O.punctuation,class:"tok-punctuation"}]);var Nr;const $i=new _;function nf(n){return Z.define({combine:n?e=>e.concat(n):void 0})}const Ua=new _;class mt{constructor(e,t,i=[],s=""){this.data=e,this.name=s,J.prototype.hasOwnProperty("tree")||Object.defineProperty(J.prototype,"tree",{get(){return Ce(this)}}),this.parser=t,this.extension=[ri.of(this),J.languageData.of((r,o,a)=>{let l=yc(r,o,a),c=l.type.prop($i);if(!c)return[];let h=r.facet(c),u=l.type.prop(Ua);if(u){let f=l.resolve(o-l.from,a);for(let d of u)if(d.test(f,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(h)}}return h})].concat(i)}isActiveAt(e,t,i=-1){return yc(e,t,i).type.prop($i)==this.data}findRegions(e){let t=e.facet(ri);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop($i)==this.data){i.push({from:o,to:o+r.length});return}let a=r.prop(_.mounted);if(a){if(a.tree.prop($i)==this.data){if(a.overlay)for(let l of a.overlay)i.push({from:l.from+o,to:l.to+o});else i.push({from:o,to:o+r.length});return}else if(a.overlay){let l=i.length;if(s(a.tree,a.overlay[0].from+o),i.length>l)return}}for(let l=0;l<r.children.length;l++){let c=r.children[l];c instanceof ke&&s(c,r.positions[l]+o)}};return s(Ce(e),0),i}get allowsNesting(){return!0}}mt.setState=Y.define();function yc(n,e,t){let i=n.facet(ri),s=Ce(n).topNode;if(!i||i.allowsNesting)for(let r=s;r;r=r.enter(e,t,be.ExcludeBuffers|be.EnterBracketed))r.type.isTop&&(s=r);return s}class Is extends mt{constructor(e,t,i){super(e,t,[],i),this.parser=t}static define(e){let t=nf(e.languageData);return new Is(t,e.parser.configure({props:[$i.add(i=>i.isTop?t:void 0)]}),e.name)}configure(e,t){return new Is(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Ce(n){let e=n.field(mt.state,!1);return e?e.tree:ke.empty}class CO{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e<i||t>=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let an=null;class Ws{constructor(e,t,i=[],s,r,o,a,l){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new Ws(e,t,[],ke.empty,0,i,[],null)}startParse(){return this.parser.startParse(new CO(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=ke.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t<this.state.doc.length&&this.parse.stopAt(t);;){let s=this.parse.advance();if(s)if(this.fragments=this.withoutTempSkipped(Oi.addTree(s,this.fragments,this.parse.stoppedAt!=null)),this.treeLen=(i=this.parse.stoppedAt)!==null&&i!==void 0?i:this.state.doc.length,this.tree=s,this.parse=null,this.treeLen<(t??this.state.doc.length))this.parse=this.startParse();else return!0;if(e())return!1}})}takeTree(){let e,t;this.parse&&(e=this.parse.parsedPos)>=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Oi.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=an;an=this;try{return e()}finally{an=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Ac(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,h,u,f)=>l.push({fromA:c,toA:h,fromB:u,toB:f})),i=Oi.applyChanges(i,l),s=ke.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let h=e.mapPos(c.from,1),u=e.mapPos(c.to,-1);h<u&&a.push({from:h,to:u})}}}return new Ws(this.parser,t,i,s,r,o,a,this.scheduleOn)}updateViewport(e){if(this.viewport.from==e.from&&this.viewport.to==e.to)return!1;this.viewport=e;let t=this.skipped.length;for(let i=0;i<this.skipped.length;i++){let{from:s,to:r}=this.skipped[i];s<e.to&&r>e.from&&(this.fragments=Ac(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends _u{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let l=an;if(l){for(let c of s)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new ke(et.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return an}}function Ac(n,e,t){return Oi.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class ji{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new ji(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Ws.create(e.facet(ri).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new ji(i)}}mt.state=Te.define({create:ji.init,update(n,e){for(let t of e.effects)if(t.is(mt.setState))return t.value;return e.startState.facet(ri)!=e.state.facet(ri)?ji.init(e.state):n.apply(e)}});let sf=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(sf=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const Hr=typeof navigator<"u"&&(!((Nr=navigator.scheduling)===null||Nr===void 0)&&Nr.isInputPending)?()=>navigator.scheduling.isInputPending():null,TO=xe.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(mt.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(mt.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=sf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnd<t&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=t+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:i,viewport:{to:s}}=this.view,r=i.field(mt.state);if(r.tree==r.context.tree&&r.context.isDone(s+1e5))return;let o=Date.now()+Math.min(this.chunkBudget,100,e&&!Hr?Math.max(25,e.timeRemaining()-5):1e9),a=r.context.treeLen<s&&i.doc.length>s+1e3,l=r.context.work(()=>Hr&&Hr()||Date.now()>o,s+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:mt.setState.of(new ji(r.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ze(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ri=Z.define({combine(n){return n.length?n[0]:null},enables:n=>[mt.state,TO,K.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class RO{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}const $O=Z.define(),br=Z.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function qs(n){let e=n.facet(br);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Tn(n,e){let t="",i=n.tabSize,s=n.facet(br)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r<e;r++)t+=s;return t}function Fa(n,e){n instanceof J&&(n=new Sr(n));for(let i of n.state.facet($O)){let s=i(n,e);if(s!==void 0)return s}let t=Ce(n.state);return t.length>=e?KO(n,t,e):null}class Sr{constructor(e,t={}){this.state=e,this.options=t,this.unit=qs(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s<e:s<=e)?{text:i.text.slice(s-i.from),from:s}:{text:i.text.slice(0,s-i.from),from:i.from}:i}textAfterPos(e,t=1){if(this.options.simulateDoubleBreak&&e==this.options.simulateBreak)return"";let{text:i,from:s}=this.lineAt(e,t);return i.slice(e-s,Math.min(i.length,e+100-s))}column(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.countColumn(i,e-s),o=this.options.overrideIndentation?this.options.overrideIndentation(s):-1;return o>-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return _i(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const rf=new _;function KO(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.from<i.node.from||o.to>i.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return of(i,n,t)}function of(n,e,t){for(let i=n;i;i=i.next){let s=MO(i.node);if(s)return s(Da.create(e,t,i))}return 0}function ZO(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function MO(n){let e=n.type.prop(rf);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(_.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>af(o,!0,1,void 0,r&&!ZO(o)?s.from:void 0)}return n.parent==null?EO:null}function EO(){return 0}class Da extends Sr{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new Da(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(UO(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return of(this.context.next,this.base,this.pos)}}function UO(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function FO(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==i)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+c}}a=l.to}}function DO({closing:n,align:e=!0,units:t=1}){return i=>af(i,e,t,n)}function af(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,a=i&&r.slice(o,o+i.length)==i||s==n.pos+o,l=e?FO(n):null;return l?a?n.column(l.from):n.column(l.to):n.baseIndent+(a?0:n.unit*t)}const LO=n=>n.baseIndent;function Gr({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const XO=200;function BO(){return J.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+XO)return n;let r=t.sliceString(s.from,i);if(!e.some(c=>c.test(r)))return n;let{state:o}=n,a=-1,l=[];for(let{head:c}of o.selection.ranges){let h=o.doc.lineAt(c);if(h.from==a)continue;a=h.from;let u=Fa(o,h.from);if(u==null)continue;let f=/^\s*/.exec(h.text)[0],d=Tn(o,u);f!=d&&l.push({from:h.from,to:h.from+f.length,insert:d})}return l.length?[n,{changes:l,sequential:!0}]:n})}const IO=Z.define(),lf=new _;function WO(n){let e=n.firstChild,t=n.lastChild;return e&&e.to<t.from?{from:e.to,to:t.type.isError?n.to:t.from}:null}function qO(n,e,t){let i=Ce(n);if(i.length<t)return null;let s=i.resolveStack(t,1),r=null;for(let o=s;o;o=o.next){let a=o.node;if(a.to<=t||a.from>t)continue;if(r&&a.from<e)break;let l=a.type.prop(lf);if(l&&(a.to<i.length-50||i.length==n.doc.length||!zO(a))){let c=l(a,n);c&&c.from<=t&&c.from>=e&&c.to>t&&(r=c)}}return r}function zO(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function zs(n,e,t){for(let i of n.facet(IO)){let s=i(n,e,t);if(s)return s}return qO(n,e,t)}function cf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const xr=Y.define({map:cf}),Xn=Y.define({map:cf});function hf(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const xi=Te.define({create(){return I.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((i,s)=>n=bc(n,i,s)),n=n.map(e.changes);let t=[];for(let i of e.effects)i.is(xr)&&!VO(n,i.value.from,i.value.to)?t.push(i.value):i.is(Xn)&&(n=n.update({filter:(s,r)=>i.value.from!=s||i.value.to!=r,filterFrom:i.value.from,filterTo:i.value.to}));if(t.length){let{preparePlaceholder:i}=e.state.facet(df),s=t.map(r=>(i?I.replace({widget:new JO(i(e.state,r))}):Sc).range(r.from,r.to));n=n.update({add:s})}return e.selection&&(n=bc(n,e.selection.main.head)),n},provide:n=>K.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t<n.length;){let i=n[t++],s=n[t++];if(typeof i!="number"||typeof s!="number")throw new RangeError("Invalid JSON for fold state");e.push(Sc.range(i,s))}return I.set(e,!0)}});function bc(n,e,t=e){let i=!1;return n.between(e,t,(s,r)=>{s<t&&r>e&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function Vs(n,e,t){var i;let s=null;return(i=n.field(xi,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function VO(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function uf(n,e){return n.field(xi,!1)?e:e.concat(Y.appendConfig.of(pf()))}const jO=n=>{for(let e of hf(n)){let t=zs(n.state,e.from,e.to);if(t)return n.dispatch({effects:uf(n.state,[xr.of(t),ff(n,t)])}),!0}return!1},YO=n=>{if(!n.state.field(xi,!1))return!1;let e=[];for(let t of hf(n)){let i=Vs(n.state,t.from,t.to);i&&e.push(Xn.of(i),ff(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function ff(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return K.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}const NO=n=>{let{state:e}=n,t=[];for(let i=0;i<e.doc.length;){let s=n.lineBlockAt(i),r=zs(e,s.from,s.to);r&&t.push(xr.of(r)),i=(r?n.lineBlockAt(r.to):s).to+1}return t.length&&n.dispatch({effects:uf(n.state,t)}),!!t.length},HO=n=>{let e=n.state.field(xi,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(Xn.of({from:i,to:s}))}),n.dispatch({effects:t}),!0},GO=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:jO},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:YO},{key:"Ctrl-Alt-[",run:NO},{key:"Ctrl-Alt-]",run:HO}],_O={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},df=Z.define({combine(n){return yt(n,_O)}});function pf(n){return[xi,i0]}function mf(n,e){let{state:t}=n,i=t.facet(df),s=o=>{let a=n.lineBlockAt(n.posAtDOM(o.target)),l=Vs(n.state,a.from,a.to);l&&n.dispatch({effects:Xn.of(l)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}const Sc=I.replace({widget:new class extends Ut{toDOM(n){return mf(n,null)}}});class JO extends Ut{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return mf(e,this.value)}}const e0={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class _r extends Mt{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function t0(n={}){let e={...e0,...n},t=new _r(e,!0),i=new _r(e,!1),s=xe.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(ri)!=o.state.facet(ri)||o.startState.field(xi,!1)!=o.state.field(xi,!1)||Ce(o.startState)!=Ce(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new It;for(let l of o.viewportLineBlocks){let c=Vs(o.state,l.from,l.to)?i:zs(o.state,l.from,l.to)?t:null;c&&a.add(l.from,l.from,c)}return a.finish()}}),{domEventHandlers:r}=e;return[s,zu({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(s))===null||a===void 0?void 0:a.markers)||H.empty},initialSpacer(){return new _r(e,!1)},domEventHandlers:{...r,click:(o,a,l)=>{if(r.click&&r.click(o,a,l))return!0;let c=Vs(o.state,a.from,a.to);if(c)return o.dispatch({effects:Xn.of(c)}),!0;let h=zs(o.state,a.from,a.to);return h?(o.dispatch({effects:xr.of(h)}),!0):!1}}}),pf()]}const i0=K.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class Bn{constructor(e,t){this.specs=e;let i;function s(a){let l=ti.newName();return(i||(i=Object.create(null)))["."+l]=a,l}const r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof mt?a=>a.prop($i)==o.data:o?a=>a==o:void 0,this.style=tf(e.map(a=>({tag:a.tag,class:a.class||s(Object.assign({},a,{tag:null}))})),{all:r}).style,this.module=i?new ti(i):null,this.themeType=t.themeType}static define(e,t){return new Bn(e,t||{})}}const ea=Z.define(),n0=Z.define({combine(n){return n.length?[n[0]]:null}});function Jr(n){let e=n.facet(ea);return e.length?e:n.facet(n0)}function s0(n,e){let t=[o0],i;return n instanceof Bn&&(n.module&&t.push(K.styleModule.of(n.module)),i=n.themeType),i?t.push(ea.computeN([K.darkTheme],s=>s.facet(K.darkTheme)==(i=="dark")?[n]:[])):t.push(ea.of(n)),t}class r0{constructor(e){this.markCache=Object.create(null),this.tree=Ce(e.state),this.decorations=this.buildDeco(e,Jr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=Ce(e.state),i=Jr(e.state),s=i!=Jr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length<r.to&&!s&&t.type==this.tree.type&&o>=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return I.none;let i=new It;for(let{from:s,to:r}of e.visibleRanges)kO(this.tree,t,(o,a,l)=>{i.add(o,a,this.markCache[l]||(this.markCache[l]=I.mark({class:l})))},s,r);return i.finish()}}const o0=oi.high(xe.fromClass(r0,{decorations:n=>n.decorations})),a0=Bn.define([{tag:O.meta,color:"#404740"},{tag:O.link,textDecoration:"underline"},{tag:O.heading,textDecoration:"underline",fontWeight:"bold"},{tag:O.emphasis,fontStyle:"italic"},{tag:O.strong,fontWeight:"bold"},{tag:O.strikethrough,textDecoration:"line-through"},{tag:O.keyword,color:"#708"},{tag:[O.atom,O.bool,O.url,O.contentSeparator,O.labelName],color:"#219"},{tag:[O.literal,O.inserted],color:"#164"},{tag:[O.string,O.deleted],color:"#a11"},{tag:[O.regexp,O.escape,O.special(O.string)],color:"#e40"},{tag:O.definition(O.variableName),color:"#00f"},{tag:O.local(O.variableName),color:"#30a"},{tag:[O.typeName,O.namespace],color:"#085"},{tag:O.className,color:"#167"},{tag:[O.special(O.variableName),O.macroName],color:"#256"},{tag:O.definition(O.propertyName),color:"#00c"},{tag:O.comment,color:"#940"},{tag:O.invalid,color:"#f00"}]),l0=K.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),gf=1e4,Of="()[]{}",yf=Z.define({combine(n){return yt(n,{afterCursor:!0,brackets:Of,maxScanDistance:gf,renderMatch:u0})}}),c0=I.mark({class:"cm-matchingBracket"}),h0=I.mark({class:"cm-nonmatchingBracket"});function u0(n){let e=[],t=n.matched?c0:h0;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function xc(n){let e=[],t=n.facet(yf);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Rt(n,i.head,-1,t)||i.head>0&&Rt(n,i.head-1,1,t)||t.afterCursor&&(Rt(n,i.head,1,t)||i.head<n.doc.length&&Rt(n,i.head+1,-1,t));s&&(e=e.concat(t.renderMatch(s,n)))}return I.set(e,!0)}const f0=xe.fromClass(class{constructor(n){this.paused=!1,this.decorations=xc(n.state)}update(n){(n.docChanged||n.selectionSet||this.paused)&&(n.view.composing?(this.decorations=this.decorations.map(n.changes),this.paused=!0):(this.decorations=xc(n.state),this.paused=!1))}},{decorations:n=>n.decorations}),d0=[f0,l0];function p0(n={}){return[yf.of(n),d0]}const m0=new _;function ta(n,e,t){let i=n.prop(e<0?_.openedBy:_.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function ia(n){let e=n.type.prop(m0);return e?e(n.node):n}function Rt(n,e,t,i={}){let s=i.maxScanDistance||gf,r=i.brackets||Of,o=Ce(n),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let c=ta(l.type,t,r);if(c&&l.from<l.to){let h=ia(l);if(h&&(t>0?e>=h.from&&e<h.to:e>h.from&&e<=h.to))return g0(n,e,t,l,h,c,r)}}return O0(n,e,t,o,a.type,s,r)}function g0(n,e,t,i,s,r,o){let a=i.parent,l={from:s.from,to:s.to},c=0,h=a?.cursor();if(h&&(t<0?h.childBefore(i.from):h.childAfter(i.to)))do if(t<0?h.to<=i.from:h.from>=i.to){if(c==0&&r.indexOf(h.type.name)>-1&&h.from<h.to){let u=ia(h);return{start:l,end:u?{from:u.from,to:u.to}:void 0,matched:!0}}else if(ta(h.type,t,o))c++;else if(ta(h.type,-t,o)){if(c==0){let u=ia(h);return{start:l,end:u&&u.from<u.to?{from:u.from,to:u.to}:void 0,matched:!1}}c--}}while(t<0?h.prevSibling():h.nextSibling());return{start:l,matched:!1}}function O0(n,e,t,i,s,r,o){if(t<0?!e:e==n.doc.length)return null;let a=t<0?n.sliceDoc(e-1,e):n.sliceDoc(e,e+1),l=o.indexOf(a);if(l<0||l%2==0!=t>0)return null;let c={from:t<0?e-1:e,to:t>0?e+1:e},h=n.doc.iterRange(e,t>0?n.doc.length:0),u=0;for(let f=0;!h.next().done&&f<=r;){let d=h.value;t<0&&(f+=d.length);let p=e+f*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let y=o.indexOf(d[m]);if(!(y<0||i.resolveInner(p+m,1).type!=s))if(y%2==0==t>0)u++;else{if(u==1)return{start:c,end:{from:p+m,to:p+m+1},matched:y>>1==l>>1};u--}}t>0&&(f+=d.length)}return h.done?{start:c,matched:!1}:null}const y0=Object.create(null),vc=[et.none],wc=[],kc=Object.create(null),A0=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])A0[n]=b0(y0,e);function eo(n,e){wc.indexOf(n)>-1||(wc.push(n),console.warn(e))}function b0(n,e){let t=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let h=n[c]||O[c];h?typeof h=="function"?l.length?l=l.map(h):eo(c,`Modifier ${c} used at start of tag`):l.length?eo(c,`Tag ${c} used as modifier`):l=Array.isArray(h)?h:[h]:eo(c,`Unknown highlighting tag ${c}`)}for(let c of l)t.push(c)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(a=>a.id),r=kc[s];if(r)return r.id;let o=kc[s]=et.define({id:vc.length,name:i,props:[Ju({[i]:t})]});return vc.push(o),o.id}fe.RTL,fe.LTR;const S0=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=Xa(n.state,t.from);return i.line?x0(n):i.block?w0(n):!1};function La(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}const x0=La(P0,0),v0=La(Af,0),w0=La((n,e)=>Af(n,e,Q0(e)),0);function Xa(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const ln=50;function k0(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-ln,i),o=n.sliceDoc(s,s+ln),a=/\s*$/.exec(r)[0].length,l=/^\s*/.exec(o)[0].length,c=r.length-a;if(r.slice(c-e.length,c)==e&&o.slice(l,l+t.length)==t)return{open:{pos:i-a,margin:a&&1},close:{pos:s+l,margin:l&&1}};let h,u;s-i<=2*ln?h=u=n.sliceDoc(i,s):(h=n.sliceDoc(i,i+ln),u=n.sliceDoc(s-ln,s));let f=/^\s*/.exec(h)[0].length,d=/\s*$/.exec(u)[0].length,p=u.length-d-t.length;return h.slice(f,f+e.length)==e&&u.slice(p,p+t.length)==t?{open:{pos:i+f+e.length,margin:/\s/.test(h.charAt(f+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(u.charAt(p-1))?1:0}}:null}function Q0(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function Af(n,e,t=e.selection.ranges){let i=t.map(r=>Xa(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>k0(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,a;o<s.length;o++)if(a=s[o]){let l=i[o],{open:c,close:h}=a;r.push({from:c.pos-l.open.length,to:c.pos+c.margin},{from:h.pos-h.margin,to:h.pos+l.close.length})}return{changes:r}}return null}function P0(n,e,t=e.selection.ranges){let i=[],s=-1;e:for(let{from:r,to:o}of t){let a=i.length,l=1e9,c;for(let h=r;h<=o;){let u=e.doc.lineAt(h);if(c==null&&(c=Xa(e,u.from).line,!c))continue e;if(u.from>s&&(r==o||o>u.from)){s=u.from;let f=/^\s*/.exec(u.text)[0].length,d=f==u.length,p=u.text.slice(f,f+c.length)==c?f:-1;f<u.text.length&&f<l&&(l=f),i.push({line:u,comment:p,token:c,indent:f,empty:d,single:!1})}h=u.to+1}if(l<1e9)for(let h=a;h<i.length;h++)i[h].indent<i[h].line.text.length&&(i[h].indent=l);i.length==a+1&&(i[a].single=!0)}if(n!=2&&i.some(r=>r.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:a,token:l,indent:c,empty:h,single:u}of i)(u||!h)&&r.push({from:a.from+c,insert:l+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:a,token:l}of i)if(a>=0){let c=o.from+a,h=c+l.length;o.text[h-o.from]==" "&&h++,r.push({from:c,to:h})}return{changes:r}}return null}const na=zt.define(),Qs=zt.define(),C0=Z.define(),bf=Z.define({combine(n){return yt(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),Ba=Te.define({create(){return $t.empty},update(n,e){let t=e.state.facet(bf),i=e.annotation(na);if(i){let l=_e.fromTransaction(e,i.selection),c=i.side,h=c==0?n.undone:n.done;return l?h=Ys(h,h.length,t.minDepth,l):h=vf(h,e.startState.selection),new $t(c==0?i.rest:h,c==0?h:i.rest)}let s=e.annotation(Qs);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(Pe.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=_e.fromTransaction(e),o=e.annotation(Pe.time),a=e.annotation(Pe.userEvent);return r?n=n.addChanges(r,o,a,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new $t(n.done.map(_e.fromJSON),n.undone.map(_e.fromJSON))}});function T0(n={}){return[Ba,bf.of(n),K.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Ia:e.inputType=="historyRedo"?js:null;return i?(e.preventDefault(),i(t)):!1}})]}function vr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(Ba,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}const Ia=vr(0,!1),js=vr(1,!1),R0=vr(0,!0),$0=vr(1,!0);function Sf(n){return function(e){let t=e.field(Ba,!1);if(!t)return 0;let i=n==0?t.done:t.undone;return i.length-(i.length&&!i[0].changes?1:0)}}const Qc=Sf(0),Pc=Sf(1);class _e{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new _e(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new _e(e.changes&&Re.fromJSON(e.changes),[],e.mapped&&Zt.fromJSON(e.mapped),e.startSelection&&A.fromJSON(e.startSelection),e.selectionsAfter.map(A.fromJSON))}static fromTransaction(e,t){let i=ht;for(let s of e.startState.facet(C0)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new _e(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,ht)}static selection(e){return new _e(void 0,ht,void 0,void 0,e)}}function Ys(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function K0(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,a)=>{for(let l=0;l<t.length;){let c=t[l++],h=t[l++];a>=c&&o<=h&&(i=!0)}}),i}function Z0(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function xf(n,e){return n.length?e.length?n.concat(e):n:e}const ht=[],M0=200;function vf(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-M0));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),Ys(n,n.length-1,1e9,t.setSelAfter(i)))}else return[_e.selection([e])]}function E0(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function to(n,e){if(!n.length)return n;let t=n.length,i=ht;for(;t;){let s=U0(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[_e.selection(i)]:ht}function U0(n,e,t){let i=xf(n.selectionsAfter.length?n.selectionsAfter.map(a=>a.map(e)):ht,t);if(!n.changes)return _e.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new _e(s,Y.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}const F0=/^(input\.type|delete)($|\.)/;class $t{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new $t(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!i||F0.test(i))&&(!a.selectionsAfter.length&&t-this.prevTime<s.newGroupDelay&&s.joinToEvent(r,K0(a.changes,e.changes))||i=="input.type.compose")?o=Ys(o,o.length-1,s.minDepth,new _e(e.changes.compose(a.changes),xf(Y.mapEffects(e.effects,a.changes),a.effects),a.mapped,a.startSelection,ht)):o=Ys(o,o.length,s.minDepth,e),new $t(o,ht,t,i)}addSelection(e,t,i,s){let r=this.done.length?this.done[this.done.length-1].selectionsAfter:ht;return r.length>0&&t-this.prevTime<s&&i==this.prevUserEvent&&i&&/^select($|\.)/.test(i)&&Z0(r[r.length-1],e)?this:new $t(vf(this.done,e),this.undone,t,i)}addMapping(e){return new $t(to(this.done,e),to(this.undone,e),this.prevTime,this.prevUserEvent)}pop(e,t,i){let s=e==0?this.done:this.undone;if(s.length==0)return null;let r=s[s.length-1],o=r.selectionsAfter[0]||(r.startSelection?r.startSelection.map(r.changes.invertedDesc,1):t.selection);if(i&&r.selectionsAfter.length)return t.update({selection:r.selectionsAfter[r.selectionsAfter.length-1],annotations:na.of({side:e,rest:E0(s),selection:o}),userEvent:e==0?"select.undo":"select.redo",scrollIntoView:!0});if(r.changes){let a=s.length==1?ht:s.slice(0,s.length-1);return r.mapped&&(a=to(a,r.mapped)),t.update({changes:r.changes,selection:r.startSelection,effects:r.effects,annotations:na.of({side:e,rest:a,selection:o}),filter:!1,userEvent:e==0?"undo":"redo",scrollIntoView:!0})}else return null}}$t.empty=new $t(ht,ht);const D0=[{key:"Mod-z",run:Ia,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:js,preventDefault:!0},{linux:"Ctrl-Shift-z",run:js,preventDefault:!0},{key:"Mod-u",run:R0,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:$0,preventDefault:!0}];function Ji(n,e){return A.create(n.ranges.map(e),n.mainIndex)}function At(n,e){return n.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function bt({state:n,dispatch:e},t){let i=Ji(n.selection,t);return i.eq(n.selection,!0)?!1:(e(At(n,i)),!0)}function wr(n,e){return A.cursor(e?n.to:n.from)}function wf(n,e){return bt(n,t=>t.empty?n.moveByChar(t,e):wr(t,e))}function Be(n){return n.textDirectionAt(n.state.selection.main.head)==fe.LTR}const kf=n=>wf(n,!Be(n)),Qf=n=>wf(n,Be(n));function Pf(n,e){return bt(n,t=>t.empty?n.moveByGroup(t,e):wr(t,e))}const L0=n=>Pf(n,!Be(n)),X0=n=>Pf(n,Be(n));function B0(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function kr(n,e,t){let i=Ce(n).resolveInner(e.head),s=t?_.closedBy:_.openedBy;for(let l=e.head;;){let c=t?i.childAfter(l):i.childBefore(l);if(!c)break;B0(n,c,s)?i=c:l=t?c.to:c.from}let r=i.type.prop(s),o,a;return r&&(o=t?Rt(n,i.from,1):Rt(n,i.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?i.to:i.from,A.cursor(a,t?-1:1)}const I0=n=>bt(n,e=>kr(n.state,e,!Be(n))),W0=n=>bt(n,e=>kr(n.state,e,Be(n)));function Cf(n,e){return bt(n,t=>{if(!t.empty)return wr(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const Tf=n=>Cf(n,!1),Rf=n=>Cf(n,!0);function $f(n){let e=n.scrollDOM.clientHeight<n.scrollDOM.scrollHeight-2,t=0,i=0,s;if(e){for(let r of n.state.facet(K.scrollMargins)){let o=r(n);o?.top&&(t=Math.max(o?.top,t)),o?.bottom&&(i=Math.max(o?.bottom,i))}s=n.scrollDOM.clientHeight-t-i}else s=(n.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:t,marginBottom:i,selfScroll:e,height:Math.max(n.defaultLineHeight,s-5)}}function Kf(n,e){let t=$f(n),{state:i}=n,s=Ji(i.selection,o=>o.empty?n.moveVertically(o,e,t.height):wr(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),a=n.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,c=a.bottom-t.marginBottom;o&&o.top>l&&o.bottom<c&&(r=K.scrollIntoView(s.main.head,{y:"start",yMargin:o.top-l}))}return n.dispatch(At(i,s),{effects:r}),!0}const Cc=n=>Kf(n,!1),sa=n=>Kf(n,!0);function ai(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=A.cursor(i.from+r))}return s}const q0=n=>bt(n,e=>ai(n,e,!0)),z0=n=>bt(n,e=>ai(n,e,!1)),V0=n=>bt(n,e=>ai(n,e,!Be(n))),j0=n=>bt(n,e=>ai(n,e,Be(n))),Y0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).from,1)),N0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).to,-1));function H0(n,e,t){let i=!1,s=Ji(n.selection,r=>{let o=Rt(n,r.head,-1)||Rt(n,r.head,1)||r.head>0&&Rt(n,r.head-1,1)||r.head<n.doc.length&&Rt(n,r.head+1,-1);if(!o||!o.end)return r;i=!0;let a=o.start.from==r.head?o.end.to:o.end.from;return A.cursor(a)});return i?(e(At(n,s)),!0):!1}const G0=({state:n,dispatch:e})=>H0(n,e);function ft(n,e,t){let i=Ji(n.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=A.range(s.head,s.anchor));let r=t(s);return A.range(s.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(At(n.state,i)),!0)}function Zf(n,e){return ft(n,e,t=>n.moveByChar(t,e))}const Mf=n=>Zf(n,!Be(n)),Ef=n=>Zf(n,Be(n));function Uf(n,e){return ft(n,e,t=>n.moveByGroup(t,e))}const _0=n=>Uf(n,!Be(n)),J0=n=>Uf(n,Be(n)),ey=n=>{let e=!Be(n);return ft(n,e,t=>kr(n.state,t,e))},ty=n=>{let e=Be(n);return ft(n,e,t=>kr(n.state,t,e))};function Ff(n,e){return ft(n,e,t=>n.moveVertically(t,e))}const Df=n=>Ff(n,!1),Lf=n=>Ff(n,!0);function Xf(n,e){return ft(n,e,t=>n.moveVertically(t,e,$f(n).height))}const Tc=n=>Xf(n,!1),Rc=n=>Xf(n,!0),iy=n=>ft(n,!0,e=>ai(n,e,!0)),ny=n=>ft(n,!1,e=>ai(n,e,!1)),sy=n=>{let e=!Be(n);return ft(n,e,t=>ai(n,t,e))},ry=n=>{let e=Be(n);return ft(n,e,t=>ai(n,t,e))},oy=n=>ft(n,!1,e=>A.cursor(n.lineBlockAt(e.head).from)),ay=n=>ft(n,!0,e=>A.cursor(n.lineBlockAt(e.head).to)),$c=({state:n,dispatch:e})=>(e(At(n,{anchor:0})),!0),Kc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.doc.length})),!0),Zc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:0})),!0),Mc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),ly=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),cy=({state:n,dispatch:e})=>{let t=Qr(n).map(({from:i,to:s})=>A.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:A.create(t),userEvent:"select"})),!0},hy=({state:n,dispatch:e})=>{let t=Ji(n.selection,i=>{let s=Ce(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:a}=o;if((a.from<i.from&&a.to>=i.to||a.to>i.to&&a.from<=i.from)&&o.next)return A.range(a.to,a.from)}return i});return t.eq(n.selection)?!1:(e(At(n,t)),!0)};function Bf(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to<n.state.doc.length:o.from>0)for(let a=r;;){let l=n.moveVertically(a,e);if(l.head<o.from||l.head>o.to){s.some(c=>c.head==l.head)||s.push(l);break}else{if(l.head==a.head)break;a=l}}}return s.length==i.ranges.length?!1:(n.dispatch(At(t,A.create(s,s.length-1))),!0)}const uy=n=>Bf(n,!1),fy=n=>Bf(n,!0),dy=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=A.create([t.main]):t.main.empty||(i=A.create([A.cursor(t.main.head)])),i?(e(At(n,i)),!0):!1};function In(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:a}=r;if(o==a){let l=e(r);l<o?(t="delete.backward",l=us(n,l,!1)):l>o&&(t="delete.forward",l=us(n,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=us(n,o,!1),a=us(n,a,!0);return o==a?{range:r}:{changes:{from:o,to:a},range:A.cursor(o,o<r.head?-1:1)}});return s.changes.empty?!1:(n.dispatch(i.update(s,{scrollIntoView:!0,userEvent:t,effects:t=="delete.selection"?K.announce.of(i.phrase("Selection deleted")):void 0})),!0)}function us(n,e,t){if(n instanceof K)for(let i of n.state.facet(K.atomicRanges).map(s=>s(n)))i.between(e,e,(s,r)=>{s<e&&r>e&&(e=t?r:s)});return e}const If=(n,e,t)=>In(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),a,l;if(t&&!e&&s>o.from&&s<o.from+200&&!/[^ \t]/.test(a=o.text.slice(0,s-o.from))){if(a[a.length-1]==" ")return s-1;let c=_i(a,r.tabSize),h=c%qs(r)||qs(r);for(let u=0;u<h&&a[a.length-1-u]==" ";u++)s--;l=s}else l=Ze(o.text,s-o.from,e,e)+o.from,l==s&&o.number!=(e?r.doc.lines:1)?l+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(o.text.slice(l-o.from,s-o.from))&&(l=Ze(o.text,l-o.from,!1,!1)+o.from);return l}),ra=n=>If(n,!1,!0),Wf=n=>If(n,!0,!1),qf=(n,e)=>In(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let a=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let l=Ze(r.text,i-r.from,e)+r.from,c=r.text.slice(Math.min(i,l)-r.from,Math.max(i,l)-r.from),h=o(c);if(a!=null&&h!=a)break;(c!=" "||i!=t.head)&&(a=h),i=l}return i}),zf=n=>qf(n,!1),py=n=>qf(n,!0),my=n=>In(n,e=>{let t=n.lineBlockAt(e.head).to;return e.head<t?t:Math.min(n.state.doc.length,e.head+1)}),gy=n=>In(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),Oy=n=>In(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head<t?t:Math.min(n.state.doc.length,e.head+1)}),yy=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:se.of(["",""])},range:A.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},Ay=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:Ze(r.text,s-r.from,!1)+r.from,a=s==r.to?s+1:Ze(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:a,insert:n.doc.slice(s,a).append(n.doc.slice(o,s))},range:A.cursor(a)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Qr(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function Vf(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of Qr(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),a=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let l of r.ranges)s.push(A.range(Math.min(n.doc.length,l.anchor+a),Math.min(n.doc.length,l.head+a)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let l of r.ranges)s.push(A.range(l.anchor-a,l.head-a))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:A.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const by=({state:n,dispatch:e})=>Vf(n,e,!1),Sy=({state:n,dispatch:e})=>Vf(n,e,!0);function jf(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of Qr(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const xy=({state:n,dispatch:e})=>jf(n,e,!1),vy=({state:n,dispatch:e})=>jf(n,e,!0),wy=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(Qr(e).map(({from:s,to:r})=>(s>0?s--:r<e.doc.length&&r++,{from:s,to:r}))),i=Ji(e.selection,s=>{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),a=n.coordsAtPos(s.head,s.assoc||1);a&&(r=o.bottom+n.documentTop-a.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function ky(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Ce(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(_.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}const Ec=Yf(!1),Qy=Yf(!0);function Yf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,a=e.doc.lineAt(r),l=!n&&r==o&&ky(e,r);n&&(r=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Sr(e,{simulateBreak:r,simulateDoubleBreak:!!l}),h=Fa(c,r);for(h==null&&(h=_i(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));o<a.to&&/\s/.test(a.text[o-a.from]);)o++;l?{from:r,to:o}=l:r>a.from&&r<a.from+100&&!/\S/.test(a.text.slice(0,r))&&(r=a.from);let u=["",Tn(e,h)];return l&&u.push(Tn(e,c.lineIndent(a.from,-1))),{changes:{from:r,to:o,insert:se.of(u)},range:A.cursor(r+1+u[1].length)}});return t(e.update(i,{scrollIntoView:!0,userEvent:"input"})),!0}}function Wa(n,e){let t=-1;return n.changeByRange(i=>{let s=[];for(let o=i.from;o<=i.to;){let a=n.doc.lineAt(o);a.number>t&&(i.empty||i.to>a.from)&&(e(a,s,i),t=a.number),o=a.to+1}let r=n.changes(s);return{changes:s,range:A.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}const Py=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Sr(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=Wa(n,(r,o,a)=>{let l=Fa(i,r.from);if(l==null)return;/\S/.test(r.text)||(l=0);let c=/^\s*/.exec(r.text)[0],h=Tn(n,l);(c!=h||a.from<r.from+c.length)&&(t[r.from]=l,o.push({from:r.from,to:r.from+c.length,insert:h}))});return s.changes.empty||e(n.update(s,{userEvent:"indent"})),!0},Nf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Wa(n,(t,i)=>{i.push({from:t.from,insert:n.facet(br)})}),{userEvent:"input.indent"})),!0),Hf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Wa(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=_i(s,n.tabSize),o=0,a=Tn(n,Math.max(0,r-qs(n)));for(;o<s.length&&o<a.length&&s.charCodeAt(o)==a.charCodeAt(o);)o++;i.push({from:t.from+o,to:t.from+s.length,insert:a.slice(o)})}),{userEvent:"delete.dedent"})),!0),Cy=n=>(n.setTabFocusMode(),!0),Ty=[{key:"Ctrl-b",run:kf,shift:Mf,preventDefault:!0},{key:"Ctrl-f",run:Qf,shift:Ef},{key:"Ctrl-p",run:Tf,shift:Df},{key:"Ctrl-n",run:Rf,shift:Lf},{key:"Ctrl-a",run:Y0,shift:oy},{key:"Ctrl-e",run:N0,shift:ay},{key:"Ctrl-d",run:Wf},{key:"Ctrl-h",run:ra},{key:"Ctrl-k",run:my},{key:"Ctrl-Alt-h",run:zf},{key:"Ctrl-o",run:yy},{key:"Ctrl-t",run:Ay},{key:"Ctrl-v",run:sa}],Ry=[{key:"ArrowLeft",run:kf,shift:Mf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:L0,shift:_0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:V0,shift:sy,preventDefault:!0},{key:"ArrowRight",run:Qf,shift:Ef,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:X0,shift:J0,preventDefault:!0},{mac:"Cmd-ArrowRight",run:j0,shift:ry,preventDefault:!0},{key:"ArrowUp",run:Tf,shift:Df,preventDefault:!0},{mac:"Cmd-ArrowUp",run:$c,shift:Zc},{mac:"Ctrl-ArrowUp",run:Cc,shift:Tc},{key:"ArrowDown",run:Rf,shift:Lf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Kc,shift:Mc},{mac:"Ctrl-ArrowDown",run:sa,shift:Rc},{key:"PageUp",run:Cc,shift:Tc},{key:"PageDown",run:sa,shift:Rc},{key:"Home",run:z0,shift:ny,preventDefault:!0},{key:"Mod-Home",run:$c,shift:Zc},{key:"End",run:q0,shift:iy,preventDefault:!0},{key:"Mod-End",run:Kc,shift:Mc},{key:"Enter",run:Ec,shift:Ec},{key:"Mod-a",run:ly},{key:"Backspace",run:ra,shift:ra,preventDefault:!0},{key:"Delete",run:Wf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:zf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:py,preventDefault:!0},{mac:"Mod-Backspace",run:gy,preventDefault:!0},{mac:"Mod-Delete",run:Oy,preventDefault:!0}].concat(Ty.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),$y=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:I0,shift:ey},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:W0,shift:ty},{key:"Alt-ArrowUp",run:by},{key:"Shift-Alt-ArrowUp",run:xy},{key:"Alt-ArrowDown",run:Sy},{key:"Shift-Alt-ArrowDown",run:vy},{key:"Mod-Alt-ArrowUp",run:uy},{key:"Mod-Alt-ArrowDown",run:fy},{key:"Escape",run:dy},{key:"Mod-Enter",run:Qy},{key:"Alt-l",mac:"Ctrl-l",run:cy},{key:"Mod-i",run:hy,preventDefault:!0},{key:"Mod-[",run:Hf},{key:"Mod-]",run:Nf},{key:"Mod-Alt-\\",run:Py},{key:"Shift-Mod-k",run:wy},{key:"Shift-Mod-\\",run:G0},{key:"Mod-/",run:S0},{key:"Alt-A",run:v0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Cy}].concat(Ry),Ky={key:"Tab",run:Nf,shift:Hf};class Gf{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=Ce(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(Jf(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}}function Uc(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Zy(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;r<s.length;r++)t[s[r]]=!0}let i=Uc(e)+Uc(t)+"*$";return[new RegExp("^"+i),new RegExp(i)]}function _f(n){let e=n.map(s=>typeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Zy(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function My(n,e){return t=>{for(let i=Ce(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}let Fc=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function yi(n){return n.selection.main.from}function Jf(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}const qa=zt.define();function Ey(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(a=>{if(a!=s&&t!=i&&n.sliceDoc(a.from+r,a.from+o)!=n.sliceDoc(t,i))return{range:a};let l=n.toText(e);return{changes:{from:a.from+r,to:i==s.from?a.to:a.from+o,insert:l},range:A.cursor(a.from+r+l.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const Dc=new WeakMap;function Uy(n){if(!Array.isArray(n))return n;let e=Dc.get(n);return e||Dc.set(n,e=_f(n)),e}const Ns=Y.define(),Rn=Y.define();class Fy{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t<e.length;){let i=Ne(e,t),s=Qt(i);this.chars.push(i);let r=e.slice(t,t+s),o=r.toUpperCase();this.folded.push(Ne(o==r?r.toLowerCase():o,0)),t+=s}this.astral=e.length!=this.chars.length}ret(e,t){return this.score=e,this.matched=t,this}match(e){if(this.pattern.length==0)return this.ret(-100,[]);if(e.length<this.pattern.length)return null;let{chars:t,folded:i,any:s,precise:r,byWord:o}=this;if(t.length==1){let x=Ne(e,0),b=Qt(x),C=b==e.length?0:-100;if(x!=t[0])if(x==i[0])C+=-200;else return null;return this.ret(C,[0,b])}let a=e.indexOf(this.pattern);if(a==0)return this.ret(e.length==this.pattern.length?0:-100,[0,this.pattern.length]);let l=t.length,c=0;if(a<0){for(let x=0,b=Math.min(e.length,200);x<b&&c<l;){let C=Ne(e,x);(C==t[c]||C==i[c])&&(s[c++]=x),x+=Qt(C)}if(c<l)return null}let h=0,u=0,f=!1,d=0,p=-1,m=-1,g=/[a-z]/.test(e),y=!0;for(let x=0,b=Math.min(e.length,200),C=0;x<b&&u<l;){let Q=Ne(e,x);a<0&&(h<l&&Q==t[h]&&(r[h++]=x),d<l&&(Q==t[d]||Q==i[d]?(d==0&&(p=x),m=x+1,d++):d=0));let P,w=Q<255?Q>=48&&Q<=57||Q>=97&&Q<=122?2:Q>=65&&Q<=90?1:0:(P=ma(Q))!=P.toLowerCase()?1:P!=P.toUpperCase()?2:0;(!x||w==1&&g||C==0&&w!=0)&&(t[u]==Q||i[u]==Q&&(f=!0)?o[u++]=x:o.length&&(y=!1)),C=w,x+=Qt(Q)}return u==l&&o[0]==0&&y?this.result(-100+(f?-200:0),o,e):d==l&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):a>-1?this.ret(-700-e.length,[a,a+this.pattern.length]):d==l?this.ret(-900-e.length,[p,m]):u==l?this.result(-100+(f?-200:0)+-700+(y?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let a=o+(this.astral?Qt(Ne(i,o)):1);r&&s[r-1]==o?s[r-1]=a:(s[r++]=o,s[r++]=a)}return this.ret(e-i.length,s)}}class Dy{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length<this.pattern.length)return null;let t=e.slice(0,this.pattern.length),i=t==this.pattern?0:t.toLowerCase()==this.folded?-200:null;return i==null?null:(this.matched=[0,t.length],this.score=i+(e.length==this.pattern.length?0:-100),this)}}const Ke=Z.define({combine(n){return yt(n,{activateOnTyping:!0,activateOnCompletion:()=>!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:Ly,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>Lc(e(i),t(i)),optionClass:(e,t)=>i=>Lc(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function Lc(n,e){return n?e?n+" "+e:n:e}function Ly(n,e,t,i,s,r){let o=n.textDirection==fe.RTL,a=o,l=!1,c="top",h,u,f=e.left-s.left,d=s.right-e.right,p=i.right-i.left,m=i.bottom-i.top;if(a&&f<Math.min(p,d)?a=!1:!a&&d<Math.min(p,f)&&(a=!0),p<=(a?f:d))h=Math.max(s.top,Math.min(t.top,s.bottom-m))-e.top,u=Math.min(400,a?f:d);else{l=!0,u=Math.min(400,(o?e.right:s.right-e.left)-30);let x=s.bottom-e.bottom;x>=m||x>e.top?h=t.bottom-e.top:(c="bottom",h=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,y=(e.right-e.left)/r.offsetWidth;return{style:`${c}: ${h/g}px; max-width: ${u/y}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":a?"left":"right")}}const za=Y.define();function Xy(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let a=t.displayLabel||t.label,l=0;for(let c=0;c<r.length;){let h=r[c++],u=r[c++];h>l&&o.appendChild(document.createTextNode(a.slice(l,h)));let f=o.appendChild(document.createElement("span"));f.appendChild(document.createTextNode(a.slice(h,u))),f.className="cm-completionMatchedText",l=u}return l<a.length&&o.appendChild(document.createTextNode(a.slice(l))),o},position:50},{render(t){if(!t.detail)return null;let i=document.createElement("span");return i.className="cm-completionDetail",i.textContent=t.detail,i},position:80}),e.sort((t,i)=>t.position-i.position).map(t=>t.render)}function io(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.ceil((n-e)/t);return{from:n-i*t,to:n-(i-1)*t}}class By{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,a=e.state.facet(Ke);this.optionContent=Xy(a),this.optionClass=a.optionClass,this.tooltipClass=a.tooltipClass,this.range=io(r.length,o,a.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=e.state.field(t).open;for(let h=l.target,u;h&&h!=this.dom;h=h.parentNode)if(h.nodeName=="LI"&&(u=/-(\d+)$/.exec(h.id))&&+u[1]<c.length){this.applyCompletion(e,c[+u[1]]),l.preventDefault();return}if(l.target==this.list){let h=this.list.classList.contains("cm-completionListIncompleteTop")&&l.clientY<this.list.firstChild.getBoundingClientRect().top?this.range.from-1:this.list.classList.contains("cm-completionListIncompleteBottom")&&l.clientY>this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;h!=null&&(e.dispatch({effects:za.of(h)}),l.preventDefault())}}),this.dom.addEventListener("focusout",l=>{let c=e.state.field(this.stateField,!1);c&&c.tooltip&&e.state.facet(Ke).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:Rn.of(null)})}),this.showOptions(r,s.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:a}=i.open;(!s.open||s.open.options!=r)&&(this.range=io(r.length,o,e.state.facet(Ke).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),a!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected<this.range.from||t.selected>=this.range.to)&&(this.range=io(t.options.length,t.selected,this.view.state.facet(Ke).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(a=>{a&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(a,s)}).catch(a=>ze(this.view.state,a,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&Wy(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom<Math.max(r.top,t.top)+10?null:this.view.state.facet(Ke).positionInfo(this.view,t,s,i,r,this.dom)}placeInfo(e){this.info&&(e?(e.style&&(this.info.style.cssText=e.style),this.info.className="cm-tooltip cm-completionInfo "+(e.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(e,t,i){const s=document.createElement("ul");s.id=t,s.setAttribute("role","listbox"),s.setAttribute("aria-expanded","true"),s.setAttribute("aria-label",this.view.state.phrase("Completions")),s.addEventListener("mousedown",o=>{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;o<i.to;o++){let{completion:a,match:l}=e[o],{section:c}=a;if(c){let f=typeof c=="string"?c:c.name;if(f!=r&&(o>i.from||i.from==0))if(r=f,typeof c!="string"&&c.header)s.appendChild(c.header(c));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=f}}const h=s.appendChild(document.createElement("li"));h.id=t+"-"+o,h.setAttribute("role","option");let u=this.optionClass(a);u&&(h.className=u);for(let f of this.optionContent){let d=f(a,this.view.state,this.view,l);d&&h.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.to<e.length&&s.classList.add("cm-completionListIncompleteBottom"),s}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function Iy(n,e){return t=>new By(t,n,e)}function Wy(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.top<t.top?n.scrollTop-=(t.top-i.top)/s:i.bottom>t.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function Xc(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function qy(n,e){let t=[],i=null,s=null,r=h=>{t.push(h);let{section:u}=h.completion;if(u){i||(i=[]);let f=typeof u=="string"?u:u.name;i.some(d=>d.name==f)||i.push(typeof u=="string"?{name:f}:u)}},o=e.facet(Ke);for(let h of n)if(h.hasResult()){let u=h.result.getMatch;if(h.result.filter===!1)for(let f of h.result.options)r(new Fc(f,h.source,u?u(f):[],1e9-t.length));else{let f=e.sliceDoc(h.from,h.to),d,p=o.filterStrict?new Dy(f):new Fy(f);for(let m of h.result.options)if(d=p.match(m.label)){let g=m.displayLabel?u?u(m,d.matched):[]:d.matched,y=d.score+(m.boost||0);if(r(new Fc(m,h.source,g,y)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:x}=m.section;s||(s=Object.create(null)),s[x]=Math.max(y,s[x]||-1e9)}}}}if(i){let h=Object.create(null),u=0,f=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.name<p.name?-1:1);for(let d of i.sort(f))u-=1e5,h[d.name]=u;for(let d of t){let{section:p}=d.completion;p&&(d.score+=h[typeof p=="string"?p:p.name])}}let a=[],l=null,c=o.compareCompletions;for(let h of t.sort((u,f)=>f.score-u.score||c(u.completion,f.completion))){let u=h.completion;!l||l.label!=u.label||l.detail!=u.detail||l.type!=null&&u.type!=null&&l.type!=u.type||l.apply!=u.apply||l.boost!=u.boost?a.push(h):Xc(h.completion)>Xc(l)&&(a[a.length-1]=h),l=h.completion}return a}class Ki{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new Ki(this.options,Bc(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(c=>c.isPending))return s.setDisabled();let a=qy(e,t);if(!a.length)return s&&e.some(c=>c.isPending)?s.setDisabled():null;let l=t.facet(Ke).selectOnOpen?0:-1;if(s&&s.selected!=l&&s.selected!=-1){let c=s.options[s.selected].completion;for(let h=0;h<a.length;h++)if(a[h].completion==c){l=h;break}}return new Ki(a,Bc(i,l),{pos:e.reduce((c,h)=>h.hasResult()?Math.min(c,h.from):c,1e8),create:Hy,above:r.aboveCursor},s?s.timestamp:Date.now(),l,!1)}map(e){return new Ki(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Ki(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class Hs{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Hs(Yy,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(Ke),r=(i.override||t.languageDataAt("autocomplete",yi(t)).map(Uy)).map(l=>(this.active.find(h=>h.source==l)||new ut(l,this.active.some(h=>h.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((l,c)=>l==this.active[c])&&(r=this.active);let o=this.open,a=e.effects.some(l=>l.is(Va));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!zy(r,this.active)||a?o=Ki.build(r,t,this.id,o,i,a):o&&o.disabled&&!r.some(l=>l.isPending)&&(o=null),!o&&r.every(l=>!l.isPending)&&r.some(l=>l.hasResult())&&(r=r.map(l=>l.hasResult()?new ut(l.source,0):l));for(let l of e.effects)l.is(za)&&(o=o&&o.setSelected(l.value,this.id));return r==this.active&&o==this.open?this:new Hs(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Vy:jy}}function zy(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t<n.length&&!n[t].hasResult();)t++;for(;i<e.length&&!e[i].hasResult();)i++;let s=t==n.length,r=i==e.length;if(s||r)return s==r;if(n[t++].result!=e[i++].result)return!1}}const Vy={"aria-autocomplete":"list"},jy={};function Bc(n,e){let t={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":n};return e>-1&&(t["aria-activedescendant"]=n+"-"+e),t}const Yy=[];function ed(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(qa);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}class ut{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=ed(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new ut(s.source,0)),i&4&&s.state==0&&(s=new ut(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(Ns))s=new ut(s.source,1,r.value);else if(r.is(Rn))s=new ut(s.source,0);else if(r.is(Va))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(yi(e.state))}}class Fi extends ut{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),a=yi(e.state);if(a>o||!s||t&2&&(yi(e.startState)==this.from||a<this.limit))return new ut(this.source,t&4?1:0);let l=e.changes.mapPos(this.limit);return Ny(s.validFor,e.state,r,o)?new Fi(this.source,this.explicit,l,s,r,o):s.update&&(s=s.update(s,r,o,new Gf(e.state,a,!1)))?new Fi(this.source,this.explicit,l,s,s.from,(i=s.to)!==null&&i!==void 0?i:yi(e.state)):new ut(this.source,1,this.explicit)}map(e){if(e.empty)return this;let t=this.result.map?this.result.map(this.result,e):this.result;return t?new Fi(this.source,this.explicit,e.mapPos(this.limit),t,e.mapPos(this.from),e.mapPos(this.to,1)):new ut(this.source,0)}touches(e){return e.changes.touchesRange(this.from,this.to)}}function Ny(n,e,t,i){if(!n)return!1;let s=e.sliceDoc(t,i);return typeof n=="function"?n(s,t,i,e):Jf(n,!0).test(s)}const Va=Y.define({map(n,e){return n.map(t=>t.map(e))}}),He=Te.define({create(){return Hs.start()},update(n,e){return n.update(e)},provide:n=>[yr.from(n,e=>e.tooltip),K.contentAttributes.from(n,e=>e.attrs)]});function ja(n,e){const t=e.completion.apply||e.completion.label;let i=n.state.field(He).active.find(s=>s.source==e.source);return i instanceof Fi?(typeof t=="string"?n.dispatch({...Ey(n.state,t,i.from,i.to),annotations:qa.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}const Hy=Iy(He,ja);function fs(n,e="option"){return t=>{let i=t.state.field(He,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp<t.state.facet(Ke).interactionDelay)return!1;let s=1,r;e=="page"&&(r=Xu(t,i.open.tooltip))&&(s=Math.max(2,Math.floor(r.dom.offsetHeight/r.dom.querySelector("li").offsetHeight)-1));let{length:o}=i.open.options,a=i.open.selected>-1?i.open.selected+s*(n?1:-1):n?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:za.of(a)}),!0}}const Gy=n=>{let e=n.state.field(He,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<n.state.facet(Ke).interactionDelay?!1:ja(n,e.open.options[e.open.selected])},no=n=>n.state.field(He,!1)?(n.dispatch({effects:Ns.of(!0)}),!0):!1,_y=n=>{let e=n.state.field(He,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Rn.of(null)}),!0)};class Jy{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const eA=50,tA=1e3,iA=xe.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(He).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(He),t=n.state.facet(Ke);if(!n.selectionSet&&!n.docChanged&&n.startState.field(He)==e)return;let i=n.transactions.some(r=>{let o=ed(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;r<this.running.length;r++){let o=this.running[r];if(i||o.context.abortOnDocChange&&n.docChanged||o.updates.length+n.transactions.length>eA&&Date.now()-o.time>tA){for(let a of o.context.abortListeners)try{a()}catch(l){ze(this.view.state,l)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(Ns)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(He);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=yi(e),i=new Gf(e,t,n.explicit,this.view),s=new Jy(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:Rn.of(null)}),ze(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(Ke),i=this.view.state.field(He);for(let s=0;s<this.running.length;s++){let r=this.running[s];if(r.done===void 0)continue;if(this.running.splice(s--,1),r.done){let a=yi(r.updates.length?r.updates[0].startState:this.view.state),l=Math.min(a,r.done.from+(r.active.explicit?0:1)),c=new Fi(r.active.source,r.active.explicit,l,r.done,r.done.from,(n=r.done.to)!==null&&n!==void 0?n:a);for(let h of r.updates)c=c.update(h,t);if(c.hasResult()){e.push(c);continue}}let o=i.active.find(a=>a.source==r.active.source);if(o&&o.isPending)if(r.done==null){let a=new ut(r.active.source,0);for(let l of r.updates)a=a.update(l,t);a.isPending||e.push(a)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:Va.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(He,!1);if(e&&e.tooltip&&this.view.state.facet(Ke).closeOnBlur){let t=e.open&&Xu(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Rn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Ns.of(!1)}),20),this.composing=0}}}),nA=typeof navigator=="object"&&/Win/.test(navigator.platform),sA=oi.highest(K.domEventHandlers({keydown(n,e){let t=e.state.field(He,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(nA&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&ja(e,i),!1}})),td=K.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class rA{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}}class Ya{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,De.TrackDel),i=e.mapPos(this.to,1,De.TrackDel);return t==null||i==null?null:new Ya(this.field,t,i)}}class Na{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let l of this.lines){if(i.length){let c=o,h=/^\t*/.exec(l)[0].length;for(let u=0;u<h;u++)c+=e.facet(br);s.push(t+c.length-h),l=c+l.slice(h)}i.push(l),t+=l.length+1}let a=this.fieldPositions.map(l=>new Ya(l.field,s[l.line]+l.from,s[l.line]+l.to));return{text:i,ranges:a}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let a=r[1]?+r[1]:null,l=r[2]||r[3]||"",c=-1;a===0&&(a=1e9);let h=l.replace(/\\[{}]/g,u=>u[1]);for(let u=0;u<t.length;u++)(a!=null?t[u].seq==a:h&&t[u].name==h)&&(c=u);if(c<0){let u=0;for(;u<t.length&&(a==null||t[u].seq!=null&&t[u].seq<a);)u++;t.splice(u,0,{seq:a,name:h}),c=u;for(let f of s)f.field>=c&&f.field++}for(let u of s)if(u.line==i.length&&u.from>r.index){let f=r[2]?3+(r[1]||"").length:2;u.from-=f,u.to-=f}s.push(new rA(c,i.length,r.index,r.index+h.length)),o=o.slice(0,r.index)+l+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(a,l,c)=>{for(let h of s)h.line==i.length&&h.from>c&&(h.from--,h.to--);return l}),i.push(o)}return new Na(i,s)}}let oA=I.widget({widget:new class extends Ut{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),aA=I.mark({class:"cm-snippetField"});class en{constructor(e,t){this.ranges=e,this.active=t,this.deco=I.set(e.map(i=>(i.from==i.to?oA:aA).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new en(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const Wn=Y.define({map(n,e){return n&&n.map(e)}}),lA=Y.define(),$n=Te.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Wn))return t.value;if(t.is(lA)&&n)return new en(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>K.decorations.from(n,e=>e?e.deco:I.none)});function Ha(n,e){return A.create(n.filter(t=>t.field==e).map(t=>A.range(t.from,t.to)))}function cA(n){let e=Na.parse(n);return(t,i,s,r)=>{let{text:o,ranges:a}=e.instantiate(t.state,s),{main:l}=t.state.selection,c={changes:{from:s,to:r==l.from?l.to:r,insert:se.of(o)},scrollIntoView:!0,annotations:i?[qa.of(i),Pe.userEvent.of("input.complete")]:void 0};if(a.length&&(c.selection=Ha(a,0)),a.some(h=>h.field>0)){let h=new en(a,0),u=c.effects=[Wn.of(h)];t.state.field($n,!1)===void 0&&u.push(Y.appendConfig.of([$n,pA,mA,td]))}t.dispatch(t.state.update(c))}}function id(n){return({state:e,dispatch:t})=>{let i=e.field($n,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:Ha(i.ranges,s),effects:Wn.of(r?null:new en(i.ranges,s)),scrollIntoView:!0})),!0}}const hA=({state:n,dispatch:e})=>n.field($n,!1)?(e(n.update({effects:Wn.of(null)})),!0):!1,uA=id(1),fA=id(-1),dA=[{key:"Tab",run:uA,shift:fA},{key:"Escape",run:hA}],Ic=Z.define({combine(n){return n.length?n[0]:dA}}),pA=oi.highest(Or.compute([Ic],n=>n.facet(Ic)));function Ye(n,e){return{...e,apply:cA(n)}}const mA=K.domEventHandlers({mousedown(n,e){let t=e.state.field($n,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:Ha(t.ranges,s.field),effects:Wn.of(t.ranges.some(r=>r.field>s.field)?new en(t.ranges,s.field):null),scrollIntoView:!0}),!0)}}),Kn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},mi=Y.define({map(n,e){let t=e.mapPos(n,-1,De.TrackAfter);return t??void 0}}),Ga=new class extends ei{};Ga.startSide=1;Ga.endSide=-1;const nd=Te.define({create(){return H.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(mi)&&(n=n.update({add:[Ga.range(t.value,t.value+1)]}));return n}});function gA(){return[yA,nd]}const so="()[]{}<>«»»«[]{}";function sd(n){for(let e=0;e<so.length;e+=2)if(so.charCodeAt(e)==n)return so.charAt(e+1);return ma(n<128?n:n+1)}function rd(n,e){return n.languageDataAt("closeBrackets",e)[0]||Kn}const OA=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),yA=K.inputHandler.of((n,e,t,i)=>{if((OA?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Qt(Ne(i,0))==1||e!=s.from||t!=s.to)return!1;let r=SA(n.state,i);return r?(n.dispatch(r),!0):!1}),AA=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=rd(n,n.selection.main.head).brackets||Kn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let a=xA(n.doc,o.head);for(let l of i)if(l==a&&Pr(n.doc,o.head)==sd(Ne(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:A.cursor(o.head-l.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},bA=[{key:"Backspace",run:AA}];function SA(n,e){let t=rd(n,n.selection.main.head),i=t.brackets||Kn.brackets;for(let s of i){let r=sd(Ne(s,0));if(e==s)return r==s?kA(n,s,i.indexOf(s+s+s)>-1,t):vA(n,s,r,t.before||Kn.before);if(e==r&&od(n,n.selection.main.from))return wA(n,s,r)}return null}function od(n,e){let t=!1;return n.field(nd).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function Pr(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Qt(Ne(t,0)))}function xA(n,e){let t=n.sliceString(e-2,e);return Qt(Ne(t,0))==t.length?t:t.slice(1)}function vA(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:mi.of(o.to+e.length),range:A.range(o.anchor+e.length,o.head+e.length)};let a=Pr(n.doc,o.head);return!a||/\s/.test(a)||i.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:mi.of(o.head+e.length),range:A.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function wA(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&Pr(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:A.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function kA(n,e,t,i){let s=i.stringPrefixes||Kn.stringPrefixes,r=null,o=n.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:mi.of(a.to+e.length),range:A.range(a.anchor+e.length,a.head+e.length)};let l=a.head,c=Pr(n.doc,l),h;if(c==e){if(Wc(n,l))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(od(n,l)){let f=t&&n.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+f.length,insert:f},range:A.cursor(l+f.length)}}}else{if(t&&n.sliceDoc(l-2*e.length,l)==e+e&&(h=qc(n,l-2*e.length,s))>-1&&Wc(n,h))return{changes:{insert:e+e+e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(n.charCategorizer(l)(c)!=ye.Word&&qc(n,l,s)>-1&&!QA(n,l,e,s))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)}}return{range:r=a}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function Wc(n,e){let t=Ce(n).resolveInner(e+1);return t.parent&&t.from==e}function QA(n,e,t,i){let s=Ce(n).resolveInner(e,-1),r=i.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),l=a.indexOf(t);if(!l||l>-1&&i.indexOf(a.slice(0,l))>-1){let h=s.firstChild;for(;h&&h.from==s.from&&h.to-h.from>t.length+l;){if(n.sliceDoc(h.to-t.length,h.to)==t)return!1;h=h.firstChild}return!0}let c=s.to==e&&s.parent;if(!c)break;s=c}return!1}function qc(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=ye.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=ye.Word)return r}return-1}function PA(n={}){return[sA,He,Ke.of(n),iA,CA,td]}const ad=[{key:"Ctrl-Space",run:no},{mac:"Alt-`",run:no},{mac:"Alt-i",run:no},{key:"Escape",run:_y},{key:"ArrowDown",run:fs(!0)},{key:"ArrowUp",run:fs(!1)},{key:"PageDown",run:fs(!0,"page")},{key:"PageUp",run:fs(!1,"page")},{key:"Enter",run:Gy}],CA=oi.highest(Or.computeN([Ke],n=>n.facet(Ke).defaultKeymap?[ad]:[]));var zc={};class Gs{constructor(e,t,i,s,r,o,a,l,c,h=0,u){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=a,this.bufferBase=l,this.curContext=c,this.lookAhead=h,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new Gs(e,[],t,i,i,0,[],0,s?new Vc(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos<this.pos-25&&this.setLookAhead(this.pos),a=r.dynamicPrecedence(s);if(a&&(this.score+=a),i==0){s<r.minRepeatTerm&&this.reducePos<this.pos&&(this.reducePos=this.pos),this.pushState(r.getGoto(this.state,s,!0),this.reducePos),s<r.minRepeatTerm&&this.storeNode(s,this.reducePos,this.reducePos,o?8:4,!0),this.reduceContext(s,this.reducePos);return}let l=this.stack.length-(i-1)*3-(e&262144?6:0),c=l?this.stack[l-2]:this.p.ranges[0].from;s<r.minRepeatTerm&&c==this.reducePos&&this.reducePos<this.pos&&(this.reducePos=this.pos);let h=this.reducePos-c;h>=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(c==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=h):this.p.lastBigReductionSize<h&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=c,this.p.lastBigReductionSize=h));let u=l?this.stack[l-1]:0,f=this.bufferBase+this.buffer.length-u;if(s<r.minRepeatTerm||e&131072){let d=r.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(s,c,d,f+4,!0)}if(e&262144)this.state=this.stack[l];else{let d=this.stack[l-3];this.state=r.getGoto(d,s,!0)}for(;this.stack.length>l;)this.stack.pop();this.reduceContext(s,c)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let o=this.buffer.length;if(o>0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let a=!1;for(let l=o;l>0&&this.buffer[l-2]>i;l-=4)if(this.buffer[l-1]>=0){a=!0;break}if(a)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let a=o.stateFlag(r,1);!a&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,a?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new Gs(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new TA(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;r<t.length;r+=2)(o=t[r+1])!=this.state&&this.p.parser.hasAction(o,e)&&s.push(t[r],o);if(this.stack.length<120)for(let r=0;s.length<8&&r<t.length;r+=2){let o=t[r+1];s.some((a,l)=>l&1&&a==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s<t.length&&i.length<4;s+=2){let r=t[s+1];if(r==this.state)continue;let o=this.split();o.pushState(r,this.pos),o.storeNode(0,o.pos,o.pos,4,!0),o.shiftContext(t[s],this.pos),o.reducePos=this.pos,o.score-=200,i.push(o)}return i}forceReduce(){let{parser:e}=this.p,t=e.stateSlot(this.state,5);if((t&65536)==0)return!1;if(!e.validAction(this.state,t)){let i=t>>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let a=(o>>19)-r;if(a>1){let l=o&65535,c=this.stack.length-a*3;if(c>=0&&e.getGoto(this.stack[c],l,!1)>=0)return a<<19|65536|l}}else{let a=i(o,r+1);if(a!=null)return a}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t<this.stack.length;t+=3)if(this.stack[t]!=e.stack[t])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(e){return this.p.parser.dialect.flags[e]}shiftContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,e,this,this.p.stream.reset(t)))}reduceContext(e,t){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,e,this,this.p.stream.reset(t)))}emitContext(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-3)&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let e=this.buffer.length-1;(e<0||this.buffer[e]!=-4)&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(e){if(e!=this.curContext.context){let t=new Vc(this.curContext.tracker,e);t.hash!=this.curContext.hash&&this.emitContext(),this.curContext=t}}setLookAhead(e){return e<=this.lookAhead?!1:(this.emitLookAhead(),this.lookAhead=e,!0)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class Vc{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class TA{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}}class _s{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new _s(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new _s(this.stack,this.pos,this.index)}}function dn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i<n.length;){let r=0;for(;;){let o=n.charCodeAt(i++),a=!1;if(o==126){r=65535;break}o>=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),r+=l,a)break;r*=46}t?t[s++]=r:t=new e(r)}return t}class Ps{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const jc=new Ps;class RA{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=jc,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;r<i.from;){if(!s)return null;let o=this.ranges[--s];r-=i.from-o.to,i=o}for(;t<0?r>i.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&e<this.range.to)return e;for(let t of this.ranges)if(t.to>e)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t<this.chunk.length)i=this.pos+e,s=this.chunk.charCodeAt(t);else{let r=this.resolveOffset(e,1);if(r==null)return-1;if(i=r,i>=this.chunk2Pos&&i<this.chunk2Pos+this.chunk2.length)s=this.chunk2.charCodeAt(i-this.chunk2Pos);else{let o=this.rangeIndex,a=this.range;for(;a.to<=i;)a=this.ranges[++o];this.chunk2=this.input.chunk(this.chunk2Pos=i),i+this.chunk2.length>a.to&&(this.chunk2=this.chunk2.slice(0,a.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=e,this.token.end=i}acceptTokenTo(e,t){this.token.value=e,this.token.end=t}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:e,chunkPos:t}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=e,this.chunk2Pos=t,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let e=this.input.chunk(this.pos),t=this.pos+e.length;this.chunk=t>this.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=jc,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;e>=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e<this.chunkPos+this.chunk.length?this.chunkOff=e-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(e,t){if(e>=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}}class Di{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;ld(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}Di.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class oa{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?dn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(ld(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}}oa.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class qn{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function ld(n,e,t,i,s,r){let o=0,a=1<<i,{dialect:l}=t.p.parser;e:for(;(a&n[o])!=0;){let c=n[o+1];for(let d=o+3;d<c;d+=2)if((n[d+1]&a)>0){let p=n[d];if(l.allows(p)&&(e.token.value==-1||e.token.value==p||$A(p,e.token.value,s,r))){e.acceptToken(p);break}}let h=e.next,u=0,f=n[o+2];if(e.next<0&&f>u&&n[c+f*3-3]==65535){o=n[c+f*3-1];continue e}for(;u<f;){let d=u+f>>1,p=c+d+(d<<1),m=n[p],g=n[p+1]||65536;if(h<m)f=d;else if(h>=g)u=d+1;else{o=n[p+2],e.advance();continue e}}break}}function Yc(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function $A(n,e,t,i){let s=Yc(t,i,e);return s<0||Yc(t,i,n)<s}const nt=typeof process<"u"&&zc&&/\bparse\b/.test(zc.LOG);let ro=null;function Nc(n,e,t){let i=n.cursor(be.IncludeAnonymous);for(i.moveTo(e);;)if(!(t<0?i.childBefore(e):i.childAfter(e)))for(;;){if((t<0?i.to<e:i.from>e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class KA{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Nc(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Nc(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(e<this.nextStart)return null;for(;this.fragment&&this.safeTo<=e;)this.nextFragment();if(!this.fragment)return null;for(;;){let t=this.trees.length-1;if(t<0)return this.nextFragment(),null;let i=this.trees[t],s=this.index[t];if(s==i.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let r=i.children[s],o=this.start[t]+i.positions[s];if(o>e)return this.nextStart=o,null;if(r instanceof ke){if(o==e){if(o<this.safeFrom)return null;let a=o+r.length;if(a<=this.safeTo){let l=r.prop(_.lookAhead);if(!l||a+l<this.fragment.to)return r}}this.index[t]++,o+r.length>=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}}class ZA{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Ps)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let c=0;c<r.length;c++){if((1<<c&o)==0)continue;let h=r[c],u=this.tokens[c];if(!(i&&!h.fallback)&&((h.contextual||u.start!=e.pos||u.mask!=o||u.context!=a)&&(this.updateCachedToken(u,h,e),u.mask=o,u.context=a),u.lookAhead>u.end+25&&(l=Math.max(u.lookAhead,l)),u.value!=0)){let f=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!h.extend&&(i=u,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!i&&e.pos==this.stream.end&&(i=new Ps,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Ps,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o<r.specialized.length;o++)if(r.specialized[o]==e.value){let a=r.specializers[o](this.stream.read(e.start,e.end),i);if(a>=0&&i.p.parser.dialect.allows(a>>1)){(a&1)==0?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;r<s;r+=3)if(this.actions[r]==e)return s;return this.actions[s++]=e,this.actions[s++]=t,this.actions[s++]=i,s}addActions(e,t,i,s){let{state:r}=e,{parser:o}=e.p,{data:a}=o;for(let l=0;l<2;l++)for(let c=o.stateSlot(r,l?2:1);;c+=3){if(a[c]==65535)if(a[c+1]==1)c=Dt(a,c+2);else{s==0&&a[c+1]==2&&(s=this.putAction(Dt(a,c+2),t,i,s));break}a[c]==t&&(s=this.putAction(Dt(a,c+1),t,i,s))}return s}}class MA{constructor(e,t,i,s){this.parser=e,this.input=t,this.ranges=s,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new RA(t,s),this.tokens=new ZA(e,this.stream),this.topTerm=e.top[1];let{from:r}=s[0];this.stacks=[Gs.start(this,e.top[0],r)],this.fragments=i.length&&this.stream.end-r>e.bufferLength*4?new KA(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;o<e.length;o++){let a=e[o];for(;;){if(this.tokens.mainToken=null,a.pos>t)i.push(a);else{if(this.advanceStack(a,i,e))continue;{s||(s=[],r=[]),s.push(a);let l=this.tokens.getMainToken(a);r.push(l.value,l.end)}}break}}if(!i.length){let o=s&&FA(s);if(o)return nt&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw nt&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return nt&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((a,l)=>l.score-a.score);i.length>o;)i.pop();i.some(a=>a.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o<i.length-1;o++){let a=i[o];for(let l=o+1;l<i.length;l++){let c=i[l];if(a.sameState(c)||a.buffer.length>500&&c.buffer.length>500)if((a.score-c.score||a.buffer.length-c.buffer.length)>0)i.splice(l--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,a)=>a.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o<i.length;o++)i[o].pos<this.minStackPos&&(this.minStackPos=i[o].pos);return null}stopAt(e){if(this.stoppedAt!=null&&this.stoppedAt<e)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=e}advanceStack(e,t,i){let s=e.pos,{parser:r}=this,o=nt?this.stackID(e)+" -> ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let c=e.curContext&&e.curContext.tracker.strict,h=c?e.curContext.hash:0;for(let u=this.fragments.nodeAt(s);u;){let f=this.parser.nodeSet.types[u.type.id]==u.type?r.getGoto(e.state,u.type.id):-1;if(f>-1&&u.length&&(!c||(u.prop(_.contextHash)||0)==h))return e.useNode(u,f),nt&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(u.type.id)})`),!0;if(!(u instanceof ke)||u.children.length==0||u.positions[0]>0)break;let d=u.children[0];if(d instanceof ke&&u.positions[0]==0)u=d;else break}}let a=r.stateSlot(e.state,4);if(a>0)return e.reduce(a),nt&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(a&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let c=0;c<l.length;){let h=l[c++],u=l[c++],f=l[c++],d=c==l.length||!i,p=d?e:e.split(),m=this.tokens.mainToken;if(p.apply(h,u,m?m.start:p.pos,f),nt&&console.log(o+this.stackID(p)+` (via ${(h&65536)==0?"shift":`reduce of ${r.getName(h&65535)}`} for ${r.getName(u)} @ ${s}${p==e?"":", split"})`),d)return!0;p.pos>s?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return Hc(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o<e.length;o++){let a=e[o],l=t[o<<1],c=t[(o<<1)+1],h=nt?this.stackID(a)+" -> ":"";if(a.deadEnd&&(r||(r=!0,a.restart(),nt&&console.log(h+this.stackID(a)+" (restarted)"),this.advanceFully(a,i))))continue;let u=a.split(),f=h;for(let d=0;d<10&&u.forceReduce()&&(nt&&console.log(f+this.stackID(u)+" (via force-reduce)"),!this.advanceFully(u,i));d++)nt&&(f=this.stackID(u)+" -> ");for(let d of a.recoverByInsert(l))nt&&console.log(h+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>a.pos?(c==a.pos&&(c++,l=0),a.recoverByDelete(l,c),nt&&console.log(h+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),Hc(a,i)):(!s||s.score<u.score)&&(s=u)}return s}stackToTree(e){return e.close(),ke.build({buffer:_s.create(e),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:e.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(e){let t=(ro||(ro=new WeakMap)).get(e);return t||ro.set(e,t=String.fromCodePoint(this.nextStackID++)),t+e}}function Hc(n,e){for(let t=0;t<e.length;t++){let i=e[t];if(i.pos==n.pos&&i.sameState(n)){e[t].score<n.score&&(e[t]=n);return}}e.push(n)}class EA{constructor(e,t,i){this.source=e,this.flags=t,this.disabled=i}allows(e){return!this.disabled||this.disabled[e]==0}}const oo=n=>n;class UA{constructor(e){this.start=e.start,this.shift=e.shift||oo,this.reduce=e.reduce||oo,this.reuse=e.reuse||oo,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Js extends _u{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;a<e.repeatNodeCount;a++)t.push("");let i=Object.keys(e.topRules).map(a=>e.topRules[a][1]),s=[];for(let a=0;a<t.length;a++)s.push([]);function r(a,l,c){s[a].push([l,l.deserialize(String(c))])}if(e.nodeProps)for(let a of e.nodeProps){let l=a[0];typeof l=="string"&&(l=_[l]);for(let c=1;c<a.length;){let h=a[c++];if(h>=0)r(h,l,a[c++]);else{let u=a[c+-h];for(let f=-h;f>0;f--)r(a[c++],l,u);c++}}}this.nodeSet=new Ka(t.map((a,l)=>et.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:s[l],top:i.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=Yu;let o=dn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;a<this.specializerSpecs.length;a++)this.specialized[a]=this.specializerSpecs[a].term;this.specializers=this.specializerSpecs.map(Gc),this.states=dn(e.states,Uint32Array),this.data=dn(e.stateData),this.goto=dn(e.goto),this.maxTerm=e.maxTerm,this.tokenizers=e.tokenizers.map(a=>typeof a=="number"?new Di(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new MA(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],a=o&1,l=s[r++];if(a&&i)return l;for(let c=r+(o>>1);r<c;r++)if(s[r]==e)return l;if(a)return-1}}hasAction(e,t){let i=this.data;for(let s=0;s<2;s++)for(let r=this.stateSlot(e,s?2:1),o;;r+=3){if((o=i[r])==65535)if(i[r+1]==1)o=i[r=Dt(i,r+2)];else{if(i[r+1]==2)return Dt(i,r+2);break}if(o==t||o==0)return Dt(i,r+1)}return 0}stateSlot(e,t){return this.states[e*6+t]}stateFlag(e,t){return(this.stateSlot(e,0)&t)>0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Dt(this.data,r+2);else break;s=t(Dt(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Dt(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(Js.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(a=>a.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=Gc(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;r<t.length;r++)if(!i[r])for(let o=this.dialects[t[r]],a;(a=this.data[o++])!=65535;)(s||(s=new Uint8Array(this.maxTerm+1)))[a]=1;return new EA(e,i,s)}static deserialize(e){return new Js(e)}}function Dt(n,e){return n[e]|n[e+1]<<16}function FA(n){let e=null;for(let t of n){let i=t.p.stoppedAt;(t.pos==t.p.stream.end||i!=null&&t.pos>i)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.score<t.score)&&(e=t)}return e}function Gc(n){if(n.external){let e=n.extend?1:0;return(t,i)=>n.external(t,i)<<1|e}return n.get}const DA=316,LA=317,_c=1,XA=2,BA=3,IA=4,WA=318,qA=320,zA=321,VA=5,jA=6,YA=0,aa=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],cd=125,NA=59,la=47,HA=42,GA=43,_A=45,JA=60,eb=44,tb=63,ib=46,nb=91,sb=new UA({start:!1,shift(n,e){return e==VA||e==jA||e==qA?n:e==zA},strict:!1}),rb=new qn((n,e)=>{let{next:t}=n;(t==cd||t==-1||e.context)&&n.acceptToken(WA)},{contextual:!0,fallback:!0}),ob=new qn((n,e)=>{let{next:t}=n,i;aa.indexOf(t)>-1||t==la&&((i=n.peek(1))==la||i==HA)||t!=cd&&t!=NA&&t!=-1&&!e.context&&n.acceptToken(DA)},{contextual:!0}),ab=new qn((n,e)=>{n.next==nb&&!e.context&&n.acceptToken(LA)},{contextual:!0}),lb=new qn((n,e)=>{let{next:t}=n;if(t==GA||t==_A){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(_c);n.acceptToken(i?_c:XA)}}else t==tb&&n.peek(1)==ib&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(BA))},{contextual:!0});function ao(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}const cb=new qn((n,e)=>{if(n.next!=JA||!e.dialectEnabled(YA)||(n.advance(),n.next==la))return;let t=0;for(;aa.indexOf(n.next)>-1;)n.advance(),t++;if(ao(n.next,!0)){for(n.advance(),t++;ao(n.next,!1);)n.advance(),t++;for(;aa.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==eb)return;for(let i=0;;i++){if(i==7){if(!ao(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(IA,-t)}),hb=Ju({"get set async static":O.modifier,"for while do if else switch try catch finally return throw break continue default case defer":O.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":O.operatorKeyword,"let var const using function class extends":O.definitionKeyword,"import export from":O.moduleKeyword,"with debugger new":O.keyword,TemplateString:O.special(O.string),super:O.atom,BooleanLiteral:O.bool,this:O.self,null:O.null,Star:O.modifier,VariableName:O.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":O.function(O.variableName),VariableDefinition:O.definition(O.variableName),Label:O.labelName,PropertyName:O.propertyName,PrivatePropertyName:O.special(O.propertyName),"CallExpression/MemberExpression/PropertyName":O.function(O.propertyName),"FunctionDeclaration/VariableDefinition":O.function(O.definition(O.variableName)),"ClassDeclaration/VariableDefinition":O.definition(O.className),"NewExpression/VariableName":O.className,PropertyDefinition:O.definition(O.propertyName),PrivatePropertyDefinition:O.definition(O.special(O.propertyName)),UpdateOp:O.updateOperator,"LineComment Hashbang":O.lineComment,BlockComment:O.blockComment,Number:O.number,String:O.string,Escape:O.escape,ArithOp:O.arithmeticOperator,LogicOp:O.logicOperator,BitOp:O.bitwiseOperator,CompareOp:O.compareOperator,RegExp:O.regexp,Equals:O.definitionOperator,Arrow:O.function(O.punctuation),": Spread":O.punctuation,"( )":O.paren,"[ ]":O.squareBracket,"{ }":O.brace,"InterpolationStart InterpolationEnd":O.special(O.brace),".":O.derefOperator,", ;":O.separator,"@":O.meta,TypeName:O.typeName,TypeDefinition:O.definition(O.typeName),"type enum interface implements namespace module declare":O.definitionKeyword,"abstract global Privacy readonly override":O.modifier,"is keyof unique infer asserts":O.operatorKeyword,JSXAttributeValue:O.attributeValue,JSXText:O.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":O.angleBracket,"JSXIdentifier JSXNameSpacedName":O.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":O.attributeName,"JSXBuiltin/JSXIdentifier":O.standard(O.tagName)}),ub={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},fb={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},db={__proto__:null,"<":193},pb=Js.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ`O'#HrO?YQ`O'#HxO?_Q!0LsO'#IOO%[QlO'#IQO?jQ!0LsO'#ISO?uQ!0LsO'#IUO9uQ!0LrO'#IWO@QQ!0MxO'#CiOASQpO'#DlQOQ`OOO%[QlO'#EQOAjQ`O'#ETO:dQMhO'#EnOA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`-e1o5{Q#p]R'i<VR)f$dY!uQ'`-e1o5{Q'k!rS'u!v!yS'w!z5}S-t'l'mQ-v'nR3T-uT#kZ%eS#jZ%eS%km,oU(g#h#i#lS.Y(h(iQ.^(jQ0t+^Q3Y.ZU3Z.[.]._S7S3[3]R9`7Td#^W#W#Z%h(T(^*Y+Z.T/mr#gZm#h#i#l%e(h(i(j+^.Z.[.]._3[3]7TS*]$x*bQ/t*^Q2U,oQ2l-VQ4`/pQ6q2dQ7s4aQ9W6rT=m'X+[V#aW%h*YU#`W%h*YS(U#W(^U(Z#Z+Z/mS-['X+[T.O(T.TV'^!e%i*ZQ$lfR)x$qT)m$l)nR4V/UT*_$x*bT*h${*YQ0w+fQ1g,VQ3_.fQ5t1iQ6P1qQ7X3cQ8r6SQ9c7WQ:^8qQ:p9bQ;Z:`Q;c:rQ;n;[R;q;dnqOXst!Z#d%m&r&t&u&w,s,x2[2_Q&l!VR,h&itmOXst!U!V!Z#d%m&i&r&t&u&w,s,x2[2_R,o&oT%lm,oR1k,XR,g&gQ&U|S+}&V&WR1^,OR+s&PT&p!W&sT&q!W&sT2^,x2_",nodeNames:"⚠ ArithOp ArithOp ?. JSXStartTag LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:sb,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[hb],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#P$/W#P#Q$4o#Q#R$5y#R#SEr#S#T$7W#T#o$8b#o#p$<r#p#q$=h#q#r$>x#r#s$@U#s$f%Z$f$g+g$g#BYEr#BY#BZ$A`#BZ$ISEr$IS$I_$A`$I_$I|Er$I|$I}$Dk$I}$JO$Dk$JO$JTEr$JT$JU$A`$JU$KVEr$KV$KW$A`$KW&FUEr&FU&FV$A`&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$A`?HUOEr(n%d_$i&j(Wp(Z!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$i&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$i&j(Z!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(Z!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$i&j(WpOY(rYZ&cZr(rrs&cs!^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;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new oa("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>ub[n]||-1},{term:343,get:n=>fb[n]||-1},{term:95,get:n=>db[n]||-1}],tokenPrec:15201}),hd=[Ye("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ye("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ye("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ye("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ye("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ye(`try { \${} } catch (\${error}) { \${} @@ -20,12 +20,19 @@ constructor(\${params}) { \${} } -}`,{label:"class",detail:"definition",type:"keyword"}),Ye('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ye('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],hb=od.concat([Ye("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Ye("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Ye("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Hc=new dO,ad=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const ub=["FunctionDeclaration"],fb={FunctionDeclaration:cn("function"),ClassDeclaration:cn("class"),ClassExpression:()=>!0,EnumDeclaration:cn("constant"),TypeAliasDeclaration:cn("type"),NamespaceDeclaration:cn("namespace"),VariableDefinition(n,e){n.matchContext(ub)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function ld(n,e){let t=Hc.get(e);if(t)return t;let i=[],s=!0;function r(o,a){let l=n.sliceString(o.from,o.to);i.push({label:l,type:a})}return e.cursor(be.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let a=fb[o.name];if(a&&a(o,r)||ad.has(o.name))return!1}else if(o.to-o.from>8192){for(let a of ld(n,o.node))i.push(a);return!1}}),Hc.set(e,i),i}const Gc=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,cd=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function db(n){let e=Ce(n.state).resolveInner(n.pos,-1);if(cd.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Gc.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)ad.has(s.name)&&(i=i.concat(ld(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:Gc}}const Xt=Xs.define({name:"javascript",parser:cb.configure({props:[ef.add({IfStatement:Nr({except:/^\s*({|else\b)/}),TryStatement:Nr({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:MO,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:ZO({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Nr({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),sf.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":DO,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),hd={test:n=>/^JSX/.test(n.name),facet:_u({commentTokens:{block:{open:"{/*",close:"*/}"}}})},pb=Xt.configure({dialect:"ts"},"typescript"),mb=Xt.configure({dialect:"jsx",props:[Za.add(n=>n.isTop?[hd]:void 0)]}),gb=Xt.configure({dialect:"jsx ts",props:[Za.add(n=>n.isTop?[hd]:void 0)]},"typescript");let ud=n=>({label:n,type:"keyword"});const fd="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(ud),Ob=fd.concat(["declare","implements","private","protected","public"].map(ud));function yb(n={}){let e=n.jsx?n.typescript?gb:mb:n.typescript?pb:Xt,t=n.typescript?hb.concat(Ob):od.concat(fd);return new kO(e,[Xt.data.of({autocomplete:Ty(cd,Yf(t))}),Xt.data.of({autocomplete:db}),n.jsx?Sb:[]])}function Ab(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function _c(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const bb=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Sb=$.inputHandler.of((n,e,t,i,s)=>{if((bb?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!Xt.isActiveAt(n.state,e,-1))return!1;let r=s(),{state:o}=r,a=o.changeByRange(l=>{var c;let{head:h}=l,u=Ce(o).resolveInner(h-1,-1),f;if(u.name=="JSXStartTag"&&(u=u.parent),!(o.doc.sliceString(h-1,h)!=i||u.name=="JSXAttributeValue"&&u.to>h)){if(i==">"&&u.name=="JSXFragmentTag")return{range:l,changes:{from:h,insert:"</>"}};if(i=="/"&&u.name=="JSXStartCloseTag"){let d=u.parent,p=d.parent;if(p&&d.from==h-2&&((f=_c(o.doc,p.firstChild,h))||((c=p.firstChild)===null||c===void 0?void 0:c.name)=="JSXFragmentTag")){let m=`${f}>`;return{range:A.cursor(h+m.length,-1),changes:{from:h,insert:m}}}}else if(i==">"){let d=Ab(u);if(d&&d.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(h,h+2))&&(f=_c(o.doc,d,h)))return{range:l,changes:{from:h,insert:`</${f}>`}}}}return{range:l}});return a.changes.empty?!1:(n.dispatch([r,o.update(a,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Jc=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n;class Yi{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?a=>r(Jc(a)):Jc,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Ne(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=fa(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Qt(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,a=!0;;r++){let l=s.charCodeAt(r),c=this.match(l,o,a,this.bufferPos+this.bufferStart,r==s.length-1);if(c)return this.value=c,this;if(r==s.length-1)break;a&&r<t.length&&t.charCodeAt(r)==l?o++:a=!1}}}match(e,t,i,s,r){let o=null;for(let a=0;a<this.matches.length;){let l=this.matches[a],c=!1;this.query.charCodeAt(l.index)==e&&(l.index==this.query.length-1?o={from:l.from,to:s,precise:r&&l.precise}:(l.index++,c=!0)),c?a++:this.matches.splice(a,1)}return this.query.charCodeAt(0)==e&&(this.query.length==1?o={from:t,to:s,precise:i&&r}:this.matches.push({from:t,index:1,precise:i})),o&&this.test&&!this.test(o.from,o.to,this.buffer,this.bufferStart)&&(o=null),o}}typeof Symbol<"u"&&(Yi.prototype[Symbol.iterator]=function(){return this});const dd={from:-1,to:-1,match:/.*/.exec(""),precise:!0},Na="gm"+(/x/.unicode==null?"":"u");class pd{constructor(e,t,i,s=0,r=e.length){if(this.text=e,this.to=r,this.curLine="",this.done=!1,this.value=dd,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new md(e,t,i,s,r);this.re=new RegExp(t,Na+(i?.ignoreCase?"i":"")),this.test=i?.test,this.iter=e.iter();let o=e.lineAt(s);this.curLineStart=o.from,this.matchPos=_s(e,s),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=_s(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(i<s||i>this.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}}const oo=new WeakMap;class Li{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(e,t,i){let s=oo.get(e);if(!s||s.from>=i||s.to<=t){let a=new Li(t,e.sliceString(t,i));return oo.set(e,a),a}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.to<i&&(r+=e.sliceString(s.to,i)),oo.set(e,new Li(o,r)),new Li(t,r.slice(t-o,i-o))}}class md{constructor(e,t,i,s,r){this.text=e,this.to=r,this.done=!1,this.value=dd,this.matchPos=_s(e,s),this.re=new RegExp(t,Na+(i?.ignoreCase?"i":"")),this.test=i?.test,this.flat=Li.get(e,s,this.chunkEnd(s+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=_s(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Li.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(pd.prototype[Symbol.iterator]=md.prototype[Symbol.iterator]=function(){return this});function xb(n){try{return new RegExp(n,Na),!0}catch{return!1}}function _s(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e<t.to&&(i=t.text.charCodeAt(e-t.from))>=56320&&i<57344;)e++;return e}const vb=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=jg(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,h,u]=o,f=h?+h.slice(1):0,d=c?+c:a.number;if(c&&u){let g=d/100;l&&(g=g*(l=="-"?-1:1)+a.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else c&&l&&(d=d*(l=="-"?-1:1)+a.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),m=A.cursor(p.from+Math.max(0,Math.min(f,p.length)));n.dispatch({effects:[i,$.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},wb={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},kb=K.define({combine(n){return yt(n,wb,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function Qb(n){return[$b,Rb]}const Pb=B.mark({class:"cm-selectionMatch"}),Cb=B.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function eh(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=ye.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=ye.Word)}function Tb(n,e,t,i){return n(e.sliceDoc(t,t+1))==ye.Word&&n(e.sliceDoc(i-1,i))==ye.Word}const Rb=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(kb),{state:t}=n,i=t.selection;if(i.ranges.length>1)return B.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return B.none;let l=t.wordAt(s.head);if(!l)return B.none;o=t.charCategorizer(s.head),r=t.sliceDoc(l.from,l.to)}else{let l=s.to-s.from;if(l<e.minSelectionLength||l>200)return B.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(eh(o,t,s.from,s.to)&&Tb(o,t,s.from,s.to)))return B.none}else if(r=t.sliceDoc(s.from,s.to),!r)return B.none}let a=[];for(let l of n.visibleRanges){let c=new Yi(t.doc,r,l.from,l.to);for(;!c.next().done;){let{from:h,to:u}=c.value;if((!o||eh(o,t,h,u))&&(s.empty&&h<=s.from&&u>=s.to?a.push(Cb.range(h,u)):(h>=s.to||u<=s.from)&&a.push(Pb.range(h,u)),a.length>e.maxMatches))return B.none}}return B.set(a)}},{decorations:n=>n.decorations}),$b=$.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Kb=({state:n,dispatch:e})=>{let{selection:t}=n,i=A.create(t.ranges.map(s=>n.wordAt(s.head)||A.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function Zb(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,a=new Yi(n.doc,e,i[i.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new Yi(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(l=>l.from==a.value.from))continue;if(r){let l=n.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const Mb=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return Kb({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=Zb(n,i);return s?(e(n.update({selection:n.selection.addRange(A.range(s.from,s.to),!1),effects:$.scrollIntoView(s.to)})),!0):!1},tn=K.define({combine(n){return yt(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Yb(e),scrollToMatch:e=>$.scrollIntoView(e)})}});class gd{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||xb(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` -`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new Xb(this):new Fb(this)}getCursor(e,t=0,i){let s=e.doc?e:_.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Pi(this,s,t,i):Qi(this,s,t,i)}}class Od{constructor(e){this.spec=e}}function Eb(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let a=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(a,e,i,s)}}function Qi(n,e,t,i){let s;return n.wholeWord&&(s=Ub(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=Eb(n.test,e,s)),new Yi(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function Ub(n,e){return(t,i,s,r)=>((r>t||r+s.length<i)&&(r=Math.max(0,t-2),s=n.sliceString(r,Math.min(n.length,i+2))),(e(Js(s,t-r))!=ye.Word||e(er(s,t-r))!=ye.Word)&&(e(er(s,i-r))!=ye.Word||e(Js(s,i-r))!=ye.Word))}class Fb extends Od{constructor(e){super(e)}nextMatch(e,t,i){let s=Qi(this.spec,e,i,e.doc.length).nextOverlapping();if(s.done){let r=Math.min(e.doc.length,t+this.spec.unquoted.length);s=Qi(this.spec,e,0,r).nextOverlapping()}return s.done||s.value.from==t&&s.value.to==i?null:s.value}prevMatchInRange(e,t,i){for(let s=i;;){let r=Math.max(t,s-1e4-this.spec.unquoted.length),o=Qi(this.spec,e,r,s),a=null;for(;!o.nextOverlapping().done;)a=o.value;if(a)return a;if(r==t)return null;s-=1e4}}prevMatch(e,t,i){let s=this.prevMatchInRange(e,0,t);return s||(s=this.prevMatchInRange(e,Math.max(0,i-this.spec.unquoted.length),e.doc.length)),s&&(s.from!=t||s.to!=i)?s:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=Qi(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Qi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}function Db(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Pi(n,e,t,i){let s;return n.wholeWord&&(s=Lb(e.charCategorizer(e.selection.main.head))),n.test&&(s=Db(n.test,e,s)),new pd(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function Js(n,e){return n.slice(Ze(n,e,!1),e)}function er(n,e){return n.slice(e,Ze(n,e))}function Lb(n){return(e,t,i)=>!i[0].length||(n(Js(i.input,i.index))!=ye.Word||n(er(i.input,i.index))!=ye.Word)&&(n(er(i.input,i.index+i[0].length))!=ye.Word||n(Js(i.input,i.index+i[0].length))!=ye.Word)}class Xb extends Od{nextMatch(e,t,i){let s=Pi(this.spec,e,i,e.doc.length).next();return s.done&&(s=Pi(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Pi(this.spec,e,r,i),a=null;for(;!o.next().done;)a=o.value;if(a&&(r==t||a.from>r+10))return a;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r<e.match.length)return e.match[r]+i.slice(s)}return t})}matchAll(e,t){let i=Pi(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Pi(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}const Zn=z.define(),Ha=z.define(),Gt=Te.define({create(n){return new ao(aa(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Zn)?n=new ao(t.value.create(),n.panel):t.is(Ha)&&(n=new ao(n.query,t.value?Ga:null));return n},provide:n=>Vi.from(n,e=>e.panel)});class ao{constructor(e,t){this.query=e,this.panel=t}}const Bb=B.mark({class:"cm-searchMatch"}),Ib=B.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Wb=xe.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Gt))}update(n){let e=n.state.field(Gt);(e!=n.startState.field(Gt)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return B.none;let{view:t}=this,i=new Bt;for(let s=0,r=t.visibleRanges,o=r.length;s<o;s++){let{from:a,to:l}=r[s];for(;s<o-1&&l>r[s+1].from-500;)l=r[++s].to;n.highlight(t.state,a,l,(c,h)=>{let u=t.state.selection.ranges.some(f=>f.from==c&&f.to==h);i.add(c,h,u?Ib:Bb)})}return i.finish()}},{decorations:n=>n.decorations});function qn(n){return e=>{let t=e.state.field(Gt,!1);return t&&t.query.spec.valid?n(e,t):bd(e)}}const tr=qn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=A.single(i.from,i.to),r=n.state.facet(tn);return n.dispatch({selection:s,effects:[_a(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),Ad(n),!0}),ir=qn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=A.single(s.from,s.to),o=n.state.facet(tn);return n.dispatch({selection:r,effects:[_a(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),Ad(n),!0}),qb=qn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:A.create(t.map(i=>A.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),zb=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let a=new Yi(n.doc,n.sliceDoc(i,s));!a.next().done;){if(r.length>1e3)return!1;a.value.from==i&&(o=r.length),r.push(A.range(a.value.from,a.value.to))}return e(n.update({selection:A.create(r,o),userEvent:"select.search.matches"})),!0},th=qn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,a=[],l,c,h=[];o.precise?o.from==i&&o.to==s&&(c=t.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(t,o.from,o.to),h.push($.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let u=n.state.changes(a);return o&&(l=A.single(o.from,o.to).map(u),h.push(_a(n,o)),h.push(t.facet(tn).scrollToMatch(l.main,n))),n.dispatch({changes:u,selection:l,effects:h,userEvent:"input.replace"}),!0}),Vb=qn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:a}=s;a&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:$.announce.of(i),userEvent:"input.replace.all"}),!0});function Ga(n){return n.state.facet(tn).createPanel(n)}function aa(n,e){var t,i,s,r,o;let a=n.selection.main,l=a.empty||a.to>a.from+100?"":n.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=n.facet(tn);return new gd({search:((t=e?.literal)!==null&&t!==void 0?t:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:c.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:c.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:c.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function yd(n){let e=Fu(n,Ga);return e&&e.dom.querySelector("[main-field]")}function Ad(n){let e=yd(n);e&&e==n.root.activeElement&&e.select()}const bd=n=>{let e=n.state.field(Gt,!1);if(e&&e.panel){let t=yd(n);if(t&&t!=n.root.activeElement){let i=aa(n.state,e.query.spec);i.valid&&n.dispatch({effects:Zn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Ha.of(!0),e?Zn.of(aa(n.state,e.query.spec)):z.appendConfig.of(Hb)]});return!0},Sd=n=>{let e=n.state.field(Gt,!1);if(!e||!e.panel)return!1;let t=Fu(n,Ga);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Ha.of(!1)}),!0},jb=[{key:"Mod-f",run:bd,scope:"editor search-panel"},{key:"F3",run:tr,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:tr,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Sd,scope:"editor search-panel"},{key:"Mod-Shift-l",run:zb},{key:"Mod-Alt-g",run:vb},{key:"Mod-d",run:Mb,preventDefault:!0}];class Yb{constructor(e){this.view=e;let t=this.query=e.state.field(Gt).query.spec;this.commit=this.commit.bind(this),this.searchField=he("input",{value:t.search,placeholder:st(e,"Find"),"aria-label":st(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=he("input",{value:t.replace,placeholder:st(e,"Replace"),"aria-label":st(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=he("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=he("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=he("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return he("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=he("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>tr(e),[st(e,"next")]),i("prev",()=>ir(e),[st(e,"previous")]),i("select",()=>qb(e),[st(e,"all")]),he("label",null,[this.caseField,st(e,"match case")]),he("label",null,[this.reField,st(e,"regexp")]),he("label",null,[this.wordField,st(e,"by word")]),...e.state.readOnly?[]:[he("br"),this.replaceField,i("replace",()=>th(e),[st(e,"replace")]),i("replaceAll",()=>Vb(e),[st(e,"replace all")])],he("button",{name:"close",onclick:()=>Sd(e),"aria-label":st(e,"close"),type:"button"},["×"])])}commit(){let e=new gd({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Zn.of(e)}))}keydown(e){sg(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?ir:tr)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),th(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Zn)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(tn).top}}function st(n,e){return n.state.phrase(e)}const fs=30,ds=/[\s\.,:;?!]/;function _a(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-fs),o=Math.min(s,t+fs),a=n.state.sliceDoc(r,o);if(r!=i.from){for(let l=0;l<fs;l++)if(!ds.test(a[l+1])&&ds.test(a[l])){a=a.slice(l);break}}if(o!=s){for(let l=a.length-1;l>a.length-fs;l--)if(!ds.test(a[l-1])&&ds.test(a[l])){a=a.slice(0,l);break}}return $.announce.of(`${n.state.phrase("current match")}. ${a} ${n.state.phrase("on line")} ${i.number}.`)}const Nb=$.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Hb=[Gt,ri.low(Wb),Nb];class ih{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class di{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(Kt).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new Bt,a=[],l=0,c=i.doc.iter(),h=0,u=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!a.length)break;let m,g;if(a.length)m=l,g=a.reduce((x,C)=>Math.min(x,C.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>u)break;g=p.to,a.push(p),d++}for(;d<r.length;){let x=r[d];if(x.from==m&&(x.to>x.from||x.to==m))a.push(x),d++,g=Math.min(x.to,g);else{g=Math.min(x.from,g);break}}g=Math.min(g,u);let y=!1;if(a.some(x=>x.from==m&&(x.to==g||g==u))&&(y=m==g,!y&&g-m<10)){let x=m-(h+c.value.length);x>0&&(c.next(x),h=m);for(let C=m;;){if(C>=g){y=!0;break}if(!c.lineBreak&&h+c.value.length>C)break;C=h+c.value.length,h+=c.value.length,c.next()}}let b=Td(a);if(y)o.add(m,m,B.widget({widget:new nS(b),diagnostics:a.slice()}));else{let x=a.reduce((C,k)=>k.markClass?C+" "+k.markClass:C,"");o.add(m,g,B.mark({class:"cm-lintRange cm-lintRange-"+b+x,diagnostics:a.slice(),inclusiveEnd:a.some(C=>C.to>g)}))}if(l=g,l==u)break;for(let x=0;x<a.length;x++)a[x].to<=l&&a.splice(x--,1)}let f=o.finish();return new di(f,t,Ni(f))}}function Ni(n,e=null,t=0){let i=null;return n.between(t,1e9,(s,r,{spec:o})=>{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new ih(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new ih(i.from,r,i.diagnostic)}}),i}function xd(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(Kt).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(Qr))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function Gb(n,e){return n.field(gt,!1)?e:e.concat(z.appendConfig.of(Kd))}function vd(n,e){return{effects:Gb(n,[Qr.of(e)])}}const Qr=z.define(),wd=z.define(),kd=z.define(),gt=Te.define({create(){return new di(B.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Ni(t,n.selected.diagnostic,r)||Ni(t,null,r)}!t.size&&s&&e.state.facet(Kt).autoPanel&&(s=null),n=new di(t,s,i)}for(let t of e.effects)if(t.is(Qr)){let i=e.state.facet(Kt).autoPanel?t.value.length?nr.open:null:n.panel;n=di.init(t.value,i,e.state)}else t.is(wd)?n=new di(n.diagnostics,t.value?nr.open:null,n.selected):t.is(kd)&&(n=new di(n.diagnostics,n.panel,t.value));return n},provide:n=>[Vi.from(n,e=>e.panel),$.decorations.from(n,e=>e.diagnostics)]}),_b=B.mark({class:"cm-lintRange cm-lintRange-active"});function Jb(n,e,t){let{diagnostics:i}=n.state.field(gt),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(l,c,{spec:h})=>{if(e>=l&&e<=c&&(l==c||(e>l||t>0)&&(e<c||t<0)))return s=h.diagnostics,r=l,o=c,!1});let a=n.state.facet(Kt).tooltipFilter;return s&&a&&(s=a(s,n.state)),s?{pos:r,end:o,above:!0,create(){return{dom:Qd(n,s)}}}:null}function Qd(n,e){return he("ul",{class:"cm-tooltip-lint"},e.map(t=>Cd(n,t,!1)))}const nh=n=>{let e=n.state.field(gt,!1);return!e||!e.panel?!1:(n.dispatch({effects:wd.of(!1)}),!0)},eS=xe.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(Kt);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){clearTimeout(this.timeout);let n=Date.now();if(n<this.lintTime-10)this.timeout=setTimeout(this.run,this.lintTime-n);else{this.set=!1;let{state:e}=this.view,{sources:t}=e.facet(Kt);t.length&&tS(t.map(i=>Promise.resolve(i(this.view))),i=>{this.view.state.doc==e.doc&&this.view.dispatch(vd(this.view.state,i.reduce((s,r)=>s.concat(r))))},i=>{ze(this.view.state,i)})}}update(n){let e=n.state.facet(Kt);(n.docChanged||e!=n.startState.facet(Kt)||e.needsRefresh&&e.needsRefresh(n))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}});function tS(n,e,t){let i=[],s=-1;for(let r of n)r.then(o=>{i.push(o),clearTimeout(s),i.length==n.length?e(i):s=setTimeout(()=>e(i),200)},t)}const Kt=K.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...yt(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:sh,tooltipFilter:sh,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function sh(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function iS(n,e={}){return[Kt.of({source:n,config:e}),eS,Kd]}function Pd(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;i<t.length;i++){let s=t[i];if(/[a-zA-Z]/.test(s)&&!e.some(r=>r.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function Cd(n,e,t){var i;let s=t?Pd(e.actions):[];return he("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},he("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let a=!1,l=d=>{if(d.preventDefault(),a)return;a=!0;let p=Ni(n.state.field(gt).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:c}=r,h=s[o]?c.indexOf(s[o]):-1,u=h<0?c:[c.slice(0,h),he("u",c.slice(h,h+1)),c.slice(h+1)],f=r.markClass?" "+r.markClass:"";return he("button",{type:"button",class:"cm-diagnosticAction"+f,onclick:l,onmousedown:l,"aria-label":` Action: ${c}${h<0?"":` (access key "${s[o]})"`}.`},u)}),e.source&&he("div",{class:"cm-diagnosticSource"},e.source))}class nS extends Ut{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return he("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class rh{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Cd(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class nr{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)nh(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=Pd(r.actions);for(let a=0;a<o.length;a++)if(o[a].toUpperCase().charCodeAt(0)==s.keyCode){let l=Ni(this.view.state.field(gt).diagnostics,r);l&&r.actions[a].apply(e,l.from,l.to)}}else return;s.preventDefault()}},i=s=>{for(let r=0;r<this.items.length;r++)this.items[r].dom.contains(s.target)&&this.moveSelection(r)};this.list=he("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:t,onclick:i}),this.dom=he("div",{class:"cm-panel-lint"},this.list,he("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>nh(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(gt).selected;if(!e)return-1;for(let t=0;t<this.items.length;t++)if(this.items[t].diagnostic==e.diagnostic)return t;return-1}update(){let{diagnostics:e,selected:t}=this.view.state.field(gt),i=0,s=!1,r=null,o=new Set;for(e.between(0,this.view.state.doc.length,(a,l,{spec:c})=>{for(let h of c.diagnostics){if(o.has(h))continue;o.add(h);let u=-1,f;for(let d=i;d<this.items.length;d++)if(this.items[d].diagnostic==h){u=d;break}u<0?(f=new rh(this.view,h),this.items.splice(i,0,f),s=!0):(f=this.items[u],u>i&&(this.items.splice(i,u-i),s=!0)),t&&f.diagnostic==t.diagnostic?f.dom.hasAttribute("aria-selected")||(f.dom.setAttribute("aria-selected","true"),r=f):f.dom.hasAttribute("aria-selected")&&f.dom.removeAttribute("aria-selected"),i++}});i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new rh(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),r?(this.list.setAttribute("aria-activedescendant",r.id),this.view.requestMeasure({key:this,read:()=>({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:a,panel:l})=>{let c=l.height/this.list.offsetHeight;a.top<l.top?this.list.scrollTop-=(l.top-a.top)/c:a.bottom>l.bottom&&(this.list.scrollTop+=(a.bottom-l.bottom)/c)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(gt),i=Ni(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:kd.of(i)})}static open(e){return new nr(e)}}function Qs(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${e}>${encodeURIComponent(n)}</svg>')`}function ps(n){return Qs(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${n}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const sS=$.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:ps("#f11")},".cm-lintRange-warning":{backgroundImage:ps("orange")},".cm-lintRange-info":{backgroundImage:ps("#999")},".cm-lintRange-hint":{backgroundImage:ps("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function rS(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function Td(n){let e="hint",t=1;for(let i of n){let s=rS(i.severity);s>t&&(t=s,e=i.severity)}return e}class Rd extends Mt{constructor(e){super(),this.diagnostics=e,this.severity=Td(e)}toDOM(e){let t=document.createElement("div");t.className="cm-lint-marker cm-lint-marker-"+this.severity;let i=this.diagnostics,s=e.state.facet(Pr).tooltipFilter;return s&&(i=s(i,e.state)),i.length&&(t.onmouseover=()=>aS(e,t,i)),t}}function oS(n,e){let t=i=>{let s=e.getBoundingClientRect();if(!(i.clientX>s.left-10&&i.clientX<s.right+10&&i.clientY>s.top-10&&i.clientY<s.bottom+10)){for(let r=i.target;r;r=r.parentNode)if(r.nodeType==1&&r.classList.contains("cm-tooltip-lint"))return;window.removeEventListener("mousemove",t),n.state.field($d)&&n.dispatch({effects:Ja.of(null)})}};window.addEventListener("mousemove",t)}function aS(n,e,t){function i(){let o=n.elementAtHeight(e.getBoundingClientRect().top+5-n.documentTop);n.coordsAtPos(o.from)&&n.dispatch({effects:Ja.of({pos:o.from,above:!1,clip:!1,create(){return{dom:Qd(n,t),getCoords:()=>e.getBoundingClientRect()}}})}),e.onmouseout=e.onmousemove=null,oS(n,e)}let{hoverTime:s}=n.state.facet(Pr),r=setTimeout(i,s);e.onmouseout=()=>{clearTimeout(r),e.onmouseout=e.onmousemove=null},e.onmousemove=()=>{clearTimeout(r),r=setTimeout(i,s)}}function lS(n,e){let t=Object.create(null);for(let s of e){let r=n.lineAt(s.from);(t[r.from]||(t[r.from]=[])).push(s)}let i=[];for(let s in t)i.push(new Rd(t[s]).range(+s));return N.of(i,!0)}const cS=Bu({class:"cm-gutter-lint",markers:n=>n.state.field(la),widgetMarker:(n,e,t)=>{let i=[];return n.state.field(la).between(t.from,t.to,(s,r,o)=>{s>t.from&&s<t.to&&i.push(...o.diagnostics)}),i.length?new Rd(i):null}}),la=Te.define({create(){return N.empty},update(n,e){n=n.map(e.changes);let t=e.state.facet(Pr).markerFilter;for(let i of e.effects)if(i.is(Qr)){let s=i.value;t&&(s=t(s||[],e.state)),n=lS(e.state.doc,s.slice(0))}return n}}),Ja=z.define(),$d=Te.define({create(){return null},update(n,e){return n&&e.docChanged&&(n=xd(e,n)?null:{...n,pos:e.changes.mapPos(n.pos)}),e.effects.reduce((t,i)=>i.is(Ja)?i.value:t,n)},provide:n=>gr.from(n)}),hS=$.baseTheme({".cm-gutter-lint":{width:"1.4em","& .cm-gutterElement":{padding:".2em"}},".cm-lint-marker":{width:"1em",height:"1em"},".cm-lint-marker-info":{content:Qs('<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>')},".cm-lint-marker-warning":{content:Qs('<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>')},".cm-lint-marker-error":{content:Qs('<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>')}}),uS=Eu(Jb,{hideOn:xd}),Kd=[gt,$.decorations.compute([gt],n=>{let{selected:e,panel:t}=n.field(gt);return!e||!t||e.from==e.to?B.none:B.set([_b.range(e.from,e.to)])}),uS,sS],Pr=K.define({combine(n){return yt(n,{hoverTime:300,markerFilter:null,tooltipFilter:null})}});function fS(n={}){return[Pr.of(n),la,cS,hS,$d]}const Zd=1,Ue=Object.freeze({ready:"studio.ready",documentOpen:"document.open",documentReplace:"document.replace",documentChanged:"document.changed",documentSave:"document.save",documentSetReadOnly:"document.setReadOnly",documentResources:"document.resources",editorInsert:"editor.insert",editorFormat:"editor.format",editorSetTheme:"editor.setTheme",editorGetState:"editor.getState",diagnosticsPublish:"diagnostics.publish"});function dS(n,e={},t=null,i=null){return{protocolVersion:Zd,type:n,documentID:t,...i===null?{}:{sessionID:i},payload:e}}function pS(n){if(window.WKWebViewJavascriptBridge){n(window.WKWebViewJavascriptBridge);return}if(window.WKWVJBCallbacks){window.WKWVJBCallbacks.push(n);return}window.webkit?.messageHandlers?.iOS_Native_InjectJavascript&&(window.WKWVJBCallbacks=[n],window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null))}function nn(n,e,t={},i=null,s=()=>{},r=null){if(!n){s({result:"unavailable"});return}n.callHandler(e,dS(e,t,i,r),s)}function mS(n){const e={capabilities:["jsx","format","search","completion","diagnostics"]};nn(n,Ue.ready,e)}const gS=[{id:"$storage.getString",arguments:["key"],returns:"string",documentation:"Read a package-scoped string. Missing keys return an empty string."},{id:"$storage.setString",arguments:["key","value"],returns:"boolean",documentation:"Set a package-scoped string, limited to 256 KiB of UTF-8. Check the success result."},{id:"$storage.getJSON",arguments:["key"],returns:"json",documentation:"Read a package-scoped JSON object. Missing or invalid values return an empty object."},{id:"$storage.setJSON",arguments:["key","value"],returns:"boolean",documentation:"Store a valid JSON object, limited to 256 KiB encoded. Check the success result."},{id:"$storage.compareAndSetString",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a string only when it still matches expected. A missing key matches an empty string. Conflicts return false; reread and retry a bounded number of times. Requires the shared storage container."},{id:"$storage.compareAndSetJSON",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a JSON object if its current value equals expected, independent of property order. A missing key matches an empty object. Wrong types and conflicts return false. Requires the shared storage container."},{id:"$storage.remove",arguments:["key"],returns:"boolean",documentation:"Remove a key from this package only."},{id:"$storage.keys",arguments:[],returns:"string[]",documentation:"List keys in this package's namespace."},{id:"$storage.clear",arguments:[],returns:"boolean",documentation:"Clear this package's storage. Other packages are unaffected."}].map(n=>({minimumRuntimeVersion:"1.0",...n,preview:"initialState"})),OS=[{id:"$notifications.status",group:"notifications",value:{authorization:"authorized"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.pending",group:"notifications",value:[],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.schedule",group:"notifications",value:{key:"daily",status:"scheduled"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$notifications.cancel",group:"notifications",value:{key:"daily",status:"cancellationRequested"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$health.dailyStatistics",group:"health",value:{metric:"steps",unit:"count",aggregation:"sum",timeZone:"UTC",items:[{date:"2026-01-01",value:6840,hasSamples:!0}]},platforms:["ios"],authorization:"healthRead",notes:"Runtime 1.6. Read-only daily HealthKit statistics on installed iPhone/iPad widgets. Declare health and minimumRuntimeVersion 1.6, review Health access in native Settings. No separate System Access toggle. Missing readings are null/hasSamples false and cannot establish read denial. No raw samples, persistence or queries in future/Live Activity presentations. Preview fixtures never access real Health data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHealth.swift",operation:"read",mock:"editable"},{id:"$calendar.create",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$calendar.update",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$weather.forecast",group:"weather",value:{provider:"MET Norway",attribution:{text:"Weather data from MET Norway",url:"https://www.met.no/en/free-meteorological-data/Download-services"},latitude:37.33,longitude:-122.01,fetchedAt:"2026-01-01T12:00:00Z",isStale:!1,hours:[{time:"2026-01-01T12:00:00Z",temperatureC:21,windMetersPerSecond:2,precipitationMM:0,condition:"partlycloudy_day"}]},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeWeather.swift",operation:"read",mock:"editable"},{id:"$alarms.status",group:"alarms",value:{authorization:"authorized"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.pending",group:"alarms",value:[],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.schedule",group:"alarms",value:{key:"focus",status:"scheduled",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.cancel",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.stop",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.pause",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.resume",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$documents.list",group:"documents",value:[{id:"550e8400-e29b-41d4-a716-446655440000",name:"Sample.json",type:"json",bytes:17},{id:"550e8400-e29b-41d4-a716-446655440001",name:"Sample.csv",type:"csv",bytes:24}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readJSON",group:"documents",value:{goal:12,done:7},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readCSV",group:"documents",value:{headers:["day","value"],rows:[["Monday","7"],["Tuesday","9"]],truncated:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$contacts.selected",group:"contacts",value:[{id:"sample.contact",name:"Alex Example",organization:"Sample",phones:["+1 202 555 0100"],emails:["alex@example.com"]}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeContacts.swift",operation:"read",mock:"editable"},{id:"$maps.search",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.geocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["address"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.reverseGeocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.snapshot",group:"maps",value:{image:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",width:256,height:256,provider:"Apple Maps"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$home.items",group:"home",value:[{id:"sample.light",name:"Living Room Lamp",kind:"power",value:!0,isCached:!0,metric:"power",unit:"boolean"},{id:"scene-sample",name:"Evening",kind:"scene",value:null,isCached:!0,metric:"scene",unit:"none"}],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"read",mock:"editable"},{id:"$home.setPower",group:"home",value:{id:"sample.light",value:!0,status:"acknowledged"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"},{id:"$home.runScene",group:"home",value:{id:"scene-sample",status:"acknowledged",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"}],ca="2026-01-01T00:00:00Z",zt="2026-01-01T12:00:00Z",lo=(n,e)=>({value:n,unit:e,hasSamples:!0,start:ca,end:zt}),oh=(n,e,t)=>Object.entries(e).map(([i,s])=>({id:`$${n}.${i}`,group:n,value:s,legacy:[t,i]})),yS=[{id:"$music.isAvailable",group:"music",value:!0},{id:"$music.authorizationStatus",group:"music",value:"authorized"},{id:"$music.current",group:"music",value:{provider:"appleMusic",state:"playing",hasItem:!0,title:"Morning Light",artist:"ScriptWidget Sessions",album:"Focus",duration:224,position:86,capturedAt:zt}},{id:"$services.status",group:"services",value:"connected"},{id:"$services.profile",group:"services",value:{service:"github",subject:"42",username:"octocat",displayName:"Mona",publicRepositories:32,privateRepositories:8,followers:128,following:24}},...oh("device",{screen:{width:390,height:844,scale:3},language:"en",model:"iPhone",name:"My iPhone",battery:{level:.8,state:"unplugged"},systemVersion:"26.0",isdarkmode:!1,totalDiskSpace:128e9,freeDiskSpace:64e9},"device"),...oh("system",{appInfo:{name:"ScriptWidget",bundleId:"com.everettjf.scriptwidget",version:"27.1.2",build:"27012"},locale:"en_US",preferredLanguages:["en-US"],timeZone:{identifier:"UTC",abbreviation:"GMT",offsetSeconds:0},is24HourClock:!1,calendarInfo:{identifier:"gregorian",firstWeekday:1,minimumDaysInFirstWeek:1},systemUptime:3600,memory:{physical:8589934592},thermalState:"nominal",lowPowerMode:!1,brightness:.5,reduceMotionEnabled:!1,platform:"ios",hostName:"My iPhone",processName:"ScriptWidgetWidget",osVersionString:"Version 26.0",processorCount:6,activeProcessorCount:6},"system"),{id:"$photos.isAvailable",group:"photos",value:!0},{id:"$photos.authorizationStatus",group:"photos",value:"authorized"},{id:"$photos.requestAuthorization",group:"photos",value:!0},{id:"$photos.items",group:"photos",value:{status:"ready",items:[{id:"sample.photo",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fbPe3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDQK/QnooooGFFFFABRRRQAUUU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sT3Hcp6r26juD8y0UjahXnRkp03qfthaXdrfW0d7ZSLNDKodHQgqynkEEcEGrFfmf8EvjnffDy6XQtdLXGiytyOrW5J5ZPVe7L+I5zn9JNO1Gx1axi1PTJVnt51DxyIcqynoQazasfXYPGQxMbx36ouUUUUjsP/R+tKKKK6z8/CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApGZVUsxwBySaR3SNDJIQqqMkngAV4h4w8ZPqjNpumMVthwzdC/8A9j/OnGNzOpUUFdkvjHxm2oFtL0psQdHcdX9h/s/z+leb0UVslY86c3N3YUUUUyAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvePgx8bNT+Gl8NN1Hdc6PM2ZIurRE9Xjz39V6H2PNeD0UjSlWlSkpwdmftNo+saZr+mQ6xo0y3FtcLvjkQ5BH9COhB5B4NaVflf8IPjJrHww1LyZN1zpU7Znt88g9N8eejDuOjDg9iP038P+INH8UaRDrmhTrcWs67kdf1BHUEdCDyDUNWPrsFjo4mPZ9Uf//S+tKKKK6z8/CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSSRwxtLKwVVGSTwABSTTRW8TTzsERBkseABXhHi3xfLrchsrIlLVT9C5Hc+3oPz9nGNzOpVUFdkvi/xjJrDmw08lbVTyehkI7n29B+ftwNFFbJWPNnNyd2FFFFMkKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvWvhP8W9b+F+r+bBm40+dh9otieG7bk/uuB379D2x5LRSLp1JU5KcHZo//0/rSiiius/PwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtYWublgiIMsx6AU26ureyt3urpwkaDJY14H4q8V3GvzeTDmO1Q/Kvdvdv8O1OMbmVWqoIk8WeLZtdlNrbZS1Q8Du59T/AEFcXRRWyVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/9T60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKKKKACq15eW2n2z3d44SNBkk0y/v7XTbV7y9cJGg5J/kPU18/eJfE114hucnKW6H5I/6n1P8qqMbmVWqoLzJPFHim58QXGxcx2yH5E9fdvf+VcpRRWqVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKo6jqNppVo17etsRfzJ9B6mm6pqlnpFm17ettReg7k+gHrXz34h8Q3niC786c7Y1+5GOij+p9TVRjcxq1lBeY/xH4ku/EN1vk+SFD8kfYe59TXOUUVqedKTbuwooopiCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9b60oqRYZX+4pP0FWV03UX+5byH6Kf8K6z4CzKVFay6Drj/AHLKc/SNv8KsJ4V8Tv8Ac026P0hf/CgfJLsYNFdOngvxc/TTbn8Y2H8xVhPAHjN+mnTfiMfzoH7KfZnIUV3C/Dbxu/TT3/FkH82qyvws8dt/y44+skf/AMVQV7Cp/K/uPPqK9JT4S+OG62yL9ZE/oTVlfg94zbqkK/WQf0BosP6vU/lZ5bRXra/Bjxc3V7Zfq7f0U1YX4JeKD9+4tR/wJz/7JRYf1Wr/ACnjlZmravZaLZte3rYUcADqx9BXpXjnwZH8PNCfXPEeoQKv3Y4k3GSV/wC6gIH4noB1r4t1vXL3Xrw3V2cAcIg6KPQf1PeqjG5y4mTo+7Jaj9e1+91+8NzcnCDhEHRR/j6msOiitTy223dhRRRTEFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/Z",width:384,height:256},{id:"sample.photo.2",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/ayiiivVAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9rKKKK9UAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0f2sooor1QCiiig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8fsv8As+p7/TrdOm5uyE3Y9G8d/tC+JLjwy3gDQp8RDMct2pPmNH08pT/d7FupHHTr8v0UV6FKjGmrQRlKbluFFFFakhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABX1N8Bf2g7rwDNH4V8WO02iucI/LPbE9x3MfqvbqO4PyzRWVWjGrHkmioTcHzRP3Us7y11C1jvrGRZoZlDo6EMrKRkEEcEEVYr8tvgV8fL/AOG10ugeIGe40OVuV6tbknl09V7sv4jnIP6eabqVhrFhDqmlTJcW86h45EOVZT0INfMYrCyoSs9u561Ksqiui7RRRXKan//R+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApGZUUu5wBySe1NkkSJDJIQqqMkngADua+f8Axv46fWGbStJYrag4Zuhk/wDsf51dOm5uyJbsT+OPHbamX0jR2xbDh5B1k9h/s/z+leV0UV6UIKKsjJu4UUUVYgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvoL4IfHTVfhdfjTNS3XWiztmSHq0RPWSPPf1Xo3sea+faKzq0o1IuE1oVGbi+aJ+5Gi61pXiLS4Na0SdLm1uF3xyIcgj+hHQg8g8HmtSvyU+DHxs1r4Vap5Em660i4bM9tnkHp5keeA47jow4PYj9UPDviPRfFmjQa/4fnW5tbhdyOv6gjqCDwQeQa+ZxeElQl5Hq0ayqLzP//S+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACo5ZYoI2mmYIiDLMTgADuaSeeG2ha4uGCIgyzHgACvnbxp42m1+Q2NgSlmp+hkI7n29B+J9tKVJzdkTKViXxt44k1x203TSUtFPJ6GQjuf9n0H4n284oor0oxUVZGLdwoooqgCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr2H4QfGLXvhTrPm2+bjTZ2H2m1J4btvT+64Hfv0PbHj1FROEZxcZrQcZOLuj//T+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKgubm3s7d7q6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joo/x9TXP0UV6aSSsjAKKKKYBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//Z",width:384,height:256},{id:"sample.photo.3",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fave3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDTt1AnooopAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9vKKKK7T0wooooAKKKKACiiigAooooAKKKKACs/VNUsNGsX1HUpBFDGMkn+Q9Sewqtruvab4c099S1STYi8AfxMeyqO5NfInjDxnqfi++865PlwIf3UIPCj1Pq3qa3o0XUfkXCHMX/HHjy/8AF115SZhsoz+7iz1/2m9T+g/U6/w38fv4buRpWqMTYSnr18pj3H+ye4/Ed8+U0V6DpR5eS2h0cqtY/QJHSVBJGQysMgjkEHuKdXzT8MPiF/Zjp4c1t/8ARmOIZGP+rJ/hP+ye3p9On0tXmVKbg7M5pR5XYKKKKzJCiiigAooooAKKKKACiiigAooooAKKKKACiiigApkkiRIZJDtUckmn1xXiK/aSb7DGflTlvc//AFqmcuVXPJzrNYZbhpYiau9ku7C/8RTSMY7H5F/vHqf8K52SeaY5ldmPuc1FRXHKTe5+LY/NsVjpOeIm35dF6IljnmhOYnZT7HFdFYeIpo2Ed986/wB4dR/jXMUURk1sGAzbFYGSnh5teXR+qPWY5ElQSRncp5BFPrivDt+0c32GQ/K/K+x/+vXa12QlzK5+05LmsMyw0cRBWezXZhRRRVHrBRRRQAUUUUAf/9P9vKKKK7T0wooooAKKKKACiiigAooooAK5vxP4p0vwpp5vtRbLHiOM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dxc67nltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AAJz/wCyUvbw7hzx7njlZesaxY6JZNe3zYUcADqx9APWvSvHfg6P4daE+u+JNQgVfuxxJuMkr/3UBAz7noB1r4j13Xr7xBem7vDgDhEHRR6D+p710UIqpqtjejT9pr0JPEHiC+8Q3hubo7UXhIx0Uf4+prBoorvStojvSS0QUUUUxhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//2Q==",width:384,height:256},{id:"sample.photo.4",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fave3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDQO3UnooooEFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9uKKKK5z1QooooAKKKKACiiigAooooAKKKKACs/VNUsNGsX1HUpBFDGMkn+Q9Sewqtruvab4c099S1STYi8AfxMeyqO5NfInjDxnqfi+9865PlwIf3UIPCj1Pq3qaaR0UKDqPyL3jjx5f+LrrykzDZRn93Fnr/tN6n9B+p2Phv4/fw3cjStUYmxlbr18pj3H+ye4/Ed8+U0U7HqOlFx5LaH6BI6SoJIyGVhkEcgg9xTq+afhh8Q/7MdPDmtv/AKMxxDIx/wBWT/CT/dPb0+nT6WqTyKtJ05WYUUUUGQUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFRTzw20LXFwwREGWY9AKlrxX4i6+9xd/2HbtiOLBkx/E3UD6Afr9K78twEsbWVGO3V9kcOY46ODoutLfou7DX/iLeXDtb6H+5jHHmEZZvoDwB+v0rzu5vr28YvdzPKT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6X4h0yHWdFnW5tbhd8ciHII/oR0IPIPBrTr8o/g58Z9Z+Fup+TJuudJnbM9vnkHp5keeA47jow4PYj9QvD3iHRvFWjw69oE63NrcLuR1/UEdQQeCDyDTTPlMbgpYeXddGf/9L60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSyxwxtNMwVFGSTwAB3NNnnhtoWuLhgiIMsx4AAr5+8Y+M5tekNlYkpaKfoXI7n29B+J9k3Y2o0XUdkS+MvGsmtO2nacSlop5PQyEdz7eg/E155RRWbdz1YQUFyxCiiikWFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABXrvwk+L2ufCzWPNt83GnTsPtNqTw3ben91wO/foe2PIqKDOpTjUi4TV0f/T+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtIHublwkaDLMegFNu7u2sbZ7u7cRxoMsx7V87+LfF9z4in8iHMdoh+VO7H+839B2pN2NqNF1H5EvjDxjP4gmNra5jtEPC93I7t/QVw1FFZtnqwgorliFFFFIsKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9T60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAqre3trp1q95euI40GST/nrTNQ1C00u0e9vnCRoOSf5D1Jr5y8U+KrvxJdZOY7dD+7j/qfU/wAqTdjejRdR+RL4r8WXXiO52LmO1Q/Inr/tN7/yrkKKKzPVjFRVkFFFFIoKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP//V+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAqhqep2ekWb318+yNPzJ9AO5NM1XVrLRbJr6/fai9B3Y9gB3NfN/iPxJe+I7zz7j5Yl/wBXGOij+p9TUt2OihQdR+RJ4m8T3niO78yT5IEP7uPsPc+prmaKKg9SMVFWQUUUUigooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/W+tKKkWKV/uKT9BVlNO1CT7kEjfRT/hWR9rcpUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf8AwoFzLuYNFdMvgvxc/TTbn8Y2H8xVlfAPjJ+mnTfiMfzoF7SPc5Ciu4X4b+N36ae/4sg/masL8LfHb/8ALjj6yR//ABVIXtYfzI8/or0lPhL44brbIv1kT+hqynwf8Zt1SFfrIP6A0C9tD+ZHltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AnP8A7JQL6xT/AJjxysrWNZsdDsmvr5sKOAB1Y+gHrXpXjvwfF8OdBfXfEmoQKv3Yok3GSV/7qAgZ9z0A618Q69r194gvTd3hwBwiDoo9B/U96TdjrwtNVveWw/xB4hvvEV6bm6O1F4SMdFH+PqawaKKg9dJJWQUUUUhhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/9k=",width:384,height:256}],unavailableCount:0,fetchedAt:zt,source:"system",stale:!1}},{id:"$calendar.isAvailable",group:"calendar",value:!0},{id:"$calendar.authorizationStatus",group:"calendar",value:"authorized"},{id:"$calendar.requestAuthorization",group:"calendar",value:!0},{id:"$calendar.calendars",group:"calendar",value:[{id:"sample.personal",title:"Personal"}]},{id:"$calendar.events",group:"calendar",value:{status:"ready",items:[{id:"sample.event",calendarID:"sample.personal",title:"Read and recharge",start:"2026-01-01T15:00:00Z",end:"2026-01-01T15:30:00Z",allDay:!1}],fetchedAt:zt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.isAvailable",group:"reminders",value:!0},{id:"$reminders.authorizationStatus",group:"reminders",value:"authorized"},{id:"$reminders.requestAuthorization",group:"reminders",value:!0},{id:"$reminders.lists",group:"reminders",value:[{id:"sample.reminders",title:"Personal"}]},{id:"$reminders.items",group:"reminders",value:{status:"ready",items:[{id:"sample.reminder",listID:"sample.reminders",title:"Read a chapter",due:"2026-01-01T16:00:00Z",hasTime:!0,completed:!1,completedAt:null,priority:0}],fetchedAt:zt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.create",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.update",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.setCompleted",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$health.authorizationStatus",group:"health",value:"notDisclosed"},{id:"$health.sleepSummary",group:"health",value:{start:ca,end:zt,timeZone:"UTC",hasSamples:!0,totalSleepSeconds:27e3,inBedSeconds:30600,awakeSeconds:1800,stages:{unspecified:0,core:16200,deep:5400,rem:5400},sourceCount:1,truncated:!1,conflictSeconds:0,aggregation:"union-awake-rem-deep-core-unspecified"}},{id:"$health.activitySummary",group:"health",value:{date:"2026-01-01",timeZone:"UTC",hasSamples:!0,moveMode:"activeEnergy",move:{value:480,goal:600,unit:"kcal"},exercise:{value:26,goal:30,unit:"min"},stand:{value:9,goal:12,unit:"count"}}},{id:"$health.workouts",group:"health",value:{start:ca,end:zt,timeZone:"UTC",hasSamples:!0,truncated:!1,items:[{id:"550e8400-e29b-41d4-a716-446655440000",activity:"running",start:"2026-01-01T09:00:00.000Z",end:"2026-01-01T09:45:00.000Z",duration:2700,energyKcal:285,distanceMeters:5200}]}},{id:"$health.isAvailable",group:"health",value:!0},{id:"$health.requestAuthorization",group:"health",value:!0,legacy:["health"]},{id:"$health.stepCountToday",group:"health",value:lo(6840,"count"),legacy:["health.stepCountToday"]},{id:"$health.activeEnergyToday",group:"health",value:lo(420,"kcal"),legacy:["health.activeEnergyToday"]},{id:"$health.heartRateLatest",group:"health",value:lo(72,"bpm"),legacy:["health.heartRateLatest"]},{id:"$location.isAvailable",group:"location",value:!0},{id:"$location.authorizationStatus",group:"location",value:"authorizedWhenInUse"},{id:"$location.isAuthorizedForWidgetUpdates",group:"location",value:!0},{id:"$location.requestAuthorization",group:"location",value:!0,legacy:["location.authorization"]},{id:"$location.current",group:"location",value:{latitude:37.3349,longitude:-122.009,altitude:0,accuracy:10,verticalAccuracy:10,speed:-1,course:-1,timestamp:zt,accuracyAuthorization:"full",age:0,isStale:!1},legacy:["location"]}],AS={music:{platforms:["ios"],authorization:"musicRead",notes:"Runtime 1.4. Read-only Music app playback, not every audio player. Requires an installed owner, music permission and Music library approval in native Settings. current() is asynchronous and returns provider, state, hasItem, nullable title/artist/album/duration/position and capturedAt. State may be playing while details are absent (Home Sharing). Native player access is main-thread-only: synchronous hosts prepare one snapshot before JSC waits; background previews capture on the main queue. No playback/queue mutation, scans, artwork, credential or subscription inference. No live queries in future entries/Live Activities. Main system-player API is unavailable on macOS; Web supplies editable samples, never actual device access."},services:{platforms:["ios","macos"],authorization:"serviceAccount",notes:"Runtime 1.4: status(service) and profile(service) are asynchronous. Only provider: github. Unknown providers reject with service_operation. Requires an installed owner and services permission. profile additionally requires network and api.github.com in networkDomains, a native connected GitHub account and explicit owner grant. Native Settings handles credentials; scripts cannot log in or obtain tokens. profile returns service, subject, username, displayName, publicRepositories, privateRepositories, followers and following (missing values are null). No live queries in future entries or Live Activities. Eight shared data queries; native requests also share the eight concurrent/32 total network budget, while Web uses its existing preview network budget. Web uses editable best-state samples only; it never authenticates or sends these requests."},photos:{platforms:["ios","macos"],authorization:"photosRead",notes:"Requires photos permission and explicit native photo/album selection (none by default). Limited Photos authorization is supported. items({limit:1..4,offset:0..63,maxAgeSeconds:0..86400}) returns bounded, metadata-stripped JPEG thumbnails as image data URLs. Four 768px / 128KiB thumbnails at most; private snapshots expire after 24h and are rechecked against current access, selected sources and asset revisions. Cloud-only items report unavailableCount; download them in Photos first. Future timeline/Live Activity presentations read matching snapshots only. Web uses editable sample data and photosSelection IDs; no actual library access."},reminders:{platforms:["ios","macos"],authorization:"remindersRead",notes:"Requires reminders in widget.json and full system Reminders access. Reads require native Settings selected lists. create/update/setCompleted additionally require remindersWrite and a native declared action, stable requestID, durable replay receipts and an unchanged selected list. Web writes update preview-only items/receipts; receipt identities are derived from that state, with configurable API errors. Use lists() for IDs. items() selects pending due dates or completed completion dates in a positive window of at most 31 days, up to 50 items. Undated pending reminders are excluded. remindersSelection mocks the user scope without granting permission."},calendar:{platforms:["ios","macos"],authorization:"calendarRead",notes:"Requires calendar in widget.json and full system Calendar access. The user's native Settings source selection limits metadata, events and cached snapshots; scripts cannot enlarge it. Use calendars() for permitted IDs and show setup when no sources are selected. Queries are read-only, limited to 31 days and 50 items. Preview calendarSelection simulates this scope without granting package permission."},device:{platforms:["ios","macos"],authorization:"none",notes:"Device values depend on hardware. Some legacy Mac values are placeholders; inspect the API documentation before using them as measurements."},system:{platforms:["ios","macos"],authorization:"none",notes:"System metadata, not whole-device CPU, FPS or network traffic monitoring. Hardware-specific values may be unavailable."},health:{platforms:["ios"],authorization:"healthRead",notes:"Read-only HealthKit. Request access in the app. Runtime 1.4 adds sleepSummary (up to 7 days / 256 samples, union with explicit stage-conflict precedence), activitySummary (one local Gregorian day including active-energy or move-time mode and optional goals), and workouts (up to 31 days / 50 fully-contained summaries, optional kcal/meters). These require an explicit health manifest; all share the query budget and cannot run in future/Live Activity presentations. No Health readings are persisted by the API. Authorization completion does not reveal whether individual read types were granted; empty results must not be labelled permission denied. API 1.3 readings add hasSamples: false means no readable samples, never a read-denial verdict. Existing value/unit/start/end fields remain."},location:{platforms:["ios"],authorization:"locationWhenInUse",notes:"Package 2.0 requires location permission. Request system access in the app. Widgets also require isAuthorizedForWidgetUpdates. Cache is rechecked against authorization and precision, discarded after 24 hours or revocation, and reports age/isStale."}},bS=[...yS.map(n=>{const e=n.id.split(".")[1],t=n.group==="music"&&e==="current"||n.group==="services"||["calendar","reminders","photos"].includes(n.group)&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="health"&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e),i=n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e)||["calendar","reminders","photos"].includes(n.group)&&["events","items"].includes(e);return{...n,...AS[n.group],minimumRuntimeVersion:["music","services","reminders","photos"].includes(n.group)||n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)?"1.4":["calendar"].includes(n.group)||["$health.authorizationStatus","$location.isAuthorizedForWidgetUpdates"].includes(n.id)?"1.3":"1.0",arguments:n.group==="services"?["service"]:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?["options"]:i?["options?"]:[],...n.group==="reminders"&&["create","update","setCompleted"].includes(e)?{authorization:"remindersWrite"}:{},asynchronous:t,nativeSource:`Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntime${n.group[0].toUpperCase()}${n.group.slice(1)}.swift`,operation:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?"write":e==="requestAuthorization"?"authorization":["isAvailable","authorizationStatus","isAuthorizedForWidgetUpdates"].includes(e)?"availability":"read",mock:"editable"}}),...OS],$e={globalProperties:{background:{type:"color",documentation:"Background color, hex value, or named color."},backgroundMaterial:{type:"enum",values:["none","ultraThin","thin","regular","thick","ultraThick"],documentation:"Runtime API 1.4. Public SwiftUI frosted material inside the widget, not Home Screen wallpaper blur or system Liquid Glass. At most four material backgrounds per tree. background supplies an opaque-composited Reduce Transparency fallback. In accented/vibrant mode local material is omitted for system rendering; none keeps the ordinary background."},color:{type:"color",documentation:"Foreground color, hex value, or named color."},font:{type:"enum",values:["largeTitle","title","title2","title3","headline","subheadline","body","callout","footnote","caption","caption2"],documentation:"Semantic text style."},fontWeight:{type:"enum",values:["ultraLight","thin","light","regular","medium","semibold","bold","heavy","black"],documentation:"Font weight."},fontDesign:{type:"enum",values:["default","rounded","serif","monospaced"],documentation:"Font design."},frame:{type:"number|string",documentation:'Square size (64 or "64"), width,height ("64,48"), or flexible frame ("max", "max,48").'},padding:{type:"number|string",documentation:"Padding amount or edge description."},corner:{type:"number",documentation:"Corner radius."},opacity:{type:"number",documentation:"Opacity from 0 through 1."},alignment:{type:"enum",values:["center","leading","trailing","top","bottom","topLeading","topTrailing","bottomLeading","bottomTrailing","firstTextBaseline","lastTextBaseline"],documentation:"Layout alignment."},clip:{type:"enum",values:["circle","rect","capsule","ellipse"],documentation:"Clip the view to a shape."},rotation:{type:"number",documentation:"Rotation in degrees."},rotation3d:{type:"string",documentation:"Static degree,x,y,z rotation with four finite numbers and a nonzero axis. Invalid values are ignored; axis magnitude is normalized. Reduce Motion removes the tilt. This does not read device motion or provide parallax."},shadow:{type:"string",documentation:"Shadow color, radius, and offset description."},animation:{type:"string",documentation:"iOS public SwiftUI scheduled clock/swing effect. Mac renders static standard-clock poses; other effects remain at rest. Signed clockCustom intervals specify a half-turn (full cycle = 2 * abs(interval)), minimum magnitude 0.25 seconds. App previews can animate; WidgetKit decides cadence and may freeze. Reduced motion/luminance freezes standard clock poses and keeps custom/swing effects at rest. Dynamic scripts are not rerun on animation ticks."},widgetAccentable:{type:"boolean",documentation:"Group this view into the accent layer in tinted and vibrant widget appearances."},linkurl:{type:"url",documentation:"Widget deep link URL."}},components:{VStack:{documentation:"Arrange children vertically.",children:!0,properties:{spacing:{type:"number"}}},HStack:{documentation:"Arrange children horizontally.",children:!0,properties:{spacing:{type:"number"}}},ZStack:{documentation:"Overlay children.",children:!0,properties:{}},VGrid:{documentation:"Vertical lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["leading","center","trailing"]}}},HGrid:{documentation:"Horizontal lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["top","center","bottom","firstTextBaseline","lastTextBaseline"]}}},Text:{documentation:"Display text content.",children:!1,properties:{text:{type:"string"}}},Date:{documentation:"Display a formatted date.",children:!1,properties:{date:{type:"date|number",required:!0},style:{type:"enum",values:["time","date","relative","offset","timer"]}}},Image:{documentation:"Display a bundled, remote, or SF Symbol image.",children:!1,properties:{systemName:{type:"string"},name:{type:"string"},id:{type:"string",deprecated:"Use name."},url:{type:"url"},src:{type:"url",deprecated:"Use url."},ratio:{type:"number"},mode:{type:"enum",values:["fit","fill"]},accentedRenderingMode:{type:"enum",values:["accented","desaturated","accentedDesaturated","fullColor"],documentation:"Control how the image is rendered in tinted and clear widget appearances."}}},Gif:{documentation:"Display a bounded package GIF using system decoding: up to 8 MiB input and 1,048,576 canvas pixels. iOS retains at most 60 downsampled frames / 4 MiB decoded pixels; more frames fall back to the first frame. Mac, Reduce Motion and reduced luminance use a static first frame. Active iOS previews use public SwiftUI timing with variable frame delays. Snapshots, inactive scenes, Mac and accessibility fallbacks use the first frame. No private clock bridge or continuous WidgetKit guarantee.",children:!1,properties:{file:{type:"string",required:!0}}},Spacer:{documentation:"Flexible layout space.",children:!1,properties:{minLength:{type:"number"}}},Rect:{documentation:"Rectangle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},RoundedRect:{documentation:"Filled rounded rectangle.",children:!1,properties:{radius:{type:"number"}}},Capsule:{documentation:"Capsule shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Ellipse:{documentation:"Ellipse shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Circle:{documentation:"Circle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Gauge:{documentation:"Display a gauge or instrument.",children:!1,properties:{type:{type:"string"},value:{type:"number"},style:{type:"enum",values:["circular","linear"]},text:{type:"string"},current:{type:"string"},min:{type:"string"},max:{type:"string"},angle:{type:"number"},thickness:{type:"number"},needleColor:{type:"color"},label:{type:"string"},title:{type:"string"},sections:{type:"string"}}},Chart:{documentation:"Render chart data.",children:!1,availability:{ios:"16.0",macos:"26.0"},properties:{type:{type:"enum",values:["bar","bar-x","bar-y","bar-gantt","line","point","line-point","area","rect","rule-x"]},data:{type:"json",required:!0},category:{type:"boolean"},hideLegend:{type:"boolean"},hideXAxis:{type:"boolean"},hideYAxis:{type:"boolean"}}},Link:{documentation:"Open a URL when selected.",children:!0,properties:{url:{type:"url",required:!0}}},Divider:{documentation:"Horizontal or vertical separator.",children:!1,properties:{thickness:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Line:{documentation:"Fixed-length line.",children:!1,properties:{thickness:{type:"number"},length:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Icon:{documentation:"SF Symbol icon.",children:!1,properties:{systemName:{type:"string",required:!0},size:{type:"number"}}},Label:{documentation:"Text paired with an SF Symbol.",children:!1,properties:{title:{type:"string"},systemName:{type:"string",required:!0}}},Progress:{documentation:"Linear or circular progress.",children:!1,properties:{value:{type:"number",required:!0},total:{type:"number"},label:{type:"string"},style:{type:"enum",values:["linear","circular"]},trackColor:{type:"color"},thickness:{type:"number"}}},Ring:{documentation:"Circular progress ring.",children:!1,properties:{value:{type:"number",required:!0},thickness:{type:"number"},trackColor:{type:"color"}}},Badge:{documentation:"Compact status badge.",children:!1,properties:{text:{type:"string"},radius:{type:"number"}}},Chip:{documentation:"Outlined metadata chip.",children:!1,properties:{text:{type:"string"},radius:{type:"number"},borderColor:{type:"color"}}},Stat:{documentation:"Title, value, and subtitle statistic.",children:!1,properties:{title:{type:"string"},value:{type:"string",required:!0},subtitle:{type:"string"},mutedColor:{type:"color"}}},Button:{documentation:"Interactive widget button. Use actionID to share a declared Package 2.0 action with Siri, Shortcuts, and Control Widgets.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["action","onClick","actionID"],properties:{action:{type:"enum",values:["reload"],conflicts:["actionID"]},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",conflicts:["action","onClick"]}}},Toggle:{documentation:"Interactive widget toggle. A declared actionID requires a package-relative storage stateKey.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["onClick","actionID"],properties:{on:{type:"boolean",required:!0},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",requires:["stateKey"],conflicts:["onClick"]},stateKey:{type:"storage-key",requires:["actionID"]}}}},functions:{...Object.fromEntries(gS.map(n=>[n.id,n])),...Object.fromEntries(bS.map(n=>[n.id,{documentation:n.notes,minimumRuntimeVersion:n.minimumRuntimeVersion,arguments:n.arguments,returns:n.asynchronous?"Promise<json>":typeof n.value=="object"?"json":typeof n.value}])),"$icloud.readJSON":{documentation:"Read cached JSON and revision; conflicts preserve all heads. Requires icloud permission and a native connection. Never certifies upload.",arguments:["name"],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.writeJSON":{documentation:"Save a new immutable JSON revision locally from a user action. Requires the revision from readJSON. Background exchange is eventual.",arguments:["name","value","expectedRevision"],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.resolveJSON":{documentation:"Explicitly resolve all observed conflicting heads into a new revision. Stale tokens fail; originals remain.",arguments:["name","value","expectedRevision"],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.sync":{documentation:"Exchange materialized revisions with iCloud; requires a user action. Upload completion is unknown.",arguments:[],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.status":{documentation:"Read native connection state. In the app, explicitly connect packages to separate stores for isolation or the same store ID to share JSON documents. Scripts cannot choose store IDs. Sync is eventual; local $storage is not migrated. Web uses preview mocks.",arguments:[],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$file.exists":{documentation:"Return whether a regular file is locally present inside this package, including binary assets. Missing files, directories, unsafe paths and links return false. Does not download iCloud files or read outside the package. Web preview uses workspace file presence.",arguments:["path"],returns:"boolean",minimumRuntimeVersion:"1.3"},"$file.read":{documentation:"Read package-relative UTF-8 text. Missing or unavailable files return an empty string.",arguments:["path"],returns:"string"},"$file.readJSON":{documentation:"Read a package-relative JSON object.",arguments:["path"],returns:"json"},fetch:{documentation:"Perform a network request and return its response text. Existing HTTP methods keep this string result."},"$http.getResponse":{documentation:"GET response metadata: {status, body, headers}. Headers are limited to content-type, cache-control, expires, last-modified, date and retry-after (lowercase; each at most 2048 UTF-8 bytes). Network permissions, public-host policy, redirects, body limits and timeline restrictions still apply. HTTP error statuses resolve; transport errors reject.",arguments:["url","options?"],returns:"Promise<json>",minimumRuntimeVersion:"1.3"},importJS:{documentation:"Import a package-relative JavaScript file."},"$dataSource.request":{documentation:"Call a declared Data Source Plugin operation. Requires Package 2.0 plugins, network permission, and networkDomains declarations.",arguments:["pluginID","operationID","parameters"],returns:"Promise<json|string>"},"$xml.parse":{documentation:"Parse up to 256 KiB of XML into {name, attributes, text, children}. DTDs and external entities are rejected; depth and node limits apply.",arguments:["source"],returns:"XMLNode"}}};function SS(n,e){const t=Object.entries(e.properties??{}).filter(([,s])=>s.required).map(([s,r])=>`${s}=${r.type.includes("number")||r.type==="boolean"?"{${}}":'"${}"'}`).join(" "),i=t?` ${t}`:"";return e.children?`<${n}${i}> +}`,{label:"class",detail:"definition",type:"keyword"}),Ye('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ye('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],mb=hd.concat([Ye("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Ye("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Ye("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Jc=new yO,ud=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const gb=["FunctionDeclaration"],Ob={FunctionDeclaration:cn("function"),ClassDeclaration:cn("class"),ClassExpression:()=>!0,EnumDeclaration:cn("constant"),TypeAliasDeclaration:cn("type"),NamespaceDeclaration:cn("namespace"),VariableDefinition(n,e){n.matchContext(gb)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function fd(n,e){let t=Jc.get(e);if(t)return t;let i=[],s=!0;function r(o,a){let l=n.sliceString(o.from,o.to);i.push({label:l,type:a})}return e.cursor(be.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let a=Ob[o.name];if(a&&a(o,r)||ud.has(o.name))return!1}else if(o.to-o.from>8192){for(let a of fd(n,o.node))i.push(a);return!1}}),Jc.set(e,i),i}const eh=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,dd=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function yb(n){let e=Ce(n.state).resolveInner(n.pos,-1);if(dd.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&eh.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)ud.has(s.name)&&(i=i.concat(fd(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:eh}}const Bt=Is.define({name:"javascript",parser:pb.configure({props:[rf.add({IfStatement:Gr({except:/^\s*({|else\b)/}),TryStatement:Gr({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:LO,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:DO({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Gr({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),lf.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":WO,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),pd={test:n=>/^JSX/.test(n.name),facet:nf({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Ab=Bt.configure({dialect:"ts"},"typescript"),bb=Bt.configure({dialect:"jsx",props:[Ua.add(n=>n.isTop?[pd]:void 0)]}),Sb=Bt.configure({dialect:"jsx ts",props:[Ua.add(n=>n.isTop?[pd]:void 0)]},"typescript");let md=n=>({label:n,type:"keyword"});const gd="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(md),xb=gd.concat(["declare","implements","private","protected","public"].map(md));function vb(n={}){let e=n.jsx?n.typescript?Sb:bb:n.typescript?Ab:Bt,t=n.typescript?mb.concat(xb):hd.concat(gd);return new RO(e,[Bt.data.of({autocomplete:My(dd,_f(t))}),Bt.data.of({autocomplete:yb}),n.jsx?Qb:[]])}function wb(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function th(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const kb=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Qb=K.inputHandler.of((n,e,t,i,s)=>{if((kb?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!Bt.isActiveAt(n.state,e,-1))return!1;let r=s(),{state:o}=r,a=o.changeByRange(l=>{var c;let{head:h}=l,u=Ce(o).resolveInner(h-1,-1),f;if(u.name=="JSXStartTag"&&(u=u.parent),!(o.doc.sliceString(h-1,h)!=i||u.name=="JSXAttributeValue"&&u.to>h)){if(i==">"&&u.name=="JSXFragmentTag")return{range:l,changes:{from:h,insert:"</>"}};if(i=="/"&&u.name=="JSXStartCloseTag"){let d=u.parent,p=d.parent;if(p&&d.from==h-2&&((f=th(o.doc,p.firstChild,h))||((c=p.firstChild)===null||c===void 0?void 0:c.name)=="JSXFragmentTag")){let m=`${f}>`;return{range:A.cursor(h+m.length,-1),changes:{from:h,insert:m}}}}else if(i==">"){let d=wb(u);if(d&&d.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(h,h+2))&&(f=th(o.doc,d,h)))return{range:l,changes:{from:h,insert:`</${f}>`}}}}return{range:l}});return a.changes.empty?!1:(n.dispatch([r,o.update(a,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),ih=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n;class Yi{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?a=>r(ih(a)):ih,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Ne(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=ma(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Qt(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,a=!0;;r++){let l=s.charCodeAt(r),c=this.match(l,o,a,this.bufferPos+this.bufferStart,r==s.length-1);if(c)return this.value=c,this;if(r==s.length-1)break;a&&r<t.length&&t.charCodeAt(r)==l?o++:a=!1}}}match(e,t,i,s,r){let o=null;for(let a=0;a<this.matches.length;){let l=this.matches[a],c=!1;this.query.charCodeAt(l.index)==e&&(l.index==this.query.length-1?o={from:l.from,to:s,precise:r&&l.precise}:(l.index++,c=!0)),c?a++:this.matches.splice(a,1)}return this.query.charCodeAt(0)==e&&(this.query.length==1?o={from:t,to:s,precise:i&&r}:this.matches.push({from:t,index:1,precise:i})),o&&this.test&&!this.test(o.from,o.to,this.buffer,this.bufferStart)&&(o=null),o}}typeof Symbol<"u"&&(Yi.prototype[Symbol.iterator]=function(){return this});const Od={from:-1,to:-1,match:/.*/.exec(""),precise:!0},_a="gm"+(/x/.unicode==null?"":"u");class yd{constructor(e,t,i,s=0,r=e.length){if(this.text=e,this.to=r,this.curLine="",this.done=!1,this.value=Od,/\\[sWDnr]|\n|\r|\[\^/.test(t))return new Ad(e,t,i,s,r);this.re=new RegExp(t,_a+(i?.ignoreCase?"i":"")),this.test=i?.test,this.iter=e.iter();let o=e.lineAt(s);this.curLineStart=o.from,this.matchPos=er(e,s),this.getLine(this.curLineStart)}getLine(e){this.iter.next(e),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=er(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(i<s||i>this.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),e=0;else return this.done=!0,this}}}const lo=new WeakMap;class Li{constructor(e,t){this.from=e,this.text=t}get to(){return this.from+this.text.length}static get(e,t,i){let s=lo.get(e);if(!s||s.from>=i||s.to<=t){let a=new Li(t,e.sliceString(t,i));return lo.set(e,a),a}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.to<i&&(r+=e.sliceString(s.to,i)),lo.set(e,new Li(o,r)),new Li(t,r.slice(t-o,i-o))}}class Ad{constructor(e,t,i,s,r){this.text=e,this.to=r,this.done=!1,this.value=Od,this.matchPos=er(e,s),this.re=new RegExp(t,_a+(i?.ignoreCase?"i":"")),this.test=i?.test,this.flat=Li.get(e,s,this.chunkEnd(s+5e3))}chunkEnd(e){return e>=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=er(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Li.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(yd.prototype[Symbol.iterator]=Ad.prototype[Symbol.iterator]=function(){return this});function Pb(n){try{return new RegExp(n,_a),!0}catch{return!1}}function er(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e<t.to&&(i=t.text.charCodeAt(e-t.from))>=56320&&i<57344;)e++;return e}const Cb=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=_g(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,h,u]=o,f=h?+h.slice(1):0,d=c?+c:a.number;if(c&&u){let g=d/100;l&&(g=g*(l=="-"?-1:1)+a.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else c&&l&&(d=d*(l=="-"?-1:1)+a.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),m=A.cursor(p.from+Math.max(0,Math.min(f,p.length)));n.dispatch({effects:[i,K.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},Tb={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Rb=Z.define({combine(n){return yt(n,Tb,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function $b(n){return[Ub,Eb]}const Kb=I.mark({class:"cm-selectionMatch"}),Zb=I.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function nh(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=ye.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=ye.Word)}function Mb(n,e,t,i){return n(e.sliceDoc(t,t+1))==ye.Word&&n(e.sliceDoc(i-1,i))==ye.Word}const Eb=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(Rb),{state:t}=n,i=t.selection;if(i.ranges.length>1)return I.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return I.none;let l=t.wordAt(s.head);if(!l)return I.none;o=t.charCategorizer(s.head),r=t.sliceDoc(l.from,l.to)}else{let l=s.to-s.from;if(l<e.minSelectionLength||l>200)return I.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(nh(o,t,s.from,s.to)&&Mb(o,t,s.from,s.to)))return I.none}else if(r=t.sliceDoc(s.from,s.to),!r)return I.none}let a=[];for(let l of n.visibleRanges){let c=new Yi(t.doc,r,l.from,l.to);for(;!c.next().done;){let{from:h,to:u}=c.value;if((!o||nh(o,t,h,u))&&(s.empty&&h<=s.from&&u>=s.to?a.push(Zb.range(h,u)):(h>=s.to||u<=s.from)&&a.push(Kb.range(h,u)),a.length>e.maxMatches))return I.none}}return I.set(a)}},{decorations:n=>n.decorations}),Ub=K.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Fb=({state:n,dispatch:e})=>{let{selection:t}=n,i=A.create(t.ranges.map(s=>n.wordAt(s.head)||A.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function Db(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,a=new Yi(n.doc,e,i[i.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new Yi(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(l=>l.from==a.value.from))continue;if(r){let l=n.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const Lb=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return Fb({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=Db(n,i);return s?(e(n.update({selection:n.selection.addRange(A.range(s.from,s.to),!1),effects:K.scrollIntoView(s.to)})),!0):!1},tn=Z.define({combine(n){return yt(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Jb(e),scrollToMatch:e=>K.scrollIntoView(e)})}});class bd{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||Pb(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` +`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new zb(this):new Ib(this)}getCursor(e,t=0,i){let s=e.doc?e:J.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Pi(this,s,t,i):Qi(this,s,t,i)}}class Sd{constructor(e){this.spec=e}}function Xb(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let a=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(a,e,i,s)}}function Qi(n,e,t,i){let s;return n.wholeWord&&(s=Bb(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=Xb(n.test,e,s)),new Yi(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function Bb(n,e){return(t,i,s,r)=>((r>t||r+s.length<i)&&(r=Math.max(0,t-2),s=n.sliceString(r,Math.min(n.length,i+2))),(e(tr(s,t-r))!=ye.Word||e(ir(s,t-r))!=ye.Word)&&(e(ir(s,i-r))!=ye.Word||e(tr(s,i-r))!=ye.Word))}class Ib extends Sd{constructor(e){super(e)}nextMatch(e,t,i){let s=Qi(this.spec,e,i,e.doc.length).nextOverlapping();if(s.done){let r=Math.min(e.doc.length,t+this.spec.unquoted.length);s=Qi(this.spec,e,0,r).nextOverlapping()}return s.done||s.value.from==t&&s.value.to==i?null:s.value}prevMatchInRange(e,t,i){for(let s=i;;){let r=Math.max(t,s-1e4-this.spec.unquoted.length),o=Qi(this.spec,e,r,s),a=null;for(;!o.nextOverlapping().done;)a=o.value;if(a)return a;if(r==t)return null;s-=1e4}}prevMatch(e,t,i){let s=this.prevMatchInRange(e,0,t);return s||(s=this.prevMatchInRange(e,Math.max(0,i-this.spec.unquoted.length),e.doc.length)),s&&(s.from!=t||s.to!=i)?s:null}getReplacement(e){return this.spec.unquote(this.spec.replace)}matchAll(e,t){let i=Qi(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Qi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}function Wb(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Pi(n,e,t,i){let s;return n.wholeWord&&(s=qb(e.charCategorizer(e.selection.main.head))),n.test&&(s=Wb(n.test,e,s)),new yd(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function tr(n,e){return n.slice(Ze(n,e,!1),e)}function ir(n,e){return n.slice(e,Ze(n,e))}function qb(n){return(e,t,i)=>!i[0].length||(n(tr(i.input,i.index))!=ye.Word||n(ir(i.input,i.index))!=ye.Word)&&(n(ir(i.input,i.index+i[0].length))!=ye.Word||n(tr(i.input,i.index+i[0].length))!=ye.Word)}class zb extends Sd{nextMatch(e,t,i){let s=Pi(this.spec,e,i,e.doc.length).next();return s.done&&(s=Pi(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Pi(this.spec,e,r,i),a=null;for(;!o.next().done;)a=o.value;if(a&&(r==t||a.from>r+10))return a;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r<e.match.length)return e.match[r]+i.slice(s)}return t})}matchAll(e,t){let i=Pi(this.spec,e,0,e.doc.length),s=[];for(;!i.next().done;){if(s.length>=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Pi(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}const Zn=Y.define(),Ja=Y.define(),_t=Te.define({create(n){return new co(ca(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Zn)?n=new co(t.value.create(),n.panel):t.is(Ja)&&(n=new co(n.query,t.value?el:null));return n},provide:n=>Vi.from(n,e=>e.panel)});class co{constructor(e,t){this.query=e,this.panel=t}}const Vb=I.mark({class:"cm-searchMatch"}),jb=I.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Yb=xe.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(_t))}update(n){let e=n.state.field(_t);(e!=n.startState.field(_t)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return I.none;let{view:t}=this,i=new It;for(let s=0,r=t.visibleRanges,o=r.length;s<o;s++){let{from:a,to:l}=r[s];for(;s<o-1&&l>r[s+1].from-500;)l=r[++s].to;n.highlight(t.state,a,l,(c,h)=>{let u=t.state.selection.ranges.some(f=>f.from==c&&f.to==h);i.add(c,h,u?jb:Vb)})}return i.finish()}},{decorations:n=>n.decorations});function zn(n){return e=>{let t=e.state.field(_t,!1);return t&&t.query.spec.valid?n(e,t):wd(e)}}const nr=zn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=A.single(i.from,i.to),r=n.state.facet(tn);return n.dispatch({selection:s,effects:[tl(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),vd(n),!0}),sr=zn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=A.single(s.from,s.to),o=n.state.facet(tn);return n.dispatch({selection:r,effects:[tl(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),vd(n),!0}),Nb=zn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:A.create(t.map(i=>A.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),Hb=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let a=new Yi(n.doc,n.sliceDoc(i,s));!a.next().done;){if(r.length>1e3)return!1;a.value.from==i&&(o=r.length),r.push(A.range(a.value.from,a.value.to))}return e(n.update({selection:A.create(r,o),userEvent:"select.search.matches"})),!0},sh=zn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,a=[],l,c,h=[];o.precise?o.from==i&&o.to==s&&(c=t.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(t,o.from,o.to),h.push(K.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let u=n.state.changes(a);return o&&(l=A.single(o.from,o.to).map(u),h.push(tl(n,o)),h.push(t.facet(tn).scrollToMatch(l.main,n))),n.dispatch({changes:u,selection:l,effects:h,userEvent:"input.replace"}),!0}),Gb=zn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:a}=s;a&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:K.announce.of(i),userEvent:"input.replace.all"}),!0});function el(n){return n.state.facet(tn).createPanel(n)}function ca(n,e){var t,i,s,r,o;let a=n.selection.main,l=a.empty||a.to>a.from+100?"":n.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=n.facet(tn);return new bd({search:((t=e?.literal)!==null&&t!==void 0?t:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:c.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:c.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:c.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function xd(n){let e=Bu(n,el);return e&&e.dom.querySelector("[main-field]")}function vd(n){let e=xd(n);e&&e==n.root.activeElement&&e.select()}const wd=n=>{let e=n.state.field(_t,!1);if(e&&e.panel){let t=xd(n);if(t&&t!=n.root.activeElement){let i=ca(n.state,e.query.spec);i.valid&&n.dispatch({effects:Zn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Ja.of(!0),e?Zn.of(ca(n.state,e.query.spec)):Y.appendConfig.of(tS)]});return!0},kd=n=>{let e=n.state.field(_t,!1);if(!e||!e.panel)return!1;let t=Bu(n,el);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Ja.of(!1)}),!0},_b=[{key:"Mod-f",run:wd,scope:"editor search-panel"},{key:"F3",run:nr,shift:sr,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:nr,shift:sr,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:kd,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Hb},{key:"Mod-Alt-g",run:Cb},{key:"Mod-d",run:Lb,preventDefault:!0}];class Jb{constructor(e){this.view=e;let t=this.query=e.state.field(_t).query.spec;this.commit=this.commit.bind(this),this.searchField=he("input",{value:t.search,placeholder:st(e,"Find"),"aria-label":st(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=he("input",{value:t.replace,placeholder:st(e,"Replace"),"aria-label":st(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=he("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=he("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=he("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return he("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=he("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>nr(e),[st(e,"next")]),i("prev",()=>sr(e),[st(e,"previous")]),i("select",()=>Nb(e),[st(e,"all")]),he("label",null,[this.caseField,st(e,"match case")]),he("label",null,[this.reField,st(e,"regexp")]),he("label",null,[this.wordField,st(e,"by word")]),...e.state.readOnly?[]:[he("br"),this.replaceField,i("replace",()=>sh(e),[st(e,"replace")]),i("replaceAll",()=>Gb(e),[st(e,"replace all")])],he("button",{name:"close",onclick:()=>kd(e),"aria-label":st(e,"close"),type:"button"},["×"])])}commit(){let e=new bd({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Zn.of(e)}))}keydown(e){cg(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?sr:nr)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),sh(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Zn)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(tn).top}}function st(n,e){return n.state.phrase(e)}const ds=30,ps=/[\s\.,:;?!]/;function tl(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-ds),o=Math.min(s,t+ds),a=n.state.sliceDoc(r,o);if(r!=i.from){for(let l=0;l<ds;l++)if(!ps.test(a[l+1])&&ps.test(a[l])){a=a.slice(l);break}}if(o!=s){for(let l=a.length-1;l>a.length-ds;l--)if(!ps.test(a[l-1])&&ps.test(a[l])){a=a.slice(0,l);break}}return K.announce.of(`${n.state.phrase("current match")}. ${a} ${n.state.phrase("on line")} ${i.number}.`)}const eS=K.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),tS=[_t,oi.low(Yb),eS];class rh{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class di{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(Kt).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new It,a=[],l=0,c=i.doc.iter(),h=0,u=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!a.length)break;let m,g;if(a.length)m=l,g=a.reduce((b,C)=>Math.min(b,C.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>u)break;g=p.to,a.push(p),d++}for(;d<r.length;){let b=r[d];if(b.from==m&&(b.to>b.from||b.to==m))a.push(b),d++,g=Math.min(b.to,g);else{g=Math.min(b.from,g);break}}g=Math.min(g,u);let y=!1;if(a.some(b=>b.from==m&&(b.to==g||g==u))&&(y=m==g,!y&&g-m<10)){let b=m-(h+c.value.length);b>0&&(c.next(b),h=m);for(let C=m;;){if(C>=g){y=!0;break}if(!c.lineBreak&&h+c.value.length>C)break;C=h+c.value.length,h+=c.value.length,c.next()}}let x=Zd(a);if(y)o.add(m,m,I.widget({widget:new lS(x),diagnostics:a.slice()}));else{let b=a.reduce((C,Q)=>Q.markClass?C+" "+Q.markClass:C,"");o.add(m,g,I.mark({class:"cm-lintRange cm-lintRange-"+x+b,diagnostics:a.slice(),inclusiveEnd:a.some(C=>C.to>g)}))}if(l=g,l==u)break;for(let b=0;b<a.length;b++)a[b].to<=l&&a.splice(b--,1)}let f=o.finish();return new di(f,t,Ni(f))}}function Ni(n,e=null,t=0){let i=null;return n.between(t,1e9,(s,r,{spec:o})=>{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new rh(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new rh(i.from,r,i.diagnostic)}}),i}function Qd(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(Kt).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(Cr))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function iS(n,e){return n.field(gt,!1)?e:e.concat(Y.appendConfig.of(Ud))}function Pd(n,e){return{effects:iS(n,[Cr.of(e)])}}const Cr=Y.define(),Cd=Y.define(),Td=Y.define(),gt=Te.define({create(){return new di(I.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Ni(t,n.selected.diagnostic,r)||Ni(t,null,r)}!t.size&&s&&e.state.facet(Kt).autoPanel&&(s=null),n=new di(t,s,i)}for(let t of e.effects)if(t.is(Cr)){let i=e.state.facet(Kt).autoPanel?t.value.length?rr.open:null:n.panel;n=di.init(t.value,i,e.state)}else t.is(Cd)?n=new di(n.diagnostics,t.value?rr.open:null,n.selected):t.is(Td)&&(n=new di(n.diagnostics,n.panel,t.value));return n},provide:n=>[Vi.from(n,e=>e.panel),K.decorations.from(n,e=>e.diagnostics)]}),nS=I.mark({class:"cm-lintRange cm-lintRange-active"});function sS(n,e,t){let{diagnostics:i}=n.state.field(gt),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(l,c,{spec:h})=>{if(e>=l&&e<=c&&(l==c||(e>l||t>0)&&(e<c||t<0)))return s=h.diagnostics,r=l,o=c,!1});let a=n.state.facet(Kt).tooltipFilter;return s&&a&&(s=a(s,n.state)),s?{pos:r,end:o,above:!0,create(){return{dom:Rd(n,s)}}}:null}function Rd(n,e){return he("ul",{class:"cm-tooltip-lint"},e.map(t=>Kd(n,t,!1)))}const oh=n=>{let e=n.state.field(gt,!1);return!e||!e.panel?!1:(n.dispatch({effects:Cd.of(!1)}),!0)},rS=xe.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(Kt);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){clearTimeout(this.timeout);let n=Date.now();if(n<this.lintTime-10)this.timeout=setTimeout(this.run,this.lintTime-n);else{this.set=!1;let{state:e}=this.view,{sources:t}=e.facet(Kt);t.length&&oS(t.map(i=>Promise.resolve(i(this.view))),i=>{this.view.state.doc==e.doc&&this.view.dispatch(Pd(this.view.state,i.reduce((s,r)=>s.concat(r))))},i=>{ze(this.view.state,i)})}}update(n){let e=n.state.facet(Kt);(n.docChanged||e!=n.startState.facet(Kt)||e.needsRefresh&&e.needsRefresh(n))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}});function oS(n,e,t){let i=[],s=-1;for(let r of n)r.then(o=>{i.push(o),clearTimeout(s),i.length==n.length?e(i):s=setTimeout(()=>e(i),200)},t)}const Kt=Z.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...yt(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:ah,tooltipFilter:ah,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function ah(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function aS(n,e={}){return[Kt.of({source:n,config:e}),rS,Ud]}function $d(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;i<t.length;i++){let s=t[i];if(/[a-zA-Z]/.test(s)&&!e.some(r=>r.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function Kd(n,e,t){var i;let s=t?$d(e.actions):[];return he("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},he("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let a=!1,l=d=>{if(d.preventDefault(),a)return;a=!0;let p=Ni(n.state.field(gt).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:c}=r,h=s[o]?c.indexOf(s[o]):-1,u=h<0?c:[c.slice(0,h),he("u",c.slice(h,h+1)),c.slice(h+1)],f=r.markClass?" "+r.markClass:"";return he("button",{type:"button",class:"cm-diagnosticAction"+f,onclick:l,onmousedown:l,"aria-label":` Action: ${c}${h<0?"":` (access key "${s[o]})"`}.`},u)}),e.source&&he("div",{class:"cm-diagnosticSource"},e.source))}class lS extends Ut{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return he("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class lh{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Kd(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class rr{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)oh(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=$d(r.actions);for(let a=0;a<o.length;a++)if(o[a].toUpperCase().charCodeAt(0)==s.keyCode){let l=Ni(this.view.state.field(gt).diagnostics,r);l&&r.actions[a].apply(e,l.from,l.to)}}else return;s.preventDefault()}},i=s=>{for(let r=0;r<this.items.length;r++)this.items[r].dom.contains(s.target)&&this.moveSelection(r)};this.list=he("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:t,onclick:i}),this.dom=he("div",{class:"cm-panel-lint"},this.list,he("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>oh(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(gt).selected;if(!e)return-1;for(let t=0;t<this.items.length;t++)if(this.items[t].diagnostic==e.diagnostic)return t;return-1}update(){let{diagnostics:e,selected:t}=this.view.state.field(gt),i=0,s=!1,r=null,o=new Set;for(e.between(0,this.view.state.doc.length,(a,l,{spec:c})=>{for(let h of c.diagnostics){if(o.has(h))continue;o.add(h);let u=-1,f;for(let d=i;d<this.items.length;d++)if(this.items[d].diagnostic==h){u=d;break}u<0?(f=new lh(this.view,h),this.items.splice(i,0,f),s=!0):(f=this.items[u],u>i&&(this.items.splice(i,u-i),s=!0)),t&&f.diagnostic==t.diagnostic?f.dom.hasAttribute("aria-selected")||(f.dom.setAttribute("aria-selected","true"),r=f):f.dom.hasAttribute("aria-selected")&&f.dom.removeAttribute("aria-selected"),i++}});i<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new lh(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),r?(this.list.setAttribute("aria-activedescendant",r.id),this.view.requestMeasure({key:this,read:()=>({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:a,panel:l})=>{let c=l.height/this.list.offsetHeight;a.top<l.top?this.list.scrollTop-=(l.top-a.top)/c:a.bottom>l.bottom&&(this.list.scrollTop+=(a.bottom-l.bottom)/c)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(gt),i=Ni(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Td.of(i)})}static open(e){return new rr(e)}}function Cs(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${e}>${encodeURIComponent(n)}</svg>')`}function ms(n){return Cs(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${n}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const cS=K.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:ms("#f11")},".cm-lintRange-warning":{backgroundImage:ms("orange")},".cm-lintRange-info":{backgroundImage:ms("#999")},".cm-lintRange-hint":{backgroundImage:ms("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function hS(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function Zd(n){let e="hint",t=1;for(let i of n){let s=hS(i.severity);s>t&&(t=s,e=i.severity)}return e}class Md extends Mt{constructor(e){super(),this.diagnostics=e,this.severity=Zd(e)}toDOM(e){let t=document.createElement("div");t.className="cm-lint-marker cm-lint-marker-"+this.severity;let i=this.diagnostics,s=e.state.facet(Tr).tooltipFilter;return s&&(i=s(i,e.state)),i.length&&(t.onmouseover=()=>fS(e,t,i)),t}}function uS(n,e){let t=i=>{let s=e.getBoundingClientRect();if(!(i.clientX>s.left-10&&i.clientX<s.right+10&&i.clientY>s.top-10&&i.clientY<s.bottom+10)){for(let r=i.target;r;r=r.parentNode)if(r.nodeType==1&&r.classList.contains("cm-tooltip-lint"))return;window.removeEventListener("mousemove",t),n.state.field(Ed)&&n.dispatch({effects:il.of(null)})}};window.addEventListener("mousemove",t)}function fS(n,e,t){function i(){let o=n.elementAtHeight(e.getBoundingClientRect().top+5-n.documentTop);n.coordsAtPos(o.from)&&n.dispatch({effects:il.of({pos:o.from,above:!1,clip:!1,create(){return{dom:Rd(n,t),getCoords:()=>e.getBoundingClientRect()}}})}),e.onmouseout=e.onmousemove=null,uS(n,e)}let{hoverTime:s}=n.state.facet(Tr),r=setTimeout(i,s);e.onmouseout=()=>{clearTimeout(r),e.onmouseout=e.onmousemove=null},e.onmousemove=()=>{clearTimeout(r),r=setTimeout(i,s)}}function dS(n,e){let t=Object.create(null);for(let s of e){let r=n.lineAt(s.from);(t[r.from]||(t[r.from]=[])).push(s)}let i=[];for(let s in t)i.push(new Md(t[s]).range(+s));return H.of(i,!0)}const pS=zu({class:"cm-gutter-lint",markers:n=>n.state.field(ha),widgetMarker:(n,e,t)=>{let i=[];return n.state.field(ha).between(t.from,t.to,(s,r,o)=>{s>t.from&&s<t.to&&i.push(...o.diagnostics)}),i.length?new Md(i):null}}),ha=Te.define({create(){return H.empty},update(n,e){n=n.map(e.changes);let t=e.state.facet(Tr).markerFilter;for(let i of e.effects)if(i.is(Cr)){let s=i.value;t&&(s=t(s||[],e.state)),n=dS(e.state.doc,s.slice(0))}return n}}),il=Y.define(),Ed=Te.define({create(){return null},update(n,e){return n&&e.docChanged&&(n=Qd(e,n)?null:{...n,pos:e.changes.mapPos(n.pos)}),e.effects.reduce((t,i)=>i.is(il)?i.value:t,n)},provide:n=>yr.from(n)}),mS=K.baseTheme({".cm-gutter-lint":{width:"1.4em","& .cm-gutterElement":{padding:".2em"}},".cm-lint-marker":{width:"1em",height:"1em"},".cm-lint-marker-info":{content:Cs('<path fill="#aaf" stroke="#77e" stroke-width="6" stroke-linejoin="round" d="M5 5L35 5L35 35L5 35Z"/>')},".cm-lint-marker-warning":{content:Cs('<path fill="#fe8" stroke="#fd7" stroke-width="6" stroke-linejoin="round" d="M20 6L37 35L3 35Z"/>')},".cm-lint-marker-error":{content:Cs('<circle cx="20" cy="20" r="15" fill="#f87" stroke="#f43" stroke-width="6"/>')}}),gS=Lu(sS,{hideOn:Qd}),Ud=[gt,K.decorations.compute([gt],n=>{let{selected:e,panel:t}=n.field(gt);return!e||!t||e.from==e.to?I.none:I.set([nS.range(e.from,e.to)])}),gS,cS],Tr=Z.define({combine(n){return yt(n,{hoverTime:300,markerFilter:null,tooltipFilter:null})}});function OS(n={}){return[Tr.of(n),ha,pS,mS,Ed]}const Fd=1,Ue=Object.freeze({ready:"studio.ready",documentOpen:"document.open",documentReplace:"document.replace",documentChanged:"document.changed",documentSave:"document.save",documentSetReadOnly:"document.setReadOnly",documentResources:"document.resources",editorInsert:"editor.insert",editorFormat:"editor.format",editorSetTheme:"editor.setTheme",editorGetState:"editor.getState",diagnosticsPublish:"diagnostics.publish"});function yS(n,e={},t=null,i=null){return{protocolVersion:Fd,type:n,documentID:t,...i===null?{}:{sessionID:i},payload:e}}function AS(n){if(window.WKWebViewJavascriptBridge){n(window.WKWebViewJavascriptBridge);return}if(window.WKWVJBCallbacks){window.WKWVJBCallbacks.push(n);return}window.webkit?.messageHandlers?.iOS_Native_InjectJavascript&&(window.WKWVJBCallbacks=[n],window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null))}function nn(n,e,t={},i=null,s=()=>{},r=null){if(!n){s({result:"unavailable"});return}n.callHandler(e,yS(e,t,i,r),s)}function bS(n){const e={capabilities:["jsx","format","search","completion","diagnostics"]};nn(n,Ue.ready,e)}const SS=[{id:"$storage.getString",arguments:["key"],returns:"string",documentation:"Read a package-scoped string. Missing keys return an empty string."},{id:"$storage.setString",arguments:["key","value"],returns:"boolean",documentation:"Set a package-scoped string, limited to 256 KiB of UTF-8. Check the success result."},{id:"$storage.getJSON",arguments:["key"],returns:"json",documentation:"Read a package-scoped JSON object. Missing or invalid values return an empty object."},{id:"$storage.setJSON",arguments:["key","value"],returns:"boolean",documentation:"Store a valid JSON object, limited to 256 KiB encoded. Check the success result."},{id:"$storage.compareAndSetString",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a string only when it still matches expected. A missing key matches an empty string. Conflicts return false; reread and retry a bounded number of times. Requires the shared storage container."},{id:"$storage.compareAndSetJSON",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a JSON object if its current value equals expected, independent of property order. A missing key matches an empty object. Wrong types and conflicts return false. Requires the shared storage container."},{id:"$storage.remove",arguments:["key"],returns:"boolean",documentation:"Remove a key from this package only."},{id:"$storage.keys",arguments:[],returns:"string[]",documentation:"List keys in this package's namespace."},{id:"$storage.clear",arguments:[],returns:"boolean",documentation:"Clear this package's storage. Other packages are unaffected."}].map(n=>({minimumRuntimeVersion:"1.0",...n,preview:"initialState"})),xS=[{id:"$notifications.status",group:"notifications",value:{authorization:"authorized"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.pending",group:"notifications",value:[],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.schedule",group:"notifications",value:{key:"daily",status:"scheduled"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$notifications.cancel",group:"notifications",value:{key:"daily",status:"cancellationRequested"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$health.dailyStatistics",group:"health",value:{metric:"steps",unit:"count",aggregation:"sum",timeZone:"UTC",items:[{date:"2026-01-01",value:6840,hasSamples:!0}]},platforms:["ios"],authorization:"healthRead",notes:"Runtime 1.6. Read-only daily HealthKit statistics on installed iPhone/iPad widgets. Declare health and minimumRuntimeVersion 1.6, review Health access in native Settings. No separate System Access toggle. Missing readings are null/hasSamples false and cannot establish read denial. No raw samples, persistence or queries in future/Live Activity presentations. Preview fixtures never access real Health data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHealth.swift",operation:"read",mock:"editable"},{id:"$calendar.create",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$calendar.update",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$weather.forecast",group:"weather",value:{provider:"MET Norway",attribution:{text:"Weather data from MET Norway",url:"https://www.met.no/en/free-meteorological-data/Download-services"},latitude:37.33,longitude:-122.01,fetchedAt:"2026-01-01T12:00:00Z",isStale:!1,hours:[{time:"2026-01-01T12:00:00Z",temperatureC:21,windMetersPerSecond:2,precipitationMM:0,condition:"partlycloudy_day"}]},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeWeather.swift",operation:"read",mock:"editable"},{id:"$alarms.status",group:"alarms",value:{authorization:"authorized"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.pending",group:"alarms",value:[],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.schedule",group:"alarms",value:{key:"focus",status:"scheduled",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.cancel",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.stop",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.pause",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.resume",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$documents.list",group:"documents",value:[{id:"550e8400-e29b-41d4-a716-446655440000",name:"Sample.json",type:"json",bytes:17},{id:"550e8400-e29b-41d4-a716-446655440001",name:"Sample.csv",type:"csv",bytes:24}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readJSON",group:"documents",value:{goal:12,done:7},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readCSV",group:"documents",value:{headers:["day","value"],rows:[["Monday","7"],["Tuesday","9"]],truncated:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$contacts.selected",group:"contacts",value:[{id:"sample.contact",name:"Alex Example",organization:"Sample",phones:["+1 202 555 0100"],emails:["alex@example.com"]}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeContacts.swift",operation:"read",mock:"editable"},{id:"$maps.search",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.geocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["address"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.reverseGeocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.snapshot",group:"maps",value:{image:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",width:256,height:256,provider:"Apple Maps"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$home.items",group:"home",value:[{id:"sample.light",name:"Living Room Lamp",kind:"power",value:!0,isCached:!0,metric:"power",unit:"boolean"},{id:"scene-sample",name:"Evening",kind:"scene",value:null,isCached:!0,metric:"scene",unit:"none"}],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"read",mock:"editable"},{id:"$home.setPower",group:"home",value:{id:"sample.light",value:!0,status:"acknowledged"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"},{id:"$home.runScene",group:"home",value:{id:"scene-sample",status:"acknowledged",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"}],ua="2026-01-01T00:00:00Z",Vt="2026-01-01T12:00:00Z",ho=(n,e)=>({value:n,unit:e,hasSamples:!0,start:ua,end:Vt}),ch=(n,e,t)=>Object.entries(e).map(([i,s])=>({id:`$${n}.${i}`,group:n,value:s,legacy:[t,i]})),vS=[{id:"$music.isAvailable",group:"music",value:!0},{id:"$music.authorizationStatus",group:"music",value:"authorized"},{id:"$music.current",group:"music",value:{provider:"appleMusic",state:"playing",hasItem:!0,title:"Morning Light",artist:"ScriptWidget Sessions",album:"Focus",duration:224,position:86,capturedAt:Vt}},{id:"$services.status",group:"services",value:"connected"},{id:"$services.profile",group:"services",value:{service:"github",subject:"42",username:"octocat",displayName:"Mona",publicRepositories:32,privateRepositories:8,followers:128,following:24}},...ch("device",{screen:{width:390,height:844,scale:3},language:"en",model:"iPhone",name:"My iPhone",battery:{level:.8,state:"unplugged"},systemVersion:"26.0",isdarkmode:!1,totalDiskSpace:128e9,freeDiskSpace:64e9},"device"),...ch("system",{appInfo:{name:"ScriptWidget",bundleId:"com.everettjf.scriptwidget",version:"27.1.2",build:"27012"},locale:"en_US",preferredLanguages:["en-US"],timeZone:{identifier:"UTC",abbreviation:"GMT",offsetSeconds:0},is24HourClock:!1,calendarInfo:{identifier:"gregorian",firstWeekday:1,minimumDaysInFirstWeek:1},systemUptime:3600,memory:{physical:8589934592},thermalState:"nominal",lowPowerMode:!1,brightness:.5,reduceMotionEnabled:!1,platform:"ios",hostName:"My iPhone",processName:"ScriptWidgetWidget",osVersionString:"Version 26.0",processorCount:6,activeProcessorCount:6},"system"),{id:"$photos.isAvailable",group:"photos",value:!0},{id:"$photos.authorizationStatus",group:"photos",value:"authorized"},{id:"$photos.requestAuthorization",group:"photos",value:!0},{id:"$photos.items",group:"photos",value:{status:"ready",items:[{id:"sample.photo",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fbPe3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDQK/QnooooGFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9uKKKK7TxwooooAKKKKACiiigAooooAKKKKACs/VNUsNGsX1HUpBFDGMkn+Q9Sewqtruvab4c099S1STYi8AfxMeyqO5NfInjDxnqfi++865Pl26H91CDwo9T6t6mhs5cTiVSXmX/ABx49v8Axdc+UmYbKM/u4vX/AGm9T+g/U6/w38fv4buRpOqMTYynr18pj3H+ye4/H1z5TRU3PHVean7S+p+gSOkiCSMhlYZBHIIPcU6vmn4YfEL+zXTw5rb/AOjscQyN/wAsyf4Sf7p7Ht9On0tVHuUKyqx5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KKACvePgx8bNT+Gl8NN1Hdc6PM2ZIurRE9Xjz39V6H2PNeD0UjSlWlSkpwdmftNo+saZr+mQ6xo0y3FtcLvjkQ5BH9COhB5B4NaVflf8IPjJrHww1LyZN1zpU7Znt88g9N8eejDuOjDg9iP038P+INH8UaRDrmhTrcWs67kdf1BHUEdCDyDUNWPrsFjo4mPZ9Uf//S+tKKKK6z8/CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSSRwxtLKwVVGSTwABSTTRW8TTzsERBkseABXhHi3xfLrchsrIlLVT9C5Hc+3oPz9nGNzOpVUFdkvi/xjJrDmw08lbVTyehkI7n29B+ftwNFFbJWPNnNyd2FFFFMkKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvWvhP8W9b+F+r+bBm40+dh9otieG7bk/uuB379D2x5LRSLp1JU5KcHZo//0/rSiiius/PwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtYWublgiIMsx6AU26ureyt3urpwkaDJY14H4q8V3GvzeTDmO1Q/Kvdvdv8O1OMbmVWqoIk8WeLZtdlNrbZS1Q8Du59T/AEFcXRRWyVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/9T60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKKKKACq15eW2n2z3d44SNBkk0y/v7XTbV7y9cJGg5J/kPU18/eJfE114hucnKW6H5I/6n1P8qqMbmVWqoLzJPFHim58QXGxcx2yH5E9fdvf+VcpRRWqVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKo6jqNppVo17etsRfzJ9B6mm6pqlnpFm17ettReg7k+gHrXz34h8Q3niC786c7Y1+5GOij+p9TVRjcxq1lBeY/xH4ku/EN1vk+SFD8kfYe59TXOUUVqedKTbuwooopiCiiigAooooAKKKKACii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onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/ayiiivVAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9rKKKK9UAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0f2sooor1QCiiigAooooAKKKKACiiigAooooAKKKKACiq15eWun2r3t7IsUUY3MzHAApbW6tr62S8tHEkUqhlZeQQaduoFiiiikAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB/9L9rKKKK9UAooooAKKKKACiiigAooooAKKKKACs/VdVsNFsZNS1OQRQxjJJ/kB3J7Cquva/pnhvTn1PVJNiLwAPvMeyqO5P+eK+P/GPjTU/GF9510fLt0P7qEHhR6n1Y9zXRRoOo/Iyq1VD1L3jrx9f+MLrykzDZRn93F6/7T+p/QdvU7Pw1+IL+GbkaTqjFrCVu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KKACiiigAooooAKKKKACiiigApGZUUu5wBySe1NkkSJDJIQqqMkngADua+f8Axv46fWGbStJYrag4Zuhk/wDsf51dOm5uyJbsT+OPHbamX0jR2xbDh5B1k9h/s/z+leV0UV6UIKKsjJu4UUUVYgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvoL4IfHTVfhdfjTNS3XWiztmSHq0RPWSPPf1Xo3sea+faKzq0o1IuE1oVGbi+aJ+5Gi61pXiLS4Na0SdLm1uF3xyIcgj+hHQg8g8HmtSvyU+DHxs1r4Vap5Em660i4bM9tnkHp5keeA47jow4PYj9UPDviPRfFmjQa/4fnW5tbhdyOv6gjqCDwQeQa+ZxeElQl5Hq0ayqLzP//S+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACo5ZYoI2mmYIiDLMTgADuaSeeG2ha4uGCIgyzHgACvnbxp42m1+Q2NgSlmp+hkI7n29B+J9tKVJzdkTKViXxt44k1x203TSUtFPJ6GQjuf9n0H4n284oor0oxUVZGLdwoooqgCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr2H4QfGLXvhTrPm2+bjTZ2H2m1J4btvT+64Hfv0PbHj1FROEZxcZrQcZOLuj//T+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKgubm3s7d7q6cRxxjLMegFNu7y2sLZ7y8cRxxjLMe1fN/jDxlc+JJ/IgzHaIflTux/vN7+g7VpSpObJlKxL4y8aXHiKY2lpmOzQ8L0Lkd2/oK4OiivSjFRVkYt3CiiiqAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//1PqCiiivszygooooAKKKKACiiigAooooAKKKKACiiigAooooAKqX19aabave3riOKMZJP+etN1HUbPSrN76/cRxoOSf5D1J9K+afFfiy88TXeTmO2Q/u4/6t6n+XataVJzfkTKViXxd4vu/EtzsTMdrGfkj9f9pvf+VcbRRXoxioqyMW7hRRRVAFFFFABRRRQAUUU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RAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fave3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDTt1AnooopAFFF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AFFFFAH//U+uKKKK+oPoAooooAKKKKACiiigAooooAKKKKACiiigAooooAKq3t7a6daveXjhI0GST/AJ602/v7TTLR729cJGg5J/kPUmvnXxR4pu/EdzzmO3Q/u4/6n1P8q0p03M1pUnN+RJ4q8V3XiK42LmO2Q/Inr/tN7/yrkaKK7UklZHfGKirIKKKKoYUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9X64ooor6g+gCiiigAooooAKKKKACiiigAooooAKKKKACqGpalZ6TZtfXz7I1/Mn0A7k03VdVstGs2vr59qL0Hcn0A7mvnLxH4jvfEV558/yxL/AKuMdFH9T6mtadPm9DWlSc/Qk8S+JrzxHd+ZJ8kKH93H2HufU1zNFFdqSSsjvSSVkFFFFMYUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//1vriipFilf7ik/QVZXTtQf7kEh+in/CvqD6ApUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf/AApcy7iuYNFdOngvxc/TTbn8Y2H8xVhfAPjJ+mnTfiMfzpc8e4XRyFFdwvw38bv009/xZB/NqsL8LfHbf8uOPrJH/wDFUvaR7hzLuef0V6Svwl8cN1tkX6yJ/Q1ZX4P+M26pCv1kH9AaXtYdxc67nltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AAJz/wCyUvbw7hzx7njlZesaxY6JZNe3zYUcADqx9APWvSvHfg6P4daE+u+JNQgVfuxxJuMkr/3UBAz7noB1r4j13Xr7xBem7vDgDhEHRR6D+p710UIqpqtjejT9pr0JPEHiC+8Q3hubo7UXhIx0Uf4+prBoorvStojvSS0QUUUUxhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//2Q==",width:384,height:256},{id:"sample.photo.4",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiuc9UKKKKAC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UUUAFFFFABXrvwk+L2ufCzWPNt83GnTsPtNqTw3ben91wO/foe2PIqKDOpTjUi4TV0f/T+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtIHublwkaDLMegFNu7u2sbZ7u7cRxoMsx7V87+LfF9z4in8iHMdoh+VO7H+839B2pN2NqNF1H5EvjDxjP4gmNra5jtEPC93I7t/QVw1FFZtnqwgorliFFFFIsKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9T60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAqre3trp1q95euI40GST/nrTNQ1C00u0e9vnCRoOSf5D1Jr5y8U+KrvxJdZOY7dD+7j/qfU/wAqTdjejRdR+RL4r8WXXiO52LmO1Q/Inr/tN7/yrkKKKzPVjFRVkFFFFIoKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP//V+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAqhqep2ekWb318+yNPzJ9AO5NM1XVrLRbJr6/fai9B3Y9gB3NfN/iPxJe+I7zz7j5Yl/wBXGOij+p9TUt2OihQdR+RJ4m8T3niO78yT5IEP7uPsPc+prmaKKg9SMVFWQUUUUigooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/W+tKKkWKV/uKT9BVlNO1CT7kEjfRT/hWR9rcpUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf8AwoFzLuYNFdMvgvxc/TTbn8Y2H8xVlfAPjJ+mnTfiMfzoF7SPc5Ciu4X4b+N36ae/4sg/masL8LfHb/8ALjj6yR//ABVIXtYfzI8/or0lPhL44brbIv1kT+hqynwf8Zt1SFfrIP6A0C9tD+ZHltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AnP8A7JQL6xT/AJjxysrWNZsdDsmvr5sKOAB1Y+gHrXpXjvwfF8OdBfXfEmoQKv3Yok3GSV/7qAgZ9z0A618Q69r194gvTd3hwBwiDoo9B/U96TdjrwtNVveWw/xB4hvvEV6bm6O1F4SMdFH+PqawaKKg9dJJWQUUUUhhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/9k=",width:384,height:256}],unavailableCount:0,fetchedAt:Vt,source:"system",stale:!1}},{id:"$calendar.isAvailable",group:"calendar",value:!0},{id:"$calendar.authorizationStatus",group:"calendar",value:"authorized"},{id:"$calendar.requestAuthorization",group:"calendar",value:!0},{id:"$calendar.calendars",group:"calendar",value:[{id:"sample.personal",title:"Personal"}]},{id:"$calendar.events",group:"calendar",value:{status:"ready",items:[{id:"sample.event",calendarID:"sample.personal",title:"Read and recharge",start:"2026-01-01T15:00:00Z",end:"2026-01-01T15:30:00Z",allDay:!1}],fetchedAt:Vt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.isAvailable",group:"reminders",value:!0},{id:"$reminders.authorizationStatus",group:"reminders",value:"authorized"},{id:"$reminders.requestAuthorization",group:"reminders",value:!0},{id:"$reminders.lists",group:"reminders",value:[{id:"sample.reminders",title:"Personal"}]},{id:"$reminders.items",group:"reminders",value:{status:"ready",items:[{id:"sample.reminder",listID:"sample.reminders",title:"Read a chapter",due:"2026-01-01T16:00:00Z",hasTime:!0,completed:!1,completedAt:null,priority:0}],fetchedAt:Vt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.create",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.update",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.setCompleted",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$health.authorizationStatus",group:"health",value:"notDisclosed"},{id:"$health.sleepSummary",group:"health",value:{start:ua,end:Vt,timeZone:"UTC",hasSamples:!0,totalSleepSeconds:27e3,inBedSeconds:30600,awakeSeconds:1800,stages:{unspecified:0,core:16200,deep:5400,rem:5400},sourceCount:1,truncated:!1,conflictSeconds:0,aggregation:"union-awake-rem-deep-core-unspecified"}},{id:"$health.activitySummary",group:"health",value:{date:"2026-01-01",timeZone:"UTC",hasSamples:!0,moveMode:"activeEnergy",move:{value:480,goal:600,unit:"kcal"},exercise:{value:26,goal:30,unit:"min"},stand:{value:9,goal:12,unit:"count"}}},{id:"$health.workouts",group:"health",value:{start:ua,end:Vt,timeZone:"UTC",hasSamples:!0,truncated:!1,items:[{id:"550e8400-e29b-41d4-a716-446655440000",activity:"running",start:"2026-01-01T09:00:00.000Z",end:"2026-01-01T09:45:00.000Z",duration:2700,energyKcal:285,distanceMeters:5200}]}},{id:"$health.isAvailable",group:"health",value:!0},{id:"$health.requestAuthorization",group:"health",value:!0,legacy:["health"]},{id:"$health.stepCountToday",group:"health",value:ho(6840,"count"),legacy:["health.stepCountToday"]},{id:"$health.activeEnergyToday",group:"health",value:ho(420,"kcal"),legacy:["health.activeEnergyToday"]},{id:"$health.heartRateLatest",group:"health",value:ho(72,"bpm"),legacy:["health.heartRateLatest"]},{id:"$location.isAvailable",group:"location",value:!0},{id:"$location.authorizationStatus",group:"location",value:"authorizedWhenInUse"},{id:"$location.isAuthorizedForWidgetUpdates",group:"location",value:!0},{id:"$location.requestAuthorization",group:"location",value:!0,legacy:["location.authorization"]},{id:"$location.current",group:"location",value:{latitude:37.3349,longitude:-122.009,altitude:0,accuracy:10,verticalAccuracy:10,speed:-1,course:-1,timestamp:Vt,accuracyAuthorization:"full",age:0,isStale:!1},legacy:["location"]}],wS={music:{platforms:["ios"],authorization:"musicRead",notes:"Runtime 1.4. Read-only Music app playback, not every audio player. Requires an installed owner, music permission and Music library approval in native Settings. current() is asynchronous and returns provider, state, hasItem, nullable title/artist/album/duration/position and capturedAt. State may be playing while details are absent (Home Sharing). Native player access is main-thread-only: synchronous hosts prepare one snapshot before JSC waits; background previews capture on the main queue. No playback/queue mutation, scans, artwork, credential or subscription inference. No live queries in future entries/Live Activities. Main system-player API is unavailable on macOS; Web supplies editable samples, never actual device access."},services:{platforms:["ios","macos"],authorization:"serviceAccount",notes:"Runtime 1.4: status(service) and profile(service) are asynchronous. Only provider: github. Unknown providers reject with service_operation. Requires an installed owner and services permission. profile additionally requires network and api.github.com in networkDomains, a native connected GitHub account and explicit owner grant. Native Settings handles credentials; scripts cannot log in or obtain tokens. profile returns service, subject, username, displayName, publicRepositories, privateRepositories, followers and following (missing values are null). No live queries in future entries or Live Activities. Eight shared data queries; native requests also share the eight concurrent/32 total network budget, while Web uses its existing preview network budget. Web uses editable best-state samples only; it never authenticates or sends these requests."},photos:{platforms:["ios","macos"],authorization:"photosRead",notes:"Requires photos permission and explicit native photo/album selection (none by default). Limited Photos authorization is supported. items({limit:1..4,offset:0..63,maxAgeSeconds:0..86400}) returns bounded, metadata-stripped JPEG thumbnails as image data URLs. Four 768px / 128KiB thumbnails at most; private snapshots expire after 24h and are rechecked against current access, selected sources and asset revisions. Cloud-only items report unavailableCount; download them in Photos first. Future timeline/Live Activity presentations read matching snapshots only. Web uses editable sample data and photosSelection IDs; no actual library access."},reminders:{platforms:["ios","macos"],authorization:"remindersRead",notes:"Requires reminders in widget.json and full system Reminders access. Reads require native Settings selected lists. create/update/setCompleted additionally require remindersWrite and a native declared action, stable requestID, durable replay receipts and an unchanged selected list. Web writes update preview-only items/receipts; receipt identities are derived from that state, with configurable API errors. Use lists() for IDs. items() selects pending due dates or completed completion dates in a positive window of at most 31 days, up to 50 items. Undated pending reminders are excluded. remindersSelection mocks the user scope without granting permission."},calendar:{platforms:["ios","macos"],authorization:"calendarRead",notes:"Requires calendar in widget.json and full system Calendar access. The user's native Settings source selection limits metadata, events and cached snapshots; scripts cannot enlarge it. Use calendars() for permitted IDs and show setup when no sources are selected. Queries are read-only, limited to 31 days and 50 items. Preview calendarSelection simulates this scope without granting package permission."},device:{platforms:["ios","macos"],authorization:"none",notes:"Device values depend on hardware. Some legacy Mac values are placeholders; inspect the API documentation before using them as measurements."},system:{platforms:["ios","macos"],authorization:"none",notes:"System metadata, not whole-device CPU, FPS or network traffic monitoring. Hardware-specific values may be unavailable."},health:{platforms:["ios"],authorization:"healthRead",notes:"Read-only HealthKit. Request access in the app. Runtime 1.4 adds sleepSummary (up to 7 days / 256 samples, union with explicit stage-conflict precedence), activitySummary (one local Gregorian day including active-energy or move-time mode and optional goals), and workouts (up to 31 days / 50 fully-contained summaries, optional kcal/meters). These require an explicit health manifest; all share the query budget and cannot run in future/Live Activity presentations. No Health readings are persisted by the API. Authorization completion does not reveal whether individual read types were granted; empty results must not be labelled permission denied. API 1.3 readings add hasSamples: false means no readable samples, never a read-denial verdict. Existing value/unit/start/end fields remain."},location:{platforms:["ios"],authorization:"locationWhenInUse",notes:"Package 2.0 requires location permission. Request system access in the app. Widgets also require isAuthorizedForWidgetUpdates. Cache is rechecked against authorization and precision, discarded after 24 hours or revocation, and reports age/isStale."}},kS=[...vS.map(n=>{const e=n.id.split(".")[1],t=n.group==="music"&&e==="current"||n.group==="services"||["calendar","reminders","photos"].includes(n.group)&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="health"&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e),i=n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e)||["calendar","reminders","photos"].includes(n.group)&&["events","items"].includes(e);return{...n,...wS[n.group],minimumRuntimeVersion:["music","services","reminders","photos"].includes(n.group)||n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)?"1.4":["calendar"].includes(n.group)||["$health.authorizationStatus","$location.isAuthorizedForWidgetUpdates"].includes(n.id)?"1.3":"1.0",arguments:n.group==="services"?["service"]:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?["options"]:i?["options?"]:[],...n.group==="reminders"&&["create","update","setCompleted"].includes(e)?{authorization:"remindersWrite"}:{},asynchronous:t,nativeSource:`Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntime${n.group[0].toUpperCase()}${n.group.slice(1)}.swift`,operation:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?"write":e==="requestAuthorization"?"authorization":["isAvailable","authorizationStatus","isAuthorizedForWidgetUpdates"].includes(e)?"availability":"read",mock:"editable"}}),...xS],$e={globalProperties:{background:{type:"color",documentation:"Background color, hex value, or named color."},backgroundMaterial:{type:"enum",values:["none","ultraThin","thin","regular","thick","ultraThick"],documentation:"Runtime API 1.4. Public SwiftUI frosted material inside the widget, not Home Screen wallpaper blur or system Liquid Glass. At most four material backgrounds per tree. background supplies an opaque-composited Reduce Transparency fallback. In accented/vibrant mode local material is omitted for system rendering; none keeps the ordinary background."},color:{type:"color",documentation:"Foreground color, hex value, or named color."},font:{type:"enum",values:["largeTitle","title","title2","title3","headline","subheadline","body","callout","footnote","caption","caption2"],documentation:"Semantic text style."},fontWeight:{type:"enum",values:["ultraLight","thin","light","regular","medium","semibold","bold","heavy","black"],documentation:"Font weight."},fontDesign:{type:"enum",values:["default","rounded","serif","monospaced"],documentation:"Font design."},frame:{type:"number|string",documentation:'Square size (64 or "64"), width,height ("64,48"), or flexible frame ("max", "max,48").'},padding:{type:"number|string",documentation:"Padding amount or edge description."},corner:{type:"number",documentation:"Corner radius."},opacity:{type:"number",documentation:"Opacity from 0 through 1."},alignment:{type:"enum",values:["center","leading","trailing","top","bottom","topLeading","topTrailing","bottomLeading","bottomTrailing","firstTextBaseline","lastTextBaseline"],documentation:"Layout alignment."},clip:{type:"enum",values:["circle","rect","capsule","ellipse"],documentation:"Clip the view to a shape."},rotation:{type:"number",documentation:"Rotation in degrees."},rotation3d:{type:"string",documentation:"Static degree,x,y,z rotation with four finite numbers and a nonzero axis. Invalid values are ignored; axis magnitude is normalized. Reduce Motion removes the tilt. This does not read device motion or provide parallax."},shadow:{type:"string",documentation:"Shadow color, radius, and offset description."},animation:{type:"string",documentation:"iOS public SwiftUI scheduled clock/swing effect. Mac renders static standard-clock poses; other effects remain at rest. Signed clockCustom intervals specify a half-turn (full cycle = 2 * abs(interval)), minimum magnitude 0.25 seconds. App previews can animate; WidgetKit decides cadence and may freeze. Reduced motion/luminance freezes standard clock poses and keeps custom/swing effects at rest. Dynamic scripts are not rerun on animation ticks."},widgetAccentable:{type:"boolean",documentation:"Group this view into the accent layer in tinted and vibrant widget appearances."},linkurl:{type:"url",documentation:"Widget deep link URL."}},components:{VStack:{documentation:"Arrange children vertically.",children:!0,properties:{spacing:{type:"number"}}},HStack:{documentation:"Arrange children horizontally.",children:!0,properties:{spacing:{type:"number"}}},ZStack:{documentation:"Overlay children.",children:!0,properties:{}},VGrid:{documentation:"Vertical lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["leading","center","trailing"]}}},HGrid:{documentation:"Horizontal lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["top","center","bottom","firstTextBaseline","lastTextBaseline"]}}},Text:{documentation:"Display text content.",children:!1,properties:{text:{type:"string"}}},Date:{documentation:"Display a formatted date.",children:!1,properties:{date:{type:"date|number",required:!0},style:{type:"enum",values:["time","date","relative","offset","timer"]}}},Image:{documentation:"Display a bundled, remote, or SF Symbol image.",children:!1,properties:{systemName:{type:"string"},name:{type:"string"},id:{type:"string",deprecated:"Use name."},url:{type:"url"},src:{type:"url",deprecated:"Use url."},ratio:{type:"number"},mode:{type:"enum",values:["fit","fill"]},accentedRenderingMode:{type:"enum",values:["accented","desaturated","accentedDesaturated","fullColor"],documentation:"Control how the image is rendered in tinted and clear widget appearances."}}},Gif:{documentation:"Display a bounded package GIF using system decoding: up to 8 MiB input and 1,048,576 canvas pixels. iOS retains at most 60 downsampled frames / 4 MiB decoded pixels; more frames fall back to the first frame. Mac, Reduce Motion and reduced luminance use a static first frame. Active iOS previews use public SwiftUI timing with variable frame delays. Snapshots, inactive scenes, Mac and accessibility fallbacks use the first frame. No private clock bridge or continuous WidgetKit guarantee.",children:!1,properties:{file:{type:"string",required:!0}}},Spacer:{documentation:"Flexible layout space.",children:!1,properties:{minLength:{type:"number"}}},Rect:{documentation:"Rectangle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},RoundedRect:{documentation:"Filled rounded rectangle.",children:!1,properties:{radius:{type:"number"}}},Capsule:{documentation:"Capsule shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Ellipse:{documentation:"Ellipse shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Circle:{documentation:"Circle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Gauge:{documentation:"Display a gauge or instrument.",children:!1,properties:{type:{type:"string"},value:{type:"number"},style:{type:"enum",values:["circular","linear"]},text:{type:"string"},current:{type:"string"},min:{type:"string"},max:{type:"string"},angle:{type:"number"},thickness:{type:"number"},needleColor:{type:"color"},label:{type:"string"},title:{type:"string"},sections:{type:"string"}}},Chart:{documentation:"Render chart data.",children:!1,availability:{ios:"16.0",macos:"26.0"},properties:{type:{type:"enum",values:["bar","bar-x","bar-y","bar-gantt","line","point","line-point","area","rect","rule-x"]},data:{type:"json",required:!0},category:{type:"boolean"},hideLegend:{type:"boolean"},hideXAxis:{type:"boolean"},hideYAxis:{type:"boolean"}}},Link:{documentation:"Open a URL when selected.",children:!0,properties:{url:{type:"url",required:!0}}},Divider:{documentation:"Horizontal or vertical separator.",children:!1,properties:{thickness:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Line:{documentation:"Fixed-length line.",children:!1,properties:{thickness:{type:"number"},length:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Icon:{documentation:"SF Symbol icon.",children:!1,properties:{systemName:{type:"string",required:!0},size:{type:"number"}}},Label:{documentation:"Text paired with an SF Symbol.",children:!1,properties:{title:{type:"string"},systemName:{type:"string",required:!0}}},Progress:{documentation:"Linear or circular progress.",children:!1,properties:{value:{type:"number",required:!0},total:{type:"number"},label:{type:"string"},style:{type:"enum",values:["linear","circular"]},trackColor:{type:"color"},thickness:{type:"number"}}},Ring:{documentation:"Circular progress ring.",children:!1,properties:{value:{type:"number",required:!0},thickness:{type:"number"},trackColor:{type:"color"}}},Badge:{documentation:"Compact status badge.",children:!1,properties:{text:{type:"string"},radius:{type:"number"}}},Chip:{documentation:"Outlined metadata chip.",children:!1,properties:{text:{type:"string"},radius:{type:"number"},borderColor:{type:"color"}}},Stat:{documentation:"Title, value, and subtitle statistic.",children:!1,properties:{title:{type:"string"},value:{type:"string",required:!0},subtitle:{type:"string"},mutedColor:{type:"color"}}},Button:{documentation:"Interactive widget button. Use actionID to share a declared Package 2.0 action with Siri, Shortcuts, and Control Widgets.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["action","onClick","actionID"],properties:{action:{type:"enum",values:["reload"],conflicts:["actionID"]},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",conflicts:["action","onClick"]}}},Toggle:{documentation:"Interactive widget toggle. A declared actionID requires a package-relative storage stateKey.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["onClick","actionID"],properties:{on:{type:"boolean",required:!0},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",requires:["stateKey"],conflicts:["onClick"]},stateKey:{type:"storage-key",requires:["actionID"]}}}},functions:{...Object.fromEntries(SS.map(n=>[n.id,n])),...Object.fromEntries(kS.map(n=>[n.id,{documentation:n.notes,minimumRuntimeVersion:n.minimumRuntimeVersion,arguments:n.arguments,returns:n.asynchronous?"Promise<json>":typeof n.value=="object"?"json":typeof n.value}])),"$icloud.readJSON":{documentation:"Read cached JSON and revision; conflicts preserve all heads. Requires icloud permission and a native connection. Never certifies upload.",arguments:["name"],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.writeJSON":{documentation:"Save a new immutable JSON revision locally from a user action. Requires the revision from readJSON. Background exchange is eventual.",arguments:["name","value","expectedRevision"],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.resolveJSON":{documentation:"Explicitly resolve all observed conflicting heads into a new revision. Stale tokens fail; originals remain.",arguments:["name","value","expectedRevision"],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.sync":{documentation:"Exchange materialized revisions with iCloud; requires a user action. Upload completion is unknown.",arguments:[],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$icloud.status":{documentation:"Read native connection state. In the app, explicitly connect packages to separate stores for isolation or the same store ID to share JSON documents. Scripts cannot choose store IDs. Sync is eventual; local $storage is not migrated. Web uses preview mocks.",arguments:[],returns:"Promise<json>",minimumRuntimeVersion:"1.5"},"$file.exists":{documentation:"Return whether a regular file is locally present inside this package, including binary assets. Missing files, directories, unsafe paths and links return false. Does not download iCloud files or read outside the package. Web preview uses workspace file presence.",arguments:["path"],returns:"boolean",minimumRuntimeVersion:"1.3"},"$file.read":{documentation:"Read package-relative UTF-8 text. Missing or unavailable files return an empty string.",arguments:["path"],returns:"string"},"$file.readJSON":{documentation:"Read a package-relative JSON object.",arguments:["path"],returns:"json"},fetch:{documentation:"Perform a network request and return its response text. Existing HTTP methods keep this string result."},"$http.getResponse":{documentation:"GET response metadata: {status, body, headers}. Headers are limited to content-type, cache-control, expires, last-modified, date and retry-after (lowercase; each at most 2048 UTF-8 bytes). Network permissions, public-host policy, redirects, body limits and timeline restrictions still apply. HTTP error statuses resolve; transport errors reject.",arguments:["url","options?"],returns:"Promise<json>",minimumRuntimeVersion:"1.3"},importJS:{documentation:"Import a package-relative JavaScript file."},"$dataSource.request":{documentation:"Call a declared Data Source Plugin operation. Requires Package 2.0 plugins, network permission, and networkDomains declarations.",arguments:["pluginID","operationID","parameters"],returns:"Promise<json|string>"},"$xml.parse":{documentation:"Parse up to 256 KiB of XML into {name, attributes, text, children}. DTDs and external entities are rejected; depth and node limits apply.",arguments:["source"],returns:"XMLNode"}}};function QS(n,e){const t=Object.entries(e.properties??{}).filter(([,s])=>s.required).map(([s,r])=>`${s}=${r.type.includes("number")||r.type==="boolean"?"{${}}":'"${}"'}`).join(" "),i=t?` ${t}`:"";return e.children?`<${n}${i}> \${} -</${n}>`:`<${n}${i} />`}const ah=Object.entries($e.components).map(([n,e])=>({label:n,type:"class",detail:`ScriptWidget · ${Object.keys(e.properties??{}).length} properties`,info:e.documentation,apply:SS(n,e)}));function xS(n){const e=n.match(/<([A-Za-z][\w]*)\b([^<>]*)$/);return!e||e[2].includes(">")?null:{name:e[1],attributes:e[2]}}function vS(n,e){const t=$e.components[n];return t?Object.entries({...$e.globalProperties,...t.properties??{}}).filter(([i])=>!e.has(i)).map(([i,s])=>({label:i,type:"property",detail:s.required?`${s.type} · required`:s.type,info:s.deprecated?`Deprecated: ${s.deprecated}`:s.documentation,apply:`${i}=${s.type.includes("number")||s.type==="boolean"?"{${}}":'"${}"'}`})):[]}function wS(n){const e=n.match(/<([A-Za-z][\w]*)\b[^<>]*\b([A-Za-z][\w]*)\s*=\s*["']([^"']*)$/);if(!e)return null;const t=$e.components[e[1]]?.properties?.[e[2]]??$e.globalProperties[e[2]];return t?.values?{typed:e[3],values:t.values}:null}function kS(n){const e=n.state.doc.sliceString(Math.max(0,n.pos-1200),n.pos),t=wS(e);if(t)return{from:n.pos-t.typed.length,options:t.values.map(o=>({label:o,type:"enum"})),validFor:/^[\w-]*$/};const i=n.matchBefore(/<[A-Za-z]*$/);if(i)return{from:i.from+1,options:ah,validFor:/^[A-Za-z]*$/};const s=xS(e);if(s&&/(?:\s|^)\w*$/.test(s.attributes)){const o=n.matchBefore(/[A-Za-z][\w]*$/),a=new Set([...s.attributes.matchAll(/\b([A-Za-z][\w]*)\s*=/g)].map(l=>l[1]));return{from:o?.from??n.pos,options:vS(s.name,a),validFor:/^[A-Za-z][\w]*$/}}const r=n.matchBefore(/\$[A-Za-z]+\.[A-Za-z]*$/);if(r){const o=r.text.slice(0,r.text.indexOf(".")+1),a=Object.entries($e.functions).filter(([l])=>l.startsWith(o));return a.length?{from:r.from+o.length,options:a.map(([l,c])=>({label:l.slice(o.length),type:"function",detail:c.returns,info:c.documentation})),validFor:/^[A-Za-z]*$/}:null}return n.explicit?{from:n.pos,options:ah,validFor:/^[A-Za-z]*$/}:null}function lh(n,e){const t=[];for(let i=n.node.firstChild;i;i=i.nextSibling)i.name===e&&t.push(i);return t}function Md(n){const e=[];return Ce(n).iterate({enter(t){if(t.name!=="JSXOpenTag"&&t.name!=="JSXSelfClosingTag")return;const s=lh(t,"JSXIdentifier")[0];s&&e.push({name:n.doc.sliceString(s.from,s.to),from:s.from,to:s.to,attributes:lh(t,"JSXAttribute").map(r=>{const o=r.firstChild;return o?{name:n.doc.sliceString(o.from,o.to),from:o.from,to:o.to}:null}).filter(Boolean)})}}),e}function Ed(n){const e=[];for(const t of Md(n.state)){const i=$e.components[t.name];if(!i)continue;const s=new Set([...Object.keys($e.globalProperties),...Object.keys(i.properties??{})]),r=new Set(t.attributes.map(o=>o.name));for(const o of t.attributes){s.has(o.name)||e.push({from:o.from,to:o.to,severity:"warning",message:`“${o.name}” is not supported by <${t.name}>.`});const a=i.properties?.[o.name]??$e.globalProperties[o.name];a?.deprecated&&e.push({from:o.from,to:o.to,severity:"warning",message:`${o.name} is deprecated. ${a.deprecated}`})}for(const[o,a]of Object.entries(i.properties??{}))if(a.required&&!r.has(o)&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires the “${o}” property.`}),r.has(o)){for(const l of a.requires??[])r.has(l)||e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> “${o}” requires the “${l}” property.`});for(const l of a.conflicts??[])r.has(l)&&o<l&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> cannot combine “${o}” with “${l}”.`})}i.requiredAny?.length&&!i.requiredAny.some(o=>r.has(o))&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires one of: ${i.requiredAny.map(o=>`“${o}”`).join(", ")}.`})}return e}function QS(n,e){const t=Md(n.state).find(s=>e>=s.from&&e<=s.to);if(!t)return null;const i=$e.components[t.name];return i?{pos:t.from,end:t.to,above:!0,create(){const s=document.createElement("div");s.className="studio-hover";const r=document.createElement("strong");r.textContent=`<${t.name}>`;const o=document.createElement("p");return o.textContent=i.documentation,s.append(r,o),{dom:s}}}:null}const ch={light:{background:"#FAFAFC",foreground:"#202124",gutter:"#F3F3F6",gutterText:"#8A8A93",activeLine:"#EDEEF3",selection:"#B9D7FF",caret:"#0067C0"},dark:{background:"#1E1F22",foreground:"#E8E8ED",gutter:"#191A1D",gutterText:"#777982",activeLine:"#292A2F",selection:"#315A85",caret:"#65B7FF"}};function PS(n,e){return $.theme({"&":{height:"100%",color:n.foreground,backgroundColor:n.background,fontSize:"13px"},".cm-scroller":{fontFamily:'ui-monospace, "SFMono-Regular", Menlo, Monaco, Consolas, monospace',lineHeight:"1.58",overscrollBehavior:"contain"},".cm-content":{caretColor:n.caret,padding:"12px 0 32px"},".cm-line":{padding:"0 8px"},".cm-cursor, .cm-dropCursor":{borderLeftColor:n.caret},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:n.selection},".cm-activeLine":{backgroundColor:n.activeLine},".cm-gutters":{backgroundColor:n.gutter,color:n.gutterText,border:"none",paddingLeft:"env(safe-area-inset-left)"},".cm-activeLineGutter":{backgroundColor:n.activeLine,color:n.foreground},".cm-foldPlaceholder":{backgroundColor:"transparent",border:`1px solid ${n.gutterText}`,color:n.gutterText},".cm-tooltip":{border:e?"1px solid #41434A":"1px solid #D2D3D8",backgroundColor:e?"#292A2F":"#FFFFFF",borderRadius:"8px",overflow:"hidden",boxShadow:"0 8px 28px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete ul li[aria-selected]":{backgroundColor:e?"#315A85":"#DCEBFA",color:n.foreground},".cm-panels":{backgroundColor:n.gutter,color:n.foreground},".cm-searchMatch":{backgroundColor:e?"#725C1D":"#FFE69A"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:e?"#8D6D20":"#FFD45C"}},{dark:e})}const CS=Xn.define([{tag:[O.keyword,O.controlKeyword,O.moduleKeyword,O.operatorKeyword,O.bool,O.null],color:"#FF7AB2"},{tag:[O.string,O.special(O.string)],color:"#FF8170"},{tag:[O.number,O.regexp],color:"#D9C97C"},{tag:[O.comment,O.lineComment,O.blockComment],color:"#7F8C98",fontStyle:"italic"},{tag:[O.tagName,O.typeName,O.className],color:"#5DD8FF"},{tag:O.attributeName,color:"#B281EB"},{tag:[O.propertyName,O.function(O.variableName),O.function(O.propertyName)],color:"#67B7A4"},{tag:O.definition(O.variableName),color:"#4EB0CC"},{tag:[O.variableName,O.operator,O.punctuation,O.bracket],color:"#E8E8ED"},{tag:O.invalid,color:"#FF453A"}]);function Ud(n){const e=n==="dark";return[PS(e?ch.dark:ch.light,e),JO(e?CS:i0)]}const TS=Xt.parser.configure({dialect:"jsx"}),RS=new Map(Object.keys($e.components).map(n=>[n.toLowerCase(),n])),$S=new Set(["VStack","HStack","ZStack","VGrid","HGrid"]),KS=512*1024,ZS=512,MS=32,ci=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},hi=(n,e)=>n.slice(e.from,e.to),de=n=>{throw new Error(n)},Fd=n=>{let e=!0;const t=n.replace(/&([^;\s]+);/g,(i,s)=>{const r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};if(Object.hasOwn(r,s))return r[s];if(/^#(?:[0-9]+|x[0-9a-f]+)$/i.test(s)){const o=s[1].toLowerCase()==="x"?parseInt(s.slice(2),16):Number(s.slice(1));if(o>0&&o<=1114111&&!(o>=55296&&o<=57343))return String.fromCodePoint(o)}return e=!1,i});return e?t:void 0};function co(n,e=!1){if(e)return Fd(n.slice(1,-1));const t=n.trim();if(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(t)){const i=Number(t);return Number.isFinite(i)?i:void 0}if(t==="true"||t==="false")return t==="true";if(t.startsWith('"'))try{const i=JSON.parse(t);return typeof i=="string"?i:void 0}catch{}}function vi(n){const e={formatVersion:1,source:n,nodes:[],roots:[],issue:""};if(typeof n!="string"||new TextEncoder().encode(n).length>KS)return{...e,issue:"Layout editing supports source files up to 512 KiB."};const t=TS.parse(n);let i=!1;if(t.iterate({enter:r=>{r.type.isError&&(i=!0)}}),i)return{...e,issue:"Fix the JavaScript/JSX syntax before using Layout. Your source is preserved."};function s(r,o,a){(a>MS||e.nodes.length>=ZS)&&de("Layout editing supports up to 512 layers and 32 nesting levels.");const l=ci(r),c=l[0],h=l.at(-1),u=ci(c).find(S=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(S.name)),f=u?hi(n,u):"Fragment",d=RS.get(f.toLowerCase()),p=$e.components[d],m={...$e.globalProperties,...p?.properties??{}},g=c.name==="JSXOpenTag"&&h?.name==="JSXCloseTag",y=g?ci(h).find(S=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(S.name)):null;u&&g&&(!y||hi(n,y)!==f)&&de("Opening and closing JSX tags must match before using Layout.");const b={id:String(r.from),parentID:o,tag:f,component:d??null,from:r.from,to:r.to,openingEnd:c.to,insertAt:c.to-(g?1:2),contentFrom:c.to,contentTo:g?h.from:c.to,children:[],properties:[],locked:!p,structure:!1,text:null,textEditable:!1,depth:a};let x=!1;for(const S of ci(c)){if(S.name==="JSXSpreadAttribute"&&(x=!0),S.name!=="JSXAttribute")continue;const w=ci(S),U=hi(n,w[0]),F=w[2],V=F?co(hi(n,F),F.name==="JSXAttributeValue"):!0,E=F?.name==="JSXEscape"?co(n.slice(F.from+1,F.to-1)):V,M=Object.hasOwn(m,U)?m[U]:null;b.properties.push({name:U,value:E??null,from:S.from,to:S.to,editable:!!(p&&M&&M.type!=="function"&&E!==void 0),definition:M??null})}const C=new Set(b.properties.map(S=>S.name)).size!==b.properties.length;b.locked||=x||C,b.reason=x?"Spread properties are preserved; edit this element in Code.":C?"Duplicate properties are preserved; resolve them in Code.":p?"":"Custom components and fragments are preserved; edit them in Code.",b.locked&&b.properties.forEach(S=>{S.editable=!1}),e.nodes.push(b);const k=g?l.slice(1,-1):[];for(const S of k)S.name==="JSXElement"&&b.children.push(s(S,b.id,a+1).id);if(b.structure=!b.locked&&g&&$S.has(d)&&k.every(S=>S.name==="JSXElement"||S.name==="JSXText"&&!hi(n,S).trim())&&b.children.every(S=>!e.nodes.find(w=>w.id===S).locked),!b.locked&&d==="Text"&&g&&k.length===1){const S=k[0],w=hi(n,S),U=S.name==="JSXText"&&!/[\r\n]/.test(w)?Fd(w):S.name==="JSXEscape"?co(w.slice(1,-1)):void 0;typeof U=="string"&&(b.text=U,b.textEditable=!0)}return b}try{t.iterate({enter(r){if(r.name!=="CallExpression")return;const o=ci(r.node);if(o[0]?.name!=="VariableName"||hi(n,o[0])!=="$render"||o[1]?.name!=="ArgList")return;const a=ci(o[1]).filter(l=>!["(",")"].includes(l.name));if(a.length===1&&a[0].name==="JSXElement")return e.roots.push(s(a[0],null,0).id),!1}})}catch(r){return{...e,nodes:[],roots:[],issue:r.message}}return e.roots.length||(e.issue="Layout needs a direct $render(<VStack>…</VStack>) or another native JSX element. Variables, loops and functions stay editable in Code."),e}function ha(n){return!n?.component||n.locked?{}:{...$e.globalProperties,...$e.components[n.component]?.properties??{}}}function ES(n,e,t){(n.source!==e||n.issue)&&de("Layout changed. Select the layer again before editing.");const i=n.nodes.find(l=>l.id===t.id);(!i||i.locked)&&de("This layer is locked. Edit its source in Code.");let s=[],r=i.from;if(t.type==="property"){const l=ha(i),c=Object.hasOwn(l,t.name)?l[t.name]:null,h=i.properties.find(d=>d.name===t.name);(!c||c.type==="function"||h&&!h.editable)&&de("Dynamic or unsupported properties must be edited in Code.");const u=new Set(i.properties.map(d=>d.name)),f=$e.components[i.component];if(t.remove?(f.requiredAny?.includes(t.name)&&!f.requiredAny.some(d=>d!==t.name&&u.has(d))&&de("Keep at least one required component property."),Object.entries(f.properties??{}).some(([d,p])=>u.has(d)&&p.requires?.includes(t.name))&&de("Another property requires this value. Edit the dependent properties together in Code.")):(c.requires?.some(d=>!u.has(d))&&de("Add the required related properties together in Code."),(c.conflicts?.some(d=>u.has(d))||Object.entries(f.properties??{}).some(([d,p])=>d!==t.name&&u.has(d)&&p.conflicts?.includes(t.name)))&&de("This property conflicts with another component property.")),t.remove)(!h||c.required)&&de("This property cannot be removed."),s=[{from:h.from,to:h.to,insert:""}];else{const d=t.value;(!["string","number","boolean"].includes(typeof d)||typeof d=="number"&&!Number.isFinite(d)||typeof d=="string"&&d.length>8192)&&de("Use a bounded string, finite number or Boolean."),c.values&&!c.values.includes(d)&&de("Choose one of the supported property values."),c.type==="boolean"&&typeof d!="boolean"&&de("This property needs true or false."),c.type==="number"&&!(typeof d=="number"||typeof d=="string"&&d.trim()&&Number.isFinite(Number(d)))&&de("This property needs a number."),typeof d=="boolean"&&c.type!=="boolean"&&de("This property does not accept a Boolean."),typeof d=="number"&&!c.type.includes("number")&&de("This property needs a string value."),t.name==="opacity"&&!(Number(d)>=0&&Number(d)<=1)&&de("Opacity must be between zero and one.");const p=`${t.name}={${JSON.stringify(d)}}`;s=h?[{from:h.from,to:h.to,insert:p}]:[{from:i.insertAt,to:i.insertAt,insert:` ${p}`}]}}else if(t.type==="text")(!i.textEditable||typeof t.value!="string"||t.value.length>8192)&&de("Dynamic text is preserved. Edit it in Code."),s=[{from:i.contentFrom,to:i.contentTo,insert:`{${JSON.stringify(t.value)}}`}];else if(t.type==="move"||t.type==="remove")if(n.nodes.find(c=>c.id===i.parentID)?.structure||de("Only literal children of a supported stack/grid can be moved or removed."),t.type==="remove")s=[{from:i.from,to:i.to,insert:""}];else{const c=n.nodes.find(p=>p.id===t.parentID);(!c?.structure||c.from>=i.from&&c.to<=i.to)&&de("Choose a supported container outside this layer.");const h=p=>{for(;p.parentID!==null;)p=n.nodes.find(m=>m.id===p.parentID);return p.id};h(i)!==h(c)&&de("Layers cannot move between render branches or JavaScript scopes.");const u=c.children.filter(p=>p!==i.id),f=t.index;(!Number.isInteger(f)||f<0||f>u.length)&&de("Invalid layer position.");const d=f===u.length?c.contentTo:n.nodes.find(p=>p.id===u[f]).from;if(d===i.from||d===i.to)return{changes:[],selectedFrom:r};s=[{from:i.from,to:i.to,insert:""},{from:d,to:d,insert:e.slice(i.from,i.to)}],r=d-(d>i.to?i.to-i.from:0)}else if(t.type==="add"){i.structure||de("Choose a supported container with literal JSX children.");const l={text:'<text font="headline">New text</text>',spacer:"<spacer/>",stack:'<vstack spacing="8"></vstack>',icon:'<icon systemName="star.fill" size="20"/>'};Object.hasOwn(l,t.kind)||de("Unsupported new layer."),s=[{from:i.contentTo,to:i.contentTo,insert:l[t.kind]}],r=i.contentTo}else de("Unsupported layout operation.");s.sort((l,c)=>l.from-c.from);let o=e;for(const l of[...s].reverse())o=o.slice(0,l.from)+l.insert+o.slice(l.to);return vi(o).issue&&de("This edit would leave the supported layout. Your source was not changed."),{changes:s,selectedFrom:r}}const Dd=Xt.parser.configure({dialect:"jsx"}),Ci=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},Qe=n=>{throw new Error(n)},Hi=Object.freeze({background:{type:"color"},surface:{type:"color"},foreground:{type:"color"},muted:{type:"color"},accent:{type:"color"},titleFont:{values:$e.globalProperties.font.values},bodyFont:{values:$e.globalProperties.font.values},fontDesign:{values:$e.globalProperties.fontDesign.values},corner:{type:"number",maximum:48},padding:{type:"number",maximum:48},spacing:{type:"number",maximum:32}}),ms={titleFont:"headline",bodyFont:"caption",fontDesign:"rounded",corner:20,padding:16,spacing:10},sr=Object.freeze({Meadow:Object.freeze({...ms,background:"#F2FAF5",surface:"#FFFFFF",foreground:"#193F31",muted:"#607C70",accent:"#328963"}),Paper:Object.freeze({...ms,background:"#F4F7FD",surface:"#FFFFFF",foreground:"#243454",muted:"#687795",accent:"#4777D6"}),Peach:Object.freeze({...ms,background:"#FFF5EE",surface:"#FFFFFF",foreground:"#56392C",muted:"#967461",accent:"#C86B43"}),Midnight:Object.freeze({...ms,background:"#192332",surface:"#283548",foreground:"#F1F5FC",muted:"#AABAD0",accent:"#8EB7FF"})});function Ld(n,e){Object.hasOwn(Hi,n)||Qe("Unknown theme token.");const t=Hi[n];t.type==="color"&&!(typeof e=="string"&&/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i.test(e))&&Qe(`${n} needs a six or eight digit hex color.`),t.values&&!t.values.includes(e)&&Qe(`${n} needs a supported font value.`),t.type==="number"&&!(typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=t.maximum)&&Qe(`${n} needs a number from zero to ${t.maximum}.`)}function el(n){(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==Object.keys(Hi).length)&&Qe("A theme needs exactly the documented tokens.");for(const e of Object.keys(n))Ld(e,n[e]);return n}function Xd(n){(typeof n!="string"||new TextEncoder().encode(n).length>4096)&&Qe("Theme JSON is limited to 4 KiB.");const e=JSON.parse(n);return(!e||Array.isArray(e)||Object.keys(e).sort().join()!=="formatVersion,name,tokens"||e.formatVersion!==1||typeof e.name!="string"||!e.name.trim()||/[\u0000-\u001f]/.test(e.name)||new TextEncoder().encode(e.name).length>64)&&Qe("Use a version 1 theme with a name of at most 64 bytes."),el(e.tokens),e}function US(n,e="My theme"){const t=JSON.stringify({formatVersion:1,name:e,tokens:n},null,2);return Xd(t),t}function rr(n){const e={source:n,tokens:null,ranges:{},issue:"",canInitialize:!1};try{(typeof n!="string"||new TextEncoder().encode(n).length>512*1024)&&Qe("Theme editing supports files up to 512 KiB.");const t=Dd.parse(n),i=[],s=[];if(t.iterate({enter(l){l.type.isError&&Qe("Fix JavaScript syntax before editing the theme."),["VariableDefinition","VariableName"].includes(l.name)&&n.slice(l.from,l.to).includes("\\")&&Qe("Escaped identifiers stay in Code."),n.slice(l.from,l.to)==="widgetTheme"&&["VariableDefinition","VariableName"].includes(l.name)&&(l.name==="VariableDefinition"?i:s).push(l.node)}}),!i.length&&!s.length){const l=vi(n);e.canInitialize=!l.issue&&l.roots.length===1&&!l.nodes[0].locked;let c=!1;for(const h of Ci(t.topNode)){const u=h.firstChild;l.nodes[0]&&h.name==="ExpressionStatement"&&u?.name==="CallExpression"&&n.slice(u.firstChild.from,u.firstChild.to)==="$render"&&u.from<l.nodes[0].from&&u.to>l.nodes[0].to&&(c=!0)}return e.canInitialize&&=c,e}i.length!==1&&Qe("Keep one top-level const widgetTheme object. Other bindings stay in Code.");const r=i[0].parent,o=Ci(r);(r.name!=="VariableDeclaration"||r.parent?.name!=="Script"||o[0]?.name!=="const"||o[1]?.from!==i[0].from||o[2]?.name!=="Equals"||o[3]?.name!=="ObjectExpression"||o.slice(4).some(l=>l.name!==";"))&&Qe("Theme editing needs a single top-level const widgetTheme = { … } declaration.");const a={};for(const l of Ci(o[3])){if(["{","}",","].includes(l.name))continue;const c=Ci(l),h=c[0]?n.slice(c[0].from,c[0].to):"",u=c[0]?.name==="String"&&h.startsWith('"')?JSON.parse(h):h;(l.name!=="Property"||c.length!==3||!["PropertyDefinition","String"].includes(c[0].name)||c[1].name!==":"||!["String","Number"].includes(c[2].name)||Object.hasOwn(a,u))&&Qe("Theme tokens must be unique literal properties. Computed or dynamic values stay in Code.");let f;try{f=JSON.parse(n.slice(c[2].from,c[2].to))}catch{Qe("Theme values use JSON strings or numbers. Edit this declaration in Code.")}Ld(u,f),a[u]=f,e.ranges[u]={from:c[2].from,to:c[2].to}}el(a);for(const l of s){const c=l.parent,h=Ci(c),u=h[2]?n.slice(h[2].from,h[2].to):"";(c.name!=="MemberExpression"||h[0].from!==l.from||h[1]?.name!=="."||h[2]?.name!=="PropertyName"||!Object.hasOwn(Hi,u))&&Qe("Theme references must read widgetTheme.token. Other uses stay in Code."),c.parent?.name==="MemberExpression"&&Qe("Mutable theme references stay in Code.");for(let f=c.parent;f;f=f.parent)(["UpdateExpression","PostfixExpression"].includes(f.name)||f.name==="UnaryExpression"&&/^(?:delete|\+\+|--)/.test(n.slice(f.from,c.from).trim())||f.name==="AssignmentExpression"&&f.firstChild.from<=c.from&&f.firstChild.to>=c.to||f.name==="ForOfSpec"||f.name==="ForInSpec")&&Qe("Mutable theme references stay in Code.")}e.tokens=a}catch(t){e.issue=t.message}return e}function ho(n,e,t){return(n.source!==e||n.issue||!n.tokens)&&Qe("Theme changed or is unsupported. Reopen Theme before editing."),el(t),{changes:Object.keys(Hi).filter(s=>t[s]!==n.tokens[s]).map(s=>({...n.ranges[s],insert:JSON.stringify(t[s])})).sort((s,r)=>s.from-r.from)}}function FS(n,e="Meadow"){(!rr(n).canInitialize||!Object.hasOwn(sr,e))&&Qe("Start with a literal top-level layout without an existing widgetTheme binding.");const i=vi(n),s=i.nodes[0],r=[];function o(c,h,u,f=!1){const d=c.properties.find(m=>m.name===h);if(c.locked||d&&!d.editable||!d&&!f)return;const p=`${h}={widgetTheme.${u}}`;r.push(d?{from:d.from,to:d.to,insert:p}:{from:c.insertAt,to:c.insertAt,insert:` ${p}`})}for(const c of["background","corner","padding"])o(s,c,c,!0);s.structure&&o(s,"spacing","spacing",!0);for(const c of i.nodes)if(c.component==="Text"){const h=c.properties.find(f=>f.name==="font")?.value,u=["headline","largeTitle","title","title2","title3"].includes(h);o(c,"font",u?"titleFont":"bodyFont",!0),o(c,"color",u?"foreground":"muted",!0),o(c,"fontDesign","fontDesign",!0)}else c.component==="Icon"&&o(c,"color","accent",!0);let a=0;for(const c of Ci(Dd.parse(n).topNode))if(!(c.name==="LineComment"||c.name==="BlockComment"))if(c.name==="ExpressionStatement"&&c.firstChild?.name==="String")a=c.to;else break;r.push({from:a,to:a,insert:` -const widgetTheme = ${JSON.stringify(sr[e],null,2)}; -`}),r.sort((c,h)=>c.from-h.from);let l=n;for(const c of[...r].reverse())l=l.slice(0,c.from)+c.insert+l.slice(c.to);return(!rr(l).tokens||vi(l).issue)&&Qe("This layout cannot be themed automatically. Your source was preserved."),{changes:r}}function Bd(n){if(!Array.isArray(n)||n.length>4096)return[];const e=new Map,t=new Set;for(const i of n){if(typeof i!="string"||new TextEncoder().encode(i).length>1024||/[\\\u0000-\u001f\u007f-\u009f]/.test(i))continue;const s=i.split("/");if(s.length!==2||s[0]!=="image"||!s[1]||new TextEncoder().encode(s[1]).length>255||s[1]!==s[1].trim()||s[1].includes("..")||!/\.(png|jpe?g|webp)$/i.test(s[1]))continue;const r=i.normalize("NFC").toLowerCase();e.has(r)&&e.get(r)!==i&&t.add(r),e.set(r,i)}return[...e].filter(([i])=>!t.has(i)).map(([,i])=>i).sort().slice(0,256)}const tl=z.define(),or=Te.define({create:()=>[],update(n,e){for(const t of e.effects)t.is(tl)&&(n=Bd(t.value));return n}});function il(n,e){n.state.field(or,!1)!==void 0&&n.dispatch({effects:tl.of(e)})}const Id=Object.freeze({bloom:Object.freeze({name:"Bloom mark",description:"A small four-petal flower",kind:"icon"}),leaf:Object.freeze({name:"Leaf mark",description:"A tilted leaf and stem",kind:"icon"}),pebble:Object.freeze({name:"Pebble friend",description:"A quiet, round-eared companion",kind:"pet"})}),uo=`/* +</${n}>`:`<${n}${i} />`}const hh=Object.entries($e.components).map(([n,e])=>({label:n,type:"class",detail:`ScriptWidget · ${Object.keys(e.properties??{}).length} properties`,info:e.documentation,apply:QS(n,e)}));function PS(n){const e=n.match(/<([A-Za-z][\w]*)\b([^<>]*)$/);return!e||e[2].includes(">")?null:{name:e[1],attributes:e[2]}}function CS(n,e){const t=$e.components[n];return t?Object.entries({...$e.globalProperties,...t.properties??{}}).filter(([i])=>!e.has(i)).map(([i,s])=>({label:i,type:"property",detail:s.required?`${s.type} · required`:s.type,info:s.deprecated?`Deprecated: ${s.deprecated}`:s.documentation,apply:`${i}=${s.type.includes("number")||s.type==="boolean"?"{${}}":'"${}"'}`})):[]}function TS(n){const e=n.match(/<([A-Za-z][\w]*)\b[^<>]*\b([A-Za-z][\w]*)\s*=\s*["']([^"']*)$/);if(!e)return null;const t=$e.components[e[1]]?.properties?.[e[2]]??$e.globalProperties[e[2]];return t?.values?{typed:e[3],values:t.values}:null}function RS(n){const e=n.state.doc.sliceString(Math.max(0,n.pos-1200),n.pos),t=TS(e);if(t)return{from:n.pos-t.typed.length,options:t.values.map(o=>({label:o,type:"enum"})),validFor:/^[\w-]*$/};const i=n.matchBefore(/<[A-Za-z]*$/);if(i)return{from:i.from+1,options:hh,validFor:/^[A-Za-z]*$/};const s=PS(e);if(s&&/(?:\s|^)\w*$/.test(s.attributes)){const o=n.matchBefore(/[A-Za-z][\w]*$/),a=new Set([...s.attributes.matchAll(/\b([A-Za-z][\w]*)\s*=/g)].map(l=>l[1]));return{from:o?.from??n.pos,options:CS(s.name,a),validFor:/^[A-Za-z][\w]*$/}}const r=n.matchBefore(/\$[A-Za-z]+\.[A-Za-z]*$/);if(r){const o=r.text.slice(0,r.text.indexOf(".")+1),a=Object.entries($e.functions).filter(([l])=>l.startsWith(o));return a.length?{from:r.from+o.length,options:a.map(([l,c])=>({label:l.slice(o.length),type:"function",detail:c.returns,info:c.documentation})),validFor:/^[A-Za-z]*$/}:null}return n.explicit?{from:n.pos,options:hh,validFor:/^[A-Za-z]*$/}:null}function uh(n,e){const t=[];for(let i=n.node.firstChild;i;i=i.nextSibling)i.name===e&&t.push(i);return t}function Dd(n){const e=[];return Ce(n).iterate({enter(t){if(t.name!=="JSXOpenTag"&&t.name!=="JSXSelfClosingTag")return;const s=uh(t,"JSXIdentifier")[0];s&&e.push({name:n.doc.sliceString(s.from,s.to),from:s.from,to:s.to,attributes:uh(t,"JSXAttribute").map(r=>{const o=r.firstChild;return o?{name:n.doc.sliceString(o.from,o.to),from:o.from,to:o.to}:null}).filter(Boolean)})}}),e}function Ld(n){const e=[];for(const t of Dd(n.state)){const i=$e.components[t.name];if(!i)continue;const s=new Set([...Object.keys($e.globalProperties),...Object.keys(i.properties??{})]),r=new Set(t.attributes.map(o=>o.name));for(const o of t.attributes){s.has(o.name)||e.push({from:o.from,to:o.to,severity:"warning",message:`“${o.name}” is not supported by <${t.name}>.`});const a=i.properties?.[o.name]??$e.globalProperties[o.name];a?.deprecated&&e.push({from:o.from,to:o.to,severity:"warning",message:`${o.name} is deprecated. ${a.deprecated}`})}for(const[o,a]of Object.entries(i.properties??{}))if(a.required&&!r.has(o)&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires the “${o}” property.`}),r.has(o)){for(const l of a.requires??[])r.has(l)||e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> “${o}” requires the “${l}” property.`});for(const l of a.conflicts??[])r.has(l)&&o<l&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> cannot combine “${o}” with “${l}”.`})}i.requiredAny?.length&&!i.requiredAny.some(o=>r.has(o))&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires one of: ${i.requiredAny.map(o=>`“${o}”`).join(", ")}.`})}return e}function $S(n,e){const t=Dd(n.state).find(s=>e>=s.from&&e<=s.to);if(!t)return null;const i=$e.components[t.name];return i?{pos:t.from,end:t.to,above:!0,create(){const s=document.createElement("div");s.className="studio-hover";const r=document.createElement("strong");r.textContent=`<${t.name}>`;const o=document.createElement("p");return o.textContent=i.documentation,s.append(r,o),{dom:s}}}:null}const fh={light:{background:"#FAFAFC",foreground:"#202124",gutter:"#F3F3F6",gutterText:"#8A8A93",activeLine:"#EDEEF3",selection:"#B9D7FF",caret:"#0067C0"},dark:{background:"#1E1F22",foreground:"#E8E8ED",gutter:"#191A1D",gutterText:"#777982",activeLine:"#292A2F",selection:"#315A85",caret:"#65B7FF"}};function KS(n,e){return K.theme({"&":{height:"100%",color:n.foreground,backgroundColor:n.background,fontSize:"13px"},".cm-scroller":{fontFamily:'ui-monospace, "SFMono-Regular", Menlo, Monaco, Consolas, monospace',lineHeight:"1.58",overscrollBehavior:"contain"},".cm-content":{caretColor:n.caret,padding:"12px 0 32px"},".cm-line":{padding:"0 8px"},".cm-cursor, .cm-dropCursor":{borderLeftColor:n.caret},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:n.selection},".cm-activeLine":{backgroundColor:n.activeLine},".cm-gutters":{backgroundColor:n.gutter,color:n.gutterText,border:"none",paddingLeft:"env(safe-area-inset-left)"},".cm-activeLineGutter":{backgroundColor:n.activeLine,color:n.foreground},".cm-foldPlaceholder":{backgroundColor:"transparent",border:`1px solid ${n.gutterText}`,color:n.gutterText},".cm-tooltip":{border:e?"1px solid #41434A":"1px solid #D2D3D8",backgroundColor:e?"#292A2F":"#FFFFFF",borderRadius:"8px",overflow:"hidden",boxShadow:"0 8px 28px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete ul li[aria-selected]":{backgroundColor:e?"#315A85":"#DCEBFA",color:n.foreground},".cm-panels":{backgroundColor:n.gutter,color:n.foreground},".cm-searchMatch":{backgroundColor:e?"#725C1D":"#FFE69A"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:e?"#8D6D20":"#FFD45C"}},{dark:e})}const ZS=Bn.define([{tag:[O.keyword,O.controlKeyword,O.moduleKeyword,O.operatorKeyword,O.bool,O.null],color:"#FF7AB2"},{tag:[O.string,O.special(O.string)],color:"#FF8170"},{tag:[O.number,O.regexp],color:"#D9C97C"},{tag:[O.comment,O.lineComment,O.blockComment],color:"#7F8C98",fontStyle:"italic"},{tag:[O.tagName,O.typeName,O.className],color:"#5DD8FF"},{tag:O.attributeName,color:"#B281EB"},{tag:[O.propertyName,O.function(O.variableName),O.function(O.propertyName)],color:"#67B7A4"},{tag:O.definition(O.variableName),color:"#4EB0CC"},{tag:[O.variableName,O.operator,O.punctuation,O.bracket],color:"#E8E8ED"},{tag:O.invalid,color:"#FF453A"}]);function Xd(n){const e=n==="dark";return[KS(e?fh.dark:fh.light,e),s0(e?ZS:a0)]}const MS=Bt.parser.configure({dialect:"jsx"}),ES=new Map(Object.keys($e.components).map(n=>[n.toLowerCase(),n])),US=new Set(["VStack","HStack","ZStack","VGrid","HGrid"]),FS=512*1024,DS=512,LS=32,hi=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},Ft=(n,e)=>n.slice(e.from,e.to),de=n=>{throw new Error(n)},fa=n=>{let e=!0;const t=n.replace(/&([^;\s]+);/g,(i,s)=>{const r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};if(Object.hasOwn(r,s))return r[s];if(/^#(?:[0-9]+|x[0-9a-f]+)$/i.test(s)){const o=s[1].toLowerCase()==="x"?parseInt(s.slice(2),16):Number(s.slice(1));if(o>0&&o<=1114111&&!(o>=55296&&o<=57343))return String.fromCodePoint(o)}return e=!1,i});return e?t:void 0},Bd=(n,e)=>n.lastIndexOf(` +`,e-1)+1,XS=(n,e)=>{const t=n.indexOf(` +`,e);return t<0?n.length:t},Mn=n=>!/\S/.test(n);function Id(n,e,t){const i=Bd(n,e),s=XS(n,t);return!Mn(n.slice(i,e))||!Mn(n.slice(t,s))?null:{start:i,end:Math.min(s+1,n.length),indent:n.slice(i,e)}}const gs=(n,e,t)=>e===null?n:n.split(` +`).map((i,s)=>s&&i.startsWith(e)?t+i.slice(e.length):i).join(` +`);function uo(n,e=!1){if(e)return fa(n.slice(1,-1));const t=n.trim();if(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(t)){const i=Number(t);return Number.isFinite(i)?i:void 0}if(t==="true"||t==="false")return t==="true";if(t.startsWith('"'))try{const i=JSON.parse(t);return typeof i=="string"?i:void 0}catch{}}function vi(n){const e={formatVersion:1,source:n,nodes:[],roots:[],issue:""};if(typeof n!="string"||new TextEncoder().encode(n).length>FS)return{...e,issue:"Layout editing supports source files up to 512 KiB."};const t=new Set,i=n.replace(/\{\s*(?:\/\*[\s\S]*?\*\/\s*)+\}/g,(a,l)=>(t.add(l),`{0${a.slice(2,-1).replace(/[^\r\n]/g," ")}}`)),s=MS.parse(i);let r=!1;if(s.iterate({enter:a=>{a.type.isError&&(r=!0)}}),r)return{...e,issue:"Fix the JavaScript/JSX syntax before using Layout. Your source is preserved."};function o(a,l,c){(c>LS||e.nodes.length>=DS)&&de("Layout editing supports up to 512 layers and 32 nesting levels.");const h=hi(a),u=h[0],f=h.at(-1),d=hi(u).find(T=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(T.name)),p=d?Ft(n,d):"Fragment",m=ES.get(p.toLowerCase()),g=$e.components[m],y={...$e.globalProperties,...g?.properties??{}},x=u.name==="JSXOpenTag"&&f?.name==="JSXCloseTag",b=x?hi(f).find(T=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(T.name)):null;d&&x&&(!b||Ft(n,b)!==p)&&de("Opening and closing JSX tags must match before using Layout.");const C={id:String(a.from),parentID:l,tag:p,component:m??null,from:a.from,to:a.to,openingEnd:u.to,insertAt:u.to-(x?1:2),contentFrom:u.to,contentTo:x?f.from:u.to,children:[],properties:[],locked:!g,structure:!1,text:null,textEditable:!1,depth:c,outerFrom:a.from,textFrom:0,textTo:0};let Q=!1;for(const T of hi(u)){if(T.name==="JSXSpreadAttribute"&&(Q=!0),T.name!=="JSXAttribute")continue;const v=hi(T),M=Ft(n,v[0]),k=v[2],z=k?uo(Ft(n,k),k.name==="JSXAttributeValue"):!0,re=k?.name==="JSXEscape"?uo(n.slice(k.from+1,k.to-1)):z,N=Object.hasOwn(y,M)?y[M]:null;C.properties.push({name:M,value:re??null,from:T.from,to:T.to,editable:!!(g&&N&&N.type!=="function"&&re!==void 0),definition:N??null})}const P=new Set(C.properties.map(T=>T.name)).size!==C.properties.length;C.locked||=Q||P,C.reason=Q?"Spread properties are preserved; edit this element in Code.":P?"Duplicate properties are preserved; resolve them in Code.":g?"":"Custom components and fragments are preserved; edit them in Code.",C.locked&&C.properties.forEach(T=>{T.editable=!1}),e.nodes.push(C);const w=x?h.slice(1,-1):[],L=T=>T.name==="JSXEscape"&&t.has(T.from),D=w.filter(T=>!L(T));let W=null;for(const T of w){if(L(T)){W??=T.from;continue}const v=Ft(n,T);if(T.name==="JSXText"&&Mn(v)){W!==null&&v.split(` +`).length>2&&(W=null);continue}if(T.name==="JSXElement"){const M=o(T,C.id,c+1);M.outerFrom=W??M.from,C.children.push(M.id)}W=null}C.structure=!C.locked&&x&&US.has(m)&&D.every(T=>T.name==="JSXElement"||T.name==="JSXText"&&!Ft(n,T).trim())&&C.children.every(T=>!e.nodes.find(v=>v.id===T).locked);const F=w.length!==D.length,U=F?D.filter(T=>!(T.name==="JSXText"&&Mn(Ft(n,T)))):D;if(!C.locked&&m==="Text"&&x&&U.length===1){const T=U[0],v=Ft(n,T),M=/[\r\n]/.test(v)&&!/[\r\n]/.test(v.trim())?v.trim():null,k=T.name==="JSXText"&&M?fa(M):T.name==="JSXText"&&!/[\r\n]/.test(v)?fa(v):T.name==="JSXEscape"?uo(v.slice(1,-1)):void 0;if(typeof k=="string"){C.text=k,C.textEditable=!0;const z=T.name==="JSXText"?[v.length-v.trimStart().length,v.length-v.trimEnd().length]:[0,0];[C.textFrom,C.textTo]=F?[T.from+z[0],T.to-z[1]]:[C.contentFrom,C.contentTo]}}return C}try{s.iterate({enter(a){if(a.name!=="CallExpression")return;const l=hi(a.node);if(l[0]?.name!=="VariableName"||Ft(n,l[0])!=="$render"||l[1]?.name!=="ArgList")return;const c=hi(l[1]).filter(h=>!["(",")",",","LineComment","BlockComment"].includes(h.name));if(c.length===1&&c[0].name==="JSXElement")return e.roots.push(o(c[0],null,0).id),!1}})}catch(a){return{...e,nodes:[],roots:[],issue:a.message}}return e.roots.length||(e.issue="Layout needs a direct $render(<VStack>…</VStack>) or another native JSX element. Variables, loops and functions stay editable in Code."),e}function da(n){return!n?.component||n.locked?{}:{...$e.globalProperties,...$e.components[n.component]?.properties??{}}}function dh(n,e,t,i,s,r,o,a){const l=y=>n.nodes.find(x=>x.id===y),c=s===i.length,h=c?t.contentTo:l(i[s]).outerFrom,u=Bd(e,h),f=e.slice(u,h);if(!Mn(f)||u===0)return{change:{from:h,to:h,insert:r},offset:o};const d=r.slice(0,o);if(!c)return{change:{from:h,to:h,insert:`${gs(r,a,f)} +${f}`},offset:gs(d,a,f).length};const p=i.length?l(i[0]):null,m=p?Id(e,p.outerFrom,p.to):null,g=m?m.indent:`${f} `;return{change:{from:u,to:u,insert:`${g}${gs(r,a,g)} +`},offset:g.length+gs(d,a,g).length}}function BS(n,e,t){(n.source!==e||n.issue)&&de("Layout changed. Select the layer again before editing.");const i=n.nodes.find(l=>l.id===t.id);(!i||i.locked)&&de("This layer is locked. Edit its source in Code.");let s=[],r=i.from;if(t.type==="property"){const l=da(i),c=Object.hasOwn(l,t.name)?l[t.name]:null,h=i.properties.find(d=>d.name===t.name);(!c||c.type==="function"||h&&!h.editable)&&de("Dynamic or unsupported properties must be edited in Code.");const u=new Set(i.properties.map(d=>d.name)),f=$e.components[i.component];if(t.remove?(f.requiredAny?.includes(t.name)&&!f.requiredAny.some(d=>d!==t.name&&u.has(d))&&de("Keep at least one required component property."),Object.entries(f.properties??{}).some(([d,p])=>u.has(d)&&p.requires?.includes(t.name))&&de("Another property requires this value. Edit the dependent properties together in Code.")):(c.requires?.some(d=>!u.has(d))&&de("Add the required related properties together in Code."),(c.conflicts?.some(d=>u.has(d))||Object.entries(f.properties??{}).some(([d,p])=>d!==t.name&&u.has(d)&&p.conflicts?.includes(t.name)))&&de("This property conflicts with another component property.")),t.remove)(!h||c.required)&&de("This property cannot be removed."),s=[{from:h.from,to:h.to,insert:""}];else{const d=t.value;(!["string","number","boolean"].includes(typeof d)||typeof d=="number"&&!Number.isFinite(d)||typeof d=="string"&&d.length>8192)&&de("Use a bounded string, finite number or Boolean."),c.values&&!c.values.includes(d)&&de("Choose one of the supported property values."),c.type==="boolean"&&typeof d!="boolean"&&de("This property needs true or false."),c.type==="number"&&!(typeof d=="number"||typeof d=="string"&&d.trim()&&Number.isFinite(Number(d)))&&de("This property needs a number."),typeof d=="boolean"&&c.type!=="boolean"&&de("This property does not accept a Boolean."),typeof d=="number"&&!c.type.includes("number")&&de("This property needs a string value."),t.name==="opacity"&&!(Number(d)>=0&&Number(d)<=1)&&de("Opacity must be between zero and one.");const p=`${t.name}={${JSON.stringify(d)}}`;s=h?[{from:h.from,to:h.to,insert:p}]:[{from:i.insertAt,to:i.insertAt,insert:` ${p}`}]}}else if(t.type==="text")(!i.textEditable||typeof t.value!="string"||t.value.length>8192)&&de("Dynamic text is preserved. Edit it in Code."),s=[{from:i.textFrom,to:i.textTo,insert:`{${JSON.stringify(t.value)}}`}];else if(t.type==="move"||t.type==="remove"){const l=n.nodes.find(u=>u.id===i.parentID);l?.structure||de("Only literal children of a supported stack/grid can be moved or removed.");const c=Id(e,i.outerFrom,i.to),h=c?{from:c.start,to:c.end,insert:""}:{from:i.outerFrom,to:i.to,insert:""};if(t.type==="remove")s=[h];else{const u=n.nodes.find(g=>g.id===t.parentID);(!u?.structure||u.from>=i.from&&u.to<=i.to)&&de("Choose a supported container outside this layer.");const f=g=>{for(;g.parentID!==null;)g=n.nodes.find(y=>y.id===g.parentID);return g.id};f(i)!==f(u)&&de("Layers cannot move between render branches or JavaScript scopes.");const d=u.children.filter(g=>g!==i.id),p=t.index;if((!Number.isInteger(p)||p<0||p>d.length)&&de("Invalid layer position."),u.id===l.id&&u.children.indexOf(i.id)===p)return{changes:[],selectedFrom:r};const m=dh(n,e,u,d,p,e.slice(i.outerFrom,i.to),i.from-i.outerFrom,c?c.indent:null);s=[h,m.change],r=m.change.from-(m.change.from>=h.to?h.to-h.from:0)+m.offset}}else if(t.type==="add"){i.structure||de("Choose a supported container with literal JSX children.");const l={text:'<text font="headline">New text</text>',spacer:"<spacer/>",stack:'<vstack spacing="8"></vstack>',icon:'<icon systemName="star.fill" size="20"/>'};Object.hasOwn(l,t.kind)||de("Unsupported new layer.");const c=dh(n,e,i,i.children,i.children.length,l[t.kind],0,null);s=[c.change],r=c.change.from+c.offset}else de("Unsupported layout operation.");s.sort((l,c)=>l.from-c.from);let o=e;for(const l of[...s].reverse())o=o.slice(0,l.from)+l.insert+o.slice(l.to);return vi(o).issue&&de("This edit would leave the supported layout. Your source was not changed."),{changes:s,selectedFrom:r}}const Wd=Bt.parser.configure({dialect:"jsx"}),Ci=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},Qe=n=>{throw new Error(n)},Hi=Object.freeze({background:{type:"color"},surface:{type:"color"},foreground:{type:"color"},muted:{type:"color"},accent:{type:"color"},titleFont:{values:$e.globalProperties.font.values},bodyFont:{values:$e.globalProperties.font.values},fontDesign:{values:$e.globalProperties.fontDesign.values},corner:{type:"number",maximum:48},padding:{type:"number",maximum:48},spacing:{type:"number",maximum:32}}),Os={titleFont:"headline",bodyFont:"caption",fontDesign:"rounded",corner:20,padding:16,spacing:10},or=Object.freeze({Meadow:Object.freeze({...Os,background:"#F2FAF5",surface:"#FFFFFF",foreground:"#193F31",muted:"#607C70",accent:"#328963"}),Paper:Object.freeze({...Os,background:"#F4F7FD",surface:"#FFFFFF",foreground:"#243454",muted:"#687795",accent:"#4777D6"}),Peach:Object.freeze({...Os,background:"#FFF5EE",surface:"#FFFFFF",foreground:"#56392C",muted:"#967461",accent:"#C86B43"}),Midnight:Object.freeze({...Os,background:"#192332",surface:"#283548",foreground:"#F1F5FC",muted:"#AABAD0",accent:"#8EB7FF"})});function qd(n,e){Object.hasOwn(Hi,n)||Qe("Unknown theme token.");const t=Hi[n];t.type==="color"&&!(typeof e=="string"&&/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i.test(e))&&Qe(`${n} needs a six or eight digit hex color.`),t.values&&!t.values.includes(e)&&Qe(`${n} needs a supported font value.`),t.type==="number"&&!(typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=t.maximum)&&Qe(`${n} needs a number from zero to ${t.maximum}.`)}function nl(n){(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==Object.keys(Hi).length)&&Qe("A theme needs exactly the documented tokens.");for(const e of Object.keys(n))qd(e,n[e]);return n}function zd(n){(typeof n!="string"||new TextEncoder().encode(n).length>4096)&&Qe("Theme JSON is limited to 4 KiB.");const e=JSON.parse(n);return(!e||Array.isArray(e)||Object.keys(e).sort().join()!=="formatVersion,name,tokens"||e.formatVersion!==1||typeof e.name!="string"||!e.name.trim()||/[\u0000-\u001f]/.test(e.name)||new TextEncoder().encode(e.name).length>64)&&Qe("Use a version 1 theme with a name of at most 64 bytes."),nl(e.tokens),e}function IS(n,e="My theme"){const t=JSON.stringify({formatVersion:1,name:e,tokens:n},null,2);return zd(t),t}function ar(n){const e={source:n,tokens:null,ranges:{},issue:"",canInitialize:!1};try{(typeof n!="string"||new TextEncoder().encode(n).length>512*1024)&&Qe("Theme editing supports files up to 512 KiB.");const t=Wd.parse(n),i=[],s=[];if(t.iterate({enter(l){l.type.isError&&Qe("Fix JavaScript syntax before editing the theme."),["VariableDefinition","VariableName"].includes(l.name)&&n.slice(l.from,l.to).includes("\\")&&Qe("Escaped identifiers stay in Code."),n.slice(l.from,l.to)==="widgetTheme"&&["VariableDefinition","VariableName"].includes(l.name)&&(l.name==="VariableDefinition"?i:s).push(l.node)}}),!i.length&&!s.length){const l=vi(n);e.canInitialize=!l.issue&&l.roots.length===1&&!l.nodes[0].locked;let c=!1;for(const h of Ci(t.topNode)){const u=h.firstChild;l.nodes[0]&&h.name==="ExpressionStatement"&&u?.name==="CallExpression"&&n.slice(u.firstChild.from,u.firstChild.to)==="$render"&&u.from<l.nodes[0].from&&u.to>l.nodes[0].to&&(c=!0)}return e.canInitialize&&=c,e}i.length!==1&&Qe("Keep one top-level const widgetTheme object. Other bindings stay in Code.");const r=i[0].parent,o=Ci(r);(r.name!=="VariableDeclaration"||r.parent?.name!=="Script"||o[0]?.name!=="const"||o[1]?.from!==i[0].from||o[2]?.name!=="Equals"||o[3]?.name!=="ObjectExpression"||o.slice(4).some(l=>l.name!==";"))&&Qe("Theme editing needs a single top-level const widgetTheme = { … } declaration.");const a={};for(const l of Ci(o[3])){if(["{","}",","].includes(l.name))continue;const c=Ci(l),h=c[0]?n.slice(c[0].from,c[0].to):"",u=c[0]?.name==="String"&&h.startsWith('"')?JSON.parse(h):h;(l.name!=="Property"||c.length!==3||!["PropertyDefinition","String"].includes(c[0].name)||c[1].name!==":"||!["String","Number"].includes(c[2].name)||Object.hasOwn(a,u))&&Qe("Theme tokens must be unique literal properties. Computed or dynamic values stay in Code.");let f;try{f=JSON.parse(n.slice(c[2].from,c[2].to))}catch{Qe("Theme values use JSON strings or numbers. Edit this declaration in Code.")}qd(u,f),a[u]=f,e.ranges[u]={from:c[2].from,to:c[2].to}}nl(a);for(const l of s){const c=l.parent,h=Ci(c),u=h[2]?n.slice(h[2].from,h[2].to):"";(c.name!=="MemberExpression"||h[0].from!==l.from||h[1]?.name!=="."||h[2]?.name!=="PropertyName"||!Object.hasOwn(Hi,u))&&Qe("Theme references must read widgetTheme.token. Other uses stay in Code."),c.parent?.name==="MemberExpression"&&Qe("Mutable theme references stay in Code.");for(let f=c.parent;f;f=f.parent)(["UpdateExpression","PostfixExpression"].includes(f.name)||f.name==="UnaryExpression"&&/^(?:delete|\+\+|--)/.test(n.slice(f.from,c.from).trim())||f.name==="AssignmentExpression"&&f.firstChild.from<=c.from&&f.firstChild.to>=c.to||f.name==="ForOfSpec"||f.name==="ForInSpec")&&Qe("Mutable theme references stay in Code.")}e.tokens=a}catch(t){e.issue=t.message}return e}function fo(n,e,t){return(n.source!==e||n.issue||!n.tokens)&&Qe("Theme changed or is unsupported. Reopen Theme before editing."),nl(t),{changes:Object.keys(Hi).filter(s=>t[s]!==n.tokens[s]).map(s=>({...n.ranges[s],insert:JSON.stringify(t[s])})).sort((s,r)=>s.from-r.from)}}function WS(n,e="Meadow"){(!ar(n).canInitialize||!Object.hasOwn(or,e))&&Qe("Start with a literal top-level layout without an existing widgetTheme binding.");const i=vi(n),s=i.nodes[0],r=[];function o(c,h,u,f=!1){const d=c.properties.find(m=>m.name===h);if(c.locked||d&&!d.editable||!d&&!f)return;const p=`${h}={widgetTheme.${u}}`;r.push(d?{from:d.from,to:d.to,insert:p}:{from:c.insertAt,to:c.insertAt,insert:` ${p}`})}for(const c of["background","corner","padding"])o(s,c,c,!0);s.structure&&o(s,"spacing","spacing",!0);for(const c of i.nodes)if(c.component==="Text"){const h=c.properties.find(f=>f.name==="font")?.value,u=["headline","largeTitle","title","title2","title3"].includes(h);o(c,"font",u?"titleFont":"bodyFont",!0),o(c,"color",u?"foreground":"muted",!0),o(c,"fontDesign","fontDesign",!0)}else c.component==="Icon"&&o(c,"color","accent",!0);let a=0;for(const c of Ci(Wd.parse(n).topNode))if(!(c.name==="LineComment"||c.name==="BlockComment"))if(c.name==="ExpressionStatement"&&c.firstChild?.name==="String")a=c.to;else break;r.push({from:a,to:a,insert:` +const widgetTheme = ${JSON.stringify(or[e],null,2)}; +`}),r.sort((c,h)=>c.from-h.from);let l=n;for(const c of[...r].reverse())l=l.slice(0,c.from)+c.insert+l.slice(c.to);return(!ar(l).tokens||vi(l).issue)&&Qe("This layout cannot be themed automatically. Your source was preserved."),{changes:r}}function Vd(n){if(!Array.isArray(n)||n.length>4096)return[];const e=new Map,t=new Set;for(const i of n){if(typeof i!="string"||new TextEncoder().encode(i).length>1024||/[\\\u0000-\u001f\u007f-\u009f]/.test(i))continue;const s=i.split("/");if(s.length!==2||s[0]!=="image"||!s[1]||new TextEncoder().encode(s[1]).length>255||s[1]!==s[1].trim()||s[1].includes("..")||!/\.(png|jpe?g|webp)$/i.test(s[1]))continue;const r=i.normalize("NFC").toLowerCase();e.has(r)&&e.get(r)!==i&&t.add(r),e.set(r,i)}return[...e].filter(([i])=>!t.has(i)).map(([,i])=>i).sort().slice(0,256)}const sl=Y.define(),lr=Te.define({create:()=>[],update(n,e){for(const t of e.effects)t.is(sl)&&(n=Vd(t.value));return n}});function rl(n,e){n.state.field(lr,!1)!==void 0&&n.dispatch({effects:sl.of(e)})}const jd=Object.freeze({bloom:Object.freeze({name:"Bloom mark",description:"A small four-petal flower",kind:"icon"}),leaf:Object.freeze({name:"Leaf mark",description:"A tilted leaf and stem",kind:"icon"}),pebble:Object.freeze({name:"Pebble friend",description:"A quiet, round-eared companion",kind:"pet"})}),po=`/* ScriptWidget original geometric assets 1: Bloom mark, Leaf mark, Pebble friend. Source: https://github.com/everettjf/scriptwidget (Editor/editorfe/src/visualAssets.js) SPDX-License-Identifier: MIT @@ -49,8 +56,8 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -`;function DS(n,e){const t=i=>e?`{widgetTheme.${i}}`:JSON.stringify(sr.Meadow[i]);if(n==="bloom")return`<zstack frame="40,40"><ellipse frame="15,36" color=${t("accent")}/><ellipse frame="15,36" rotation="90" color=${t("accent")}/><circle frame="11" color=${t("surface")}/></zstack>`;if(n==="leaf")return`<zstack frame="40,40"><ellipse frame="21,34" rotation="40" color=${t("accent")}/><roundedrect frame="3,28" radius="2" rotation="40" color=${t("foreground")}/></zstack>`;if(n==="pebble")return`<vstack spacing="0"><hstack spacing="20"><roundedrect frame="10,14" radius="5" rotation="-12" color=${t("accent")}/><roundedrect frame="10,14" radius="5" rotation="12" color=${t("accent")}/></hstack><zstack><ellipse frame="64,38" color=${t("accent")}/><hstack spacing="9"><circle frame="4" color=${t("foreground")}/><ellipse frame="9,3" color=${t("surface")}/><circle frame="4" color=${t("foreground")}/></hstack></zstack></vstack>`;throw new Error("Choose an original asset from the catalog.")}function LS(n,e,{id:t,kind:i,path:s},r=[]){if(n.source!==e||n.issue)throw new Error("Layout changed. Select the container again.");const o=n.nodes.find(f=>f.id===t);if(!o?.structure)throw new Error("Select a stack/grid with literal JSX children in Layout or Assets.");let a;if(i==="photo"){if(!Bd(r).includes(s))throw new Error("This image is no longer in the package resource list. Refresh images.");a=`<image name={${JSON.stringify(s.slice(6))}} mode="fill" frame="96,64" corner="12"/>`}else{if(!Object.hasOwn(Id,i))throw new Error("Choose an original asset from the catalog.");a=DS(i,!!rr(e).tokens)}const l=[{from:o.contentTo,to:o.contentTo,insert:a}];let c=o.contentTo;if(i!=="photo"&&!e.includes(uo)){const f=e.startsWith("#!")?e.indexOf(` -`)+1:0;l.push({from:f,to:f,insert:uo}),c+=uo.length}l.sort((f,d)=>f.from-d.from);let h=e;for(const f of[...l].reverse())h=h.slice(0,f.from)+f.insert+h.slice(f.to);if(vi(h).issue)throw new Error("This asset would exceed the supported layout limits. Your source was preserved.");return{changes:l,selectedFrom:c}}const XS=n=>["string","number","number|string","date|number","boolean","enum","color","url","action-id","storage-key"].includes(n.type);function X(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function BS(n,e){const t=X("section","sw-layout"),i=X("div","sw-layout-header"),s=X("div","sw-layout-body");t.setAttribute("aria-label","Visual layout editor");let r=!1,o="layout",a=null,l=null,c="",h=null,u=!1,f=0;const d=String(Math.random()),p=(Q,D)=>P=>{if(u||!t.contains(Q)){P.preventDefault();return}return D(P)},m=(Q,D,P)=>Q.addEventListener(D,p(Q,P)),g=(Q,D,P=!1)=>{const j=X("button","sw-layout-button",Q);return j.type="button",j.disabled=P,m(j,"click",D),j},y=g("Layout",()=>{r=o==="layout"?!r:!0,o="layout",Y(),n.requestMeasure()});y.classList.add("sw-layout-toggle"),y.setAttribute("aria-expanded","false");const b=X("span","sw-layout-hint","Select layers and edit literal JSX"),x=g("Undo",()=>La(n)),C=g("Redo",()=>zs(n)),k=g("Theme",()=>{r=o==="theme"?!r:!0,o="theme",Y(),n.requestMeasure()});k.setAttribute("aria-expanded","false");const S=g("Assets",()=>{r=o==="assets"?!r:!0,o="assets",Y(),n.requestMeasure()});S.setAttribute("aria-expanded","false"),i.append(y,k,S,b,x,C),t.append(i,s),s.hidden=x.hidden=C.hidden=!0;const w=X("p","sw-layout-error");w.setAttribute("role","alert"),w.hidden=!0,t.append(w);function U(){a=vi(n.state.doc.toString());const Q=X("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(Q),Q.append(X("div","sw-layout-title","Widget assets")),Q.append(X("p","sw-layout-notice","Insert editable original JSX or a package image. Originals follow connected theme colors; pet artwork is static. Import photos with the app's existing image tools or Web Studio's Add image.")),a.issue){Q.append(X("p","sw-layout-notice",a.issue));return}const D=a.nodes.filter(I=>I.structure),P=X("select");P.setAttribute("aria-label","Asset destination");for(const I of D){const H=X("option","",`${I.tag} · line ${n.state.doc.lineAt(I.from).number}`);H.value=I.id,P.append(H)}D.some(I=>I.id===l)?P.value=l:l=P.value,m(P,"change",()=>{l=P.value}),Q.append(P);const j=n.state.readOnly||!D.length;D.length||Q.append(X("p","sw-layout-notice","Add a stack/grid with literal JSX children in Code to insert assets."));function ae(I,H){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const ce=LS(a,n.state.doc.toString(),{id:P.value,kind:I,path:H},n.state.field(or));l=P.value,w.hidden=!0,n.dispatch({changes:ce.changes,selection:{anchor:ce.selectedFrom},annotations:ws.of("full"),userEvent:"input.asset",scrollIntoView:!0})}catch(ce){w.textContent=ce.message,w.hidden=!1}}for(const[I,H]of Object.entries(Id)){const ce=X("div","sw-layout-actions");ce.append(g(`Insert ${H.name}`,()=>ae(I),j),X("span","",H.description)),Q.append(ce)}Q.append(X("div","sw-layout-title","Package images"));const J=n.state.field(or),ee=X("select");ee.setAttribute("aria-label","Package image");for(const I of J){const H=X("option","",I);H.value=I,ee.append(H)}ee.disabled=!J.length,Q.append(ee,g("Insert package image",()=>ae("photo",ee.value),j||!J.length)),J.length||Q.append(X("p","sw-layout-notice","No supported images in image/. Add a PNG, JPEG or WebP to the package, then refresh or reopen the editor.")),e.refreshResources&&Q.append(g("Refresh images",async()=>{const I=++f,H=n.state.doc,ce=()=>!u&&I===f&&n.state.doc===H;try{const W=await e.refreshResources();ce()&&(w.hidden=!0,il(n,W))}catch{ce()&&(w.textContent="Images could not be refreshed. Reopen this document and try again.",w.hidden=!1)}})),Q.append(X("p","sw-layout-notice","Bloom mark, Leaf mark and Pebble friend: original ScriptWidget geometry, MIT licensed. Package photos retain their own rights. See the Studio assets documentation."))}function F(Q,D){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const P=n.state.doc.toString();if(P!==D)throw new Error("Source changed. Reopen Theme before editing.");const j=Q(P);w.hidden=!0,j.changes.length&&n.dispatch({changes:j.changes,annotations:ws.of("full"),userEvent:"input.theme"})}catch(P){w.textContent=P.message,w.hidden=!1}}function V(){const Q=n.state.doc.toString(),D=rr(Q),P=n.state.readOnly,j=X("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(j),j.append(X("div","sw-layout-title","Widget theme")),j.append(X("p","sw-layout-notice","Saved as ordinary JavaScript with your widget. Dynamic values stay in Code. Applying a theme changes the connected colors, fonts and spacing.")),D.issue){j.append(X("p","sw-layout-notice",D.issue));return}if(!D.tokens){j.append(g("Connect layout to Meadow theme",()=>F(ee=>FS(ee),Q),P||!D.canInitialize)),D.canInitialize||j.append(X("p","sw-layout-notice","Use a literal top-level $render layout, or define the documented widgetTheme object in Code."));return}const ae=X("div","sw-layout-actions");for(const[ee,I]of Object.entries(sr))ae.append(g(ee,()=>F(H=>ho(D,H,I),Q),P));j.append(ae);for(const[ee,I]of Object.entries(Hi)){const H=X("form","sw-layout-form"),ce=X("label","",ee),W=X(I.values?"select":"input");if(I.values)for(const re of I.values){const Me=X("option","",re);Me.value=re,W.append(Me)}I.type==="number"&&(W.type="number",W.min="0",W.max=String(I.maximum),W.step="any"),W.value=String(D.tokens[ee]),W.setAttribute("aria-label",`Theme ${ee}`),W.disabled=P;const te=g(`Apply ${ee}`,()=>{},P);te.type="submit",H.append(ce,W,te),m(H,"submit",re=>{re.preventDefault();const Me=I.type==="number"?W.value.trim()?Number(W.value):NaN:W.value;F(Oe=>ho(D,Oe,{...D.tokens,[ee]:Me}),Q)}),j.append(H)}const J=X("textarea");J.rows=5,J.setAttribute("aria-label","Reusable theme JSON"),J.value=US(D.tokens),j.append(X("label","","Copy this JSON to reuse a theme, or paste a version 1 theme and import it."),J,g("Import theme JSON",()=>F(ee=>ho(D,ee,Xd(J.value).tokens),Q),P))}function E(Q,D=a?.source){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");if(D!==n.state.doc.toString())throw new Error("Source changed during this operation. Select the layer again.");const P=ES(a,n.state.doc.toString(),Q);if(w.hidden=!0,!P.changes.length)return;n.dispatch({changes:P.changes,selection:{anchor:P.selectedFrom},annotations:ws.of("full"),userEvent:"input.layout",scrollIntoView:!0})}catch(P){w.textContent=P.message,w.hidden=!1}}function M(Q){u||(l=Q.id,c="",n.dispatch({selection:{anchor:Q.from,head:Q.to},scrollIntoView:!0,userEvent:"select.layout"}),Y())}function Y(){if(y.setAttribute("aria-expanded",String(r&&o==="layout")),k.setAttribute("aria-expanded",String(r&&o==="theme")),S.setAttribute("aria-expanded",String(r&&o==="assets")),s.hidden=!r,x.hidden=C.hidden=!r,b.hidden=r,x.disabled=n.state.readOnly||vc(n.state)===0,C.disabled=n.state.readOnly||wc(n.state)===0,!r)return;if(o==="assets"){U();return}if(o==="theme"){V();return}if(a=vi(n.state.doc.toString()),s.replaceChildren(),a.issue){s.append(X("p","sw-layout-notice",a.issue));return}const Q=n.state.selection.main.from,D=a.nodes.filter(W=>W.from<=Q&&Q<W.to).at(-1),P=a.nodes.find(W=>W.id===l&&W.from<=Q&&Q<=W.to)??D??a.nodes[0];l=P.id;const j=X("div","sw-layout-layers");j.setAttribute("role","tree"),j.setAttribute("aria-label","Layout layers");const ae=n.state.readOnly,J=W=>{const te=W.text??W.properties.find(re=>re.name==="text"&&re.editable&&typeof re.value=="string")?.value;return`<${W.tag}>${te?` · ${te.slice(0,32)}`:""}${W.locked?" · locked":""}`};for(const[W,te]of a.nodes.entries()){const re=a.nodes.find(ie=>ie.id===te.parentID),Me=!ae&&!te.locked&&re?.structure,Oe=g(J(te),()=>M(te));Oe.classList.add("sw-layout-layer"),Oe.dataset.layerId=te.id,Oe.style.paddingInlineStart=`${8+te.depth*14}px`,Oe.setAttribute("role","treeitem"),Oe.setAttribute("aria-level",String(te.depth+1)),Oe.setAttribute("aria-selected",String(te.id===P.id)),Oe.tabIndex=te.id===P.id?0:-1,Oe.draggable=!!Me,m(Oe,"keydown",ie=>{let ve;ie.key==="ArrowUp"&&(ve=a.nodes[Math.max(0,W-1)]),ie.key==="ArrowDown"&&(ve=a.nodes[Math.min(a.nodes.length-1,W+1)]),ie.key==="ArrowLeft"&&(ve=re),ie.key==="ArrowRight"&&(ve=a.nodes.find(Ie=>Ie.id===te.children[0])),ie.key==="Home"&&(ve=a.nodes[0]),ie.key==="End"&&(ve=a.nodes.at(-1)),ve&&(ie.preventDefault(),ie.stopPropagation(),M(ve),ee().find(Ie=>Ie.dataset.layerId===ve.id)?.focus())}),m(Oe,"dragstart",ie=>{if(!Me){ie.preventDefault();return}h={id:te.id,source:a.source},ie.dataTransfer.setData("application/x-scriptwidget-layer",d),ie.dataTransfer.effectAllowed="move"}),m(Oe,"dragover",ie=>{h&&re?.structure&&te.id!==h.id&&(ie.preventDefault(),ie.dataTransfer.dropEffect="move")}),m(Oe,"drop",ie=>{if(!h||ie.dataTransfer.getData("application/x-scriptwidget-layer")!==d||!re?.structure)return;ie.preventDefault();const ve=h;h=null,E({type:"move",id:ve.id,parentID:re.id,index:re.children.filter(Ie=>Ie!==ve.id).indexOf(te.id)},ve.source)}),m(Oe,"dragend",()=>{h=null}),j.append(Oe)}function ee(){return[...t.querySelectorAll(".sw-layout-layer")]}const I=X("div","sw-layout-inspector"),H=X("div","sw-layout-title",`<${P.tag}>`);if(I.append(H),(ae||P.locked)&&I.append(X("p","sw-layout-notice",ae?"This document is read only.":P.reason)),!ae&&!P.locked){let Oe=function(){c=re.value;const oe=ha(P)[c],Ae=P.properties.find(tt=>tt.name===c);if(Me.replaceChildren(),te.onsubmit=tt=>tt.preventDefault(),Ae&&!Ae.editable){Me.append(X("span","sw-layout-notice","Dynamic value: edit it in Code. Connected widgetTheme tokens can be changed in Theme."));return}const le=X(oe.values||oe.type==="boolean"?"select":"input");le.setAttribute("aria-label","Layout property value");for(const tt of oe.values??(oe.type==="boolean"?[!0,!1]:[])){const ai=X("option","",String(tt));ai.value=String(tt),le.append(ai)}le.value=Ae?String(Ae.value):oe.values?.[0]??(oe.type==="boolean"?"true":"");const We=g("Apply",()=>{});We.type="submit",Me.append(le,We,g("Remove",()=>E({type:"property",id:P.id,name:c,remove:!0}),!Ae||oe.required)),te.onsubmit=p(te,tt=>{tt.preventDefault();const ai=oe.type==="boolean"?le.value==="true":oe.type==="number"?le.value.trim()?Number(le.value):NaN:le.value;E({type:"property",id:P.id,name:c,value:ai})})};if(P.textEditable){const oe=X("form","sw-layout-form"),Ae=X("label","","Text"),le=X("input");le.value=P.text,le.setAttribute("aria-label","Layer text");const We=g("Apply text",()=>{});We.type="submit",oe.append(Ae,le,We),m(oe,"submit",tt=>{tt.preventDefault(),E({type:"text",id:P.id,value:le.value})}),I.append(oe)}const W=Object.entries(ha(P)).filter(([,oe])=>XS(oe)),te=X("form","sw-layout-form"),re=X("select");re.setAttribute("aria-label","Layout property");for(const[oe]of W){const Ae=X("option","",oe);Ae.value=oe,re.append(Ae)}W.some(([oe])=>oe===c)||(c=P.structure?"alignment":"color"),re.value=c,re.value||(re.selectedIndex=0,c=re.value);const Me=X("div","sw-layout-property");te.append(re,Me),m(re,"change",Oe),Oe(),I.append(te);const ie=a.nodes.find(oe=>oe.id===P.parentID),ve=ie?.children.indexOf(P.id)??-1,Ie=X("div","sw-layout-actions");if(Ie.append(g("Move up",()=>E({type:"move",id:P.id,parentID:ie.id,index:ve-1}),!ie?.structure||ve<=0),g("Move down",()=>E({type:"move",id:P.id,parentID:ie.id,index:ve+1}),!ie?.structure||ve>=ie.children.length-1),g("Delete layer",()=>E({type:"remove",id:P.id}),!ie?.structure)),I.append(Ie),ie?.structure){const oe=a.nodes.filter(le=>le.structure&&!(le.from>=P.from&&le.to<=P.to)),Ae=X("select");Ae.setAttribute("aria-label","Move layer into container");for(const le of oe){const We=X("option","",`${le.tag} · line ${n.state.doc.lineAt(le.from).number}`);We.value=le.id,Ae.append(We)}I.append(Ae,g("Move inside",()=>{const le=a.nodes.find(We=>We.id===Ae.value);E({type:"move",id:P.id,parentID:le.id,index:le.children.filter(We=>We!==P.id).length})},!oe.length))}if(P.structure){const oe=X("div","sw-layout-actions");for(const[Ae,le]of[["text","Add text"],["stack","Add stack"],["spacer","Add spacer"],["icon","Add icon"]])oe.append(g(le,()=>E({type:"add",id:P.id,kind:Ae})));I.append(oe)}}const ce=P.properties.filter(W=>!W.editable).map(W=>W.name);ce.length&&I.append(X("p","sw-layout-notice",`Preserved in Code: ${ce.join(", ")}`)),!P.structure&&P.children.length&&I.append(X("p","sw-layout-notice","This child structure stays in Code. Reordering is available on literal stack/grid children.")),s.append(j,I)}return{dom:t,top:!0,update(Q){if(!r)return;const D=n.state.selection.main.from,P=a?.nodes.filter(ae=>ae.from<=D&&D<ae.to).at(-1)?.id,j=Q.transactions.some(ae=>ae.effects.some(J=>J.is(tl)));(Q.docChanged||j||Q.startState.readOnly!==n.state.readOnly||Q.selectionSet&&P!==l)&&(Q.docChanged&&o!=="assets"&&(l=null),Y()),x.disabled=n.state.readOnly||vc(n.state)===0,C.disabled=n.state.readOnly||wc(n.state)===0},destroy(){u=!0}}}const IS=$.baseTheme({".sw-layout":{fontFamily:"system-ui, sans-serif",fontSize:"12px",backgroundColor:"#f6f7fa",color:"#272a34",borderBottom:"1px solid #dce0e9"},"&dark .sw-layout":{backgroundColor:"#252830",color:"#eceef5",borderColor:"#414552"},".sw-layout-header":{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",padding:"6px 10px"},".sw-layout-toggle":{fontWeight:"600"},".sw-layout-hint":{opacity:"0.65",fontSize:"11px"},".sw-layout-button":{fontFamily:"inherit",fontSize:"11px",color:"inherit",backgroundColor:"transparent",border:"1px solid #a0a5b655",borderRadius:"6px",padding:"4px 8px",cursor:"pointer",whiteSpace:"nowrap"},".sw-layout-button:disabled":{opacity:"0.4",cursor:"default"},".sw-layout-body":{display:"grid",gridTemplateColumns:"minmax(120px, 1fr) minmax(180px, 1.6fr)",maxHeight:"280px",overflow:"auto",borderTop:"1px solid #a0a5b633"},".sw-layout-body[hidden]":{display:"none"},".sw-layout-layers":{padding:"6px 2px",overflow:"auto",borderRight:"1px solid #a0a5b633"},".sw-layout-layer":{display:"block",border:0,borderRadius:"4px",width:"100%",textAlign:"left",overflow:"hidden",textOverflow:"ellipsis",margin:"1px 0",paddingBlock:"6px"},'.sw-layout-layer[aria-selected="true"]':{backgroundColor:"#4085f52b",color:"inherit"},".sw-layout-inspector":{padding:"8px 10px",display:"flex",alignItems:"start",flexDirection:"column",gap:"8px",minWidth:0},".sw-theme-inspector":{gridColumn:"1 / -1"},".sw-theme-inspector textarea":{boxSizing:"border-box",width:"100%",fontFamily:"monospace",backgroundColor:"transparent",color:"inherit",border:"1px solid #a0a5b666",borderRadius:"5px"},".sw-layout-title":{fontWeight:"600"},".sw-layout-form":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"5px",width:"100%"},".sw-layout-property,.sw-layout-actions":{display:"flex",flexWrap:"wrap",gap:"5px",alignItems:"center"},".sw-layout input,.sw-layout select":{fontFamily:"inherit",fontSize:"12px",minWidth:0,maxWidth:"100%",padding:"4px 6px",border:"1px solid #a0a5b666",borderRadius:"5px",backgroundColor:"transparent",color:"inherit"},".sw-layout-notice":{margin:"8px",lineHeight:"1.5",fontSize:"11px",opacity:"0.7"},".sw-layout-body > .sw-layout-notice":{gridColumn:"1 / -1"},".sw-layout-error":{margin:"0 10px 6px",color:"#b32636",fontSize:"12px"},"&dark .sw-layout-error":{color:"#ff99a4"},".sw-layout button:focus-visible,.sw-layout input:focus-visible,.sw-layout select:focus-visible":{outline:"2px solid #4085f5",outlineOffset:"1px"},"@media (max-width: 480px)":{".sw-layout-body":{gridTemplateColumns:"minmax(90px, 1fr) minmax(150px, 1.6fr)"},".sw-layout-hint":{display:"none"}}});function WS(n={}){return[IS,or,Vi.of(e=>BS(e,n))]}const Wd="scriptwidget.studio.document-state.v1.";function qd(n,e,t){if(!n||!e)return!1;try{return n.setItem(`${Wd}${e}`,JSON.stringify({anchor:Number(t.anchor)||0,head:Number(t.head)||0,scrollTop:Number(t.scrollTop)||0})),!0}catch{return!1}}function qS(n,e,t){if(!n||!e)return null;try{const i=JSON.parse(n.getItem(`${Wd}${e}`));if(!i||typeof i!="object")return null;const s=r=>Math.max(0,Math.min(Number(r)||0,t));return{anchor:s(i.anchor),head:s(i.head),scrollTop:Math.max(0,Number(i.scrollTop)||0)}}catch{return null}}const zS="scriptwidget.web-studio.draft.v1:";function nl(n){return`${zS}${n}`}function VS(n,e){if(!e)return null;try{const t=JSON.parse(n.getItem(nl(e))||"null");return t&&typeof t.content=="string"&&typeof t.baseRevision=="string"?t:null}catch{return null}}function hh(n,e,t,i,s=Date.now()){if(!e||typeof i!="string")return null;const r={documentID:e,content:t,baseRevision:i,updatedAt:s};return n.setItem(nl(e),JSON.stringify(r)),r}function fo(n,e){e&&n.removeItem(nl(e))}function jS(n,e,t,i){const s=VS(n,e);return!s||s.content===t?null:{...s,serverContent:t,serverRevision:i,isStale:s.baseRevision!==i}}function YS(){return{connection:"connecting",save:"idle",preview:"idle",conflict:null}}function NS(n,e){switch(e.type){case"CONNECTED":return{...n,connection:"connected"};case"OFFLINE":return{...n,connection:"offline",save:n.save==="saving"?"draft":n.save};case"DISCONNECTED":return{...n,connection:"disconnected"};case"EDITED":return{...n,save:"draft",conflict:null};case"SAVING":return{...n,save:"saving"};case"SAVED":return{...n,save:"saved",preview:e.preview||"requested",conflict:null};case"SAVE_FAILED":return{...n,save:"error"};case"CONFLICT":return{...n,save:"conflict",conflict:e.conflict};default:return n}}class HS{constructor(e){this.send=e,this.epoch=0,this.context=null,this.inFlight=null,this.needsFlush=!1}open({documentID:e,packageID:t,path:i,revision:s,content:r}){return this.epoch+=1,this.context={documentID:e,packageID:t,path:i,revision:s,content:r,generation:0,savedGeneration:0},this.needsFlush=!1,this.snapshot()}edit(e){return this.context?(this.context.content=e,this.context.generation+=1,this.snapshot()):null}rebase(e){return this.context&&(this.context.revision=e),this.snapshot()}get isDirty(){return!!(this.context&&this.context.generation!==this.context.savedGeneration)}snapshot(){return this.context?{...this.context,dirty:this.isDirty}:null}async flush(){if(!this.context||!this.isDirty)return{skipped:!0,snapshot:this.snapshot()};if(this.inFlight)return this.needsFlush=!0,this.inFlight.then(()=>this.isDirty?this.flush():{skipped:!0,snapshot:this.snapshot()});const e=this.epoch,t={...this.context};this.needsFlush=!1,this.inFlight=this.send({documentID:t.documentID,packageID:t.packageID,path:t.path,content:t.content,baseRevision:t.revision}).then(s=>this.epoch!==e||this.context?.documentID!==t.documentID?{ignored:!0,result:s,snapshot:this.snapshot()}:(this.context.revision=s.revision,this.context.savedGeneration=t.generation,{result:s,snapshot:this.snapshot()})).finally(()=>{this.inFlight=null});const i=await this.inFlight;return this.needsFlush&&this.isDirty?this.flush():i}}function uh(n){return["draft","saving","error","conflict"].includes(n)}class GS extends Error{constructor(e,t,i={}){super(e),this.name="StudioAPIError",this.status=t,this.body=i}}class _S{constructor({fetchImpl:e=globalThis.fetch,token:t=()=>"",onUnauthorized:i=()=>{}}={}){if(typeof e!="function")throw new TypeError("A fetch implementation is required");this.fetchImpl=e,this.token=t,this.onUnauthorized=i}async request(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t)),s=await i.json().catch(()=>({}));return this.validate(i,e,s),s}async requestBlob(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t));if(!i.ok){const s=await i.json().catch(()=>({}));this.validate(i,e,s)}return i.blob()}authorizedOptions(e){return{...e,headers:{"Content-Type":"application/json","X-Studio-Token":this.token(),...e.headers||{}}}}validate(e,t,i){if(!e.ok){const s=new GS(i.message||`Request failed (${e.status})`,e.status,i);throw e.status===401&&t!=="/api/v1/pair"&&this.onUnauthorized(s),s}}}const sl=/^https?:$/.test(window.location.protocol)&&!window.ScriptWidgetAndroid,JS=document.querySelector(sl?"#editor":"#native-editor"),rl=new Gi,ar=new Gi;let Wt=null,me=null,Et=null,at=0,wi=0,ua=!1,Mn=null,fh=null;const dh=document.querySelector("#save-status");let zd=null;function En(n,e="idle"){dh.textContent=n,dh.dataset.state=e}function e1(){window.clearTimeout(fh),fh=window.setTimeout(()=>{const n=q.state.selection.main;qd(window.localStorage,me,{anchor:n.anchor,head:n.head,scrollTop:q.scrollDOM.scrollTop})},180)}function Vd(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function ol(){window.clearTimeout(Mn),En("Saving…","saving"),Mn=window.setTimeout(()=>{const n=q.state.doc.toString(),e=at,t=me,i=Et,s=wi;nn(Wt,Ue.documentSave,{content:n,version:e},t,(r={})=>{sl||t!==me||i!==Et||s!==wi||e!==at||En(r.result==="ok"||r.result==="unavailable"?"Saved":"Save failed",r.result==="failed"?"error":"saved")},i)},700)}function t1(n){if((n.selectionSet||n.viewportChanged||n.docChanged)&&e1(),!n.docChanged||ua)return;at+=1,zd?.documentChanged();const e=[];n.changes.iterChanges((t,i,s,r,o)=>{e.push({from:t,to:i,insert:o.toString(),newFrom:s,newTo:r})}),nn(Wt,Ue.documentChanged,{changes:e,version:at},me,void 0,Et),ol()}const jd=[nO(),oO(),xg(),w0(),WS({refreshResources:()=>new Promise((n,e)=>{const t=me,i=wi,s=Et,r=window.setTimeout(()=>e(new Error("Resource refresh timed out")),5e3);nn(Wt,Ue.documentResources,{},t,(o={})=>{window.clearTimeout(r),t!==me||i!==wi||o.result!=="ok"||o.documentID!==t||!Array.isArray(o.resources)?e(new Error("Document resources are unavailable")):n(o.resources)},s)})}),HO(),hg(),gg(),_.allowMultipleSelections.of(!0),UO(),c0(),uA(),xA({override:[kS],activateOnTyping:!0}),Mg(),Fg(),Cg(),Qb(),fS(),iS(Ed,{delay:350}),Eu(QS),yb({jsx:!0}),mr.of([Py,...mA,...Qy,...jb,...Z0,...VO,...nd]),rl.of(_.readOnly.of(!1)),ar.of(Ud(Vd())),$.updateListener.of(t1),$.contentAttributes.of({autocapitalize:"off",autocomplete:"off",spellcheck:"false"})],q=new $({state:_.create({doc:"",extensions:jd}),parent:JS});function _t(n,e=me,t=0,i=!1){window.clearTimeout(Mn),wi+=1;const s=q.state.selection.main;qd(window.localStorage,me,{anchor:s.anchor,head:s.head,scrollTop:q.scrollDOM.scrollTop}),ua=!0;const r=e!==me;me=e,at=t;const o=qS(window.localStorage,me,(n??"").length),a=o?{anchor:o.anchor,head:o.head}:{anchor:0};if(r){const l=ar.get(q.state),c=q.state.readOnly;let h=_.create({doc:n??"",extensions:jd,selection:a});h=h.update({effects:[ar.reconfigure(l),rl.reconfigure(_.readOnly.of(c))]}).state,q.setState(h)}else q.dispatch({changes:{from:0,to:q.state.doc.length,insert:n??""},selection:a,scrollIntoView:!0});o&&window.requestAnimationFrame(()=>{q.scrollDOM.scrollTop=o.scrollTop}),ua=!1,i&&nn(Wt,Ue.documentChanged,{content:q.state.doc.toString(),version:at},me,void 0,Et),En("Saved","saved")}function ph(n){if(q.state.readOnly)return!1;const e=q.state.selection.main;return q.dispatch({changes:{from:e.from,to:e.to,insert:n},selection:{anchor:e.from+n.length},userEvent:"input"}),q.focus(),!0}async function lr(){if(q.state.readOnly)return!1;const n=q.state.doc.toString(),e=wi,t=at,i=()=>!q.state.readOnly&&e===wi&&t===at&&n===q.state.doc.toString();try{const[{format:s},{default:r},{default:o}]=await Promise.all([Cr(()=>import("./standalone-Cayz_KD-.js"),[],import.meta.url),Cr(()=>import("./babel-BktJt1uC.js"),[],import.meta.url),Cr(()=>import("./estree-DFfjoHvx.js"),[],import.meta.url)]),a=await s(n,{parser:"babel",plugins:[r,o],semi:!0,singleQuote:!0,trailingComma:"es5"});return i()?(_t(a,me,at+1,!0),ol(),!0):!1}catch(s){return i()&&nn(Wt,"diagnostics.publish",{message:String(s),severity:"error"},me,void 0,Et),!1}}function Xi(n){q.dispatch({effects:rl.reconfigure(_.readOnly.of(!!n))})}function cr(n){const e=n==="dark"||n==="light"?n:Vd();document.documentElement.dataset.theme=e,q.dispatch({effects:ar.reconfigure(Ud(e))})}function i1(n=[]){const e=n.map(t=>({from:Math.max(0,Math.min(t.from??0,q.state.doc.length)),to:Math.max(0,Math.min(t.to??t.from??0,q.state.doc.length)),severity:t.severity??"error",message:t.message??"Unknown error"}));q.dispatch(vd(q.state,e))}function rt(n,e){Wt.registerHandler(n,async(t={},i=()=>{})=>{try{if(Et!==null&&n!==Ue.documentOpen&&n!==Ue.editorSetTheme&&(t.documentID!==me||t.sessionID!==Et))throw new Error("The editor session changed.");i({result:"ok",...await e(t)})}catch(s){i({result:"failed",message:String(s)})}})}pS(n=>{Wt=n,rt(Ue.documentOpen,({payload:e={},documentID:t,sessionID:i=null})=>(Et=i,_t(e.content,t,e.version??0),il(q,e.resources??[]),Xi(e.readOnly),e.dirty&&(En("Restored unsaved edits","editing"),e.readOnly||ol()),{protocolVersion:Zd})),rt(Ue.documentReplace,({payload:e={},documentID:t})=>{if(q.state.readOnly||e.expectedContent!==void 0&&e.expectedContent!==q.state.doc.toString())throw new Error("The file changed or is read only.");return _t(e.content,t,e.version??at,!0),{}}),rt(Ue.documentSetReadOnly,({payload:e={}})=>(Xi(e.readOnly),{readOnly:!!e.readOnly})),rt(Ue.editorInsert,({payload:e={}})=>({inserted:ph(e.content??"")})),rt(Ue.editorFormat,async()=>({formatted:await lr()})),rt(Ue.editorSetTheme,({payload:e={}})=>(cr(e.theme),{})),rt(Ue.editorGetState,()=>({content:q.state.doc.toString(),version:at,documentID:me,sessionID:Et,selection:{from:q.state.selection.main.from,to:q.state.selection.main.to}})),rt(Ue.diagnosticsPublish,({payload:e={}})=>(i1(e.items),{})),rt("editor_setValue",({value:e})=>(_t(e),{})),rt("editor_insertValue",({value:e})=>({inserted:ph(e??"")})),rt("editor_getValue",()=>({value:q.state.doc.toString()})),rt("editor_setReadonly",({readonly:e})=>(Xi(e),{readonly:!!e})),rt("editor_formatCode",async()=>({formatted:await lr()})),mS(Wt)});sl&&(document.querySelector("#native-editor").hidden=!0,document.querySelector("#web-studio").hidden=!1,n1());async function n1(){const n=document.querySelector("#pair-dialog"),e=document.querySelector("#pair-form"),t=document.querySelector("#pair-error"),i=document.querySelector("#package-select"),s=document.querySelector("#file-select"),r=document.querySelector("#connection-status"),o=document.querySelector("#disconnect-button"),a=document.querySelector("#studio-grid"),l=document.querySelector(".editor-column"),c=document.querySelector("#recovery-banner"),h=document.querySelector("#conflict-banner"),u=document.querySelector("#command-dialog"),f=document.querySelector("#command-search"),d=document.querySelector("#command-list"),p=document.querySelector("#compare-dialog");let m=window.sessionStorage.getItem("scriptwidget.web-studio.token")||"",g=[],y=null,b=null,x=null,C=0,k=null,S="",w="",U=null,F=YS(),V="",E="",M=null;function Y(v="Session ended. Enter the new code shown on your device."){m="",window.sessionStorage.removeItem("scriptwidget.web-studio.token"),o.hidden=!0,Q({type:"DISCONNECTED"}),r.textContent=v,Xi(!0),n.open||n.showModal()}function Q(v){F=NS(F,v);const Z={connecting:"Connecting",connected:"Connected",offline:"Offline",disconnected:"Disconnected"},L={idle:"Ready",draft:"Draft saved locally",saving:"Saving…",saved:"Saved",error:"Save failed",conflict:"Conflict"};r.dataset.state=F.connection,document.querySelector("#status-connection").textContent=Z[F.connection]||F.connection,En(L[F.save]||F.save,F.save),document.querySelector("#dirty-indicator").hidden=!["draft","saving","error","conflict"].includes(F.save),document.querySelector("#status-preview").textContent=F.preview==="requested"?"Preview requested":"Preview idle",document.querySelector("#preview-detail").textContent=F.preview==="requested"?"Requested on device":"Not requested"}const D=new _S({token:()=>m,onUnauthorized:()=>Y()}),P=(v,Z)=>D.request(v,Z);M=new HS(({packageID:v,path:Z,content:L,baseRevision:ne})=>P("/api/v1/document",{method:"PUT",body:JSON.stringify({package:v,path:Z,content:L,baseRevision:ne})}));async function j(v){m=(await P("/api/v1/pair",{method:"POST",body:JSON.stringify({code:v})})).token,window.sessionStorage.setItem("scriptwidget.web-studio.token",m),o.hidden=!1,Q({type:"CONNECTED"}),ae()}function ae(){window.clearInterval(y),y=window.setInterval(async()=>{if(m)try{const v=await P("/api/v1/session");if(!navigator.onLine)return;W(v),Q({type:"CONNECTED"})}catch(v){v.status!==401&&(r.textContent=`Interrupted · ${v.message}`,Q({type:"OFFLINE"}))}},5e3)}async function J(){if(g=(await P("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(Z=>new Option(Z.name,Z.id))),!g.length){r.textContent="No editable widgets",Xi(!0);return}await ee()}async function ee(){const v=g.find(ne=>ne.id===i.value),Z=v?.files||[];s.replaceChildren(...Z.map(ne=>new Option(ne,ne)));const L=Z.includes(v?.entry)?v.entry:Z[0];L&&(s.value=L),await H()}async function I(v=""){g=(await P("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(ge=>new Option(ge.name,ge.id))),V&&(i.value=V);const L=g.find(ge=>ge.id===i.value),ne=L?.files||[];s.replaceChildren(...ne.map(ge=>new Option(ge,ge))),s.value=ne.includes(v)?v:ne.includes(E)?E:L?.entry||ne[0]}async function H(){if(!i.value||!s.value)return;const v=new URLSearchParams({package:i.value,path:s.value}),Z=await P(`/api/v1/document?${v}`),L=`${i.value}/${s.value}`;V=i.value,E=s.value,S=Z.revision,w=Z.content,U=null,h.hidden=!0,_t(Z.content,L,0),il(q,g.find(ge=>ge.id===V)?.files??[]),M.open({documentID:L,packageID:V,path:E,revision:Z.revision,content:Z.content}),Xi(!!Z.readOnly),ce(Z);const ne=jS(window.localStorage,L,Z.content,Z.revision);c.hidden=!ne,c._draft=ne,document.querySelector("#recovery-message").textContent=ne?.isStale?"The device version also changed. Review before saving.":"Restore it or keep the device version.",r.textContent="Connected",Q({type:"CONNECTED"}),o.hidden=!1,Oe(),ae(),Me()}function ce(v){document.querySelector("#breadcrumb-package").textContent=v.packageName||i.value,document.querySelector("#breadcrumb-file").textContent=s.value,document.querySelector("#editor-tab-name").textContent=s.value,document.querySelector("#revision-detail").textContent=S?S.slice(0,8):"—",document.querySelector("#access-detail").textContent=v.readOnly?"Read only":"Editable"}function W(v){v.device&&(document.querySelector("#device-name").textContent=v.device.name||v.device.model,document.querySelector("#device-system").textContent=`${v.device.model} · ${v.device.system}`),v.preview?.package&&(document.querySelector("#preview-target").textContent=v.preview.package),v.preview?.snapshotSequence&&te()}async function te(){try{const v=await D.requestBlob("/api/v1/preview"),Z=URL.createObjectURL(v),L=document.querySelector("#device-preview"),ne=k;k=Z,L.onload=()=>{ne&&URL.revokeObjectURL(ne)},L.src=Z,L.hidden=!1,document.querySelector("#preview-detail").textContent="Rendered on device"}catch{}}function re(v){const Z=document.querySelector("#console-list"),L=document.createElement("li");for(L.className=v.level||"info",L.textContent=v.message||"",Z.append(L);Z.children.length>200;)Z.firstChild.remove();Z.scrollTop=Z.scrollHeight}function Me(){window.clearTimeout(x);const v=async()=>{if(m)try{const Z=await P(`/api/v1/events?after=${C}`);C=Z.nextSequence??C;for(const L of Z.events||[])L.type==="console"&&re(L.payload||{}),L.type==="preview.snapshot"&&te(),L.type==="preview.requested"&&(document.querySelector("#status-preview").textContent="Preview requested",document.querySelector("#preview-detail").textContent="Requested on device"),L.type==="files.changed"&&L.payload?.package===V&&I(E).catch(Ie);Q({type:"CONNECTED"})}catch(Z){Z.status!==401&&Q({type:"OFFLINE"})}finally{m&&(x=window.setTimeout(v,1e3))}};v()}function Oe(){const v=Ed(q);document.querySelector("#problems-list").replaceChildren(...v.map(L=>{const ne=q.state.doc.lineAt(L.from),ge=document.createElement("li");ge.className=`problem-item ${L.severity}`;const it=document.createElement("button");return it.type="button",it.innerHTML=`<span class="problem-severity">${L.severity==="error"?"●":"▲"}</span><span></span><span class="problem-location">Ln ${ne.number}</span>`,it.children[1].textContent=L.message,it.addEventListener("click",()=>{q.dispatch({selection:{anchor:L.from},scrollIntoView:!0}),q.focus()}),ge.append(it),ge})),document.querySelector("#problems-count").textContent=String(v.length),document.querySelector("#status-problem-count").textContent=String(v.length),document.querySelector("#problems-summary").textContent=v.length?`${v.filter(L=>L.severity==="error").length} errors, ${v.filter(L=>L.severity!=="error").length} warnings`:"No problems detected"}async function ie(v,Z,L=null){M.snapshot()?.content!==v&&M.edit(v),L&&M.rebase(L),Q({type:"SAVING"});try{const ne=await M.flush();if(ne.ignored){Z({result:"ok",ignored:!0});return}if(ne.skipped){Q({type:"SAVED"}),Z({result:"ok",skipped:!0});return}const ge=ne.result||{},it=M.snapshot();S=it?.revision||S,w=it?.content||v,fo(window.localStorage,me),U=null,h.hidden=!0,document.querySelector("#revision-detail").textContent=S?.slice(0,8)||"—",Q({type:"SAVED",preview:ge.preview?.state}),Z({result:"ok",...ge})}catch(ne){ne.status===409?(U=ne.body,h.hidden=!1,Q({type:"CONFLICT",conflict:U})):Q({type:"SAVE_FAILED"}),Z({result:"failed",message:ne.message})}}Wt={registerHandler(){},callHandler(v,Z,L=()=>{}){if(v===Ue.documentSave)ie(Z.payload.content,L);else if(v===Ue.documentResources){const ne=me,ge=V;P("/api/v1/packages").then(it=>{if(ne!==me||Z.documentID!==me||ge!==V){L({result:"failed"});return}L({result:"ok",documentID:ne,resources:(it.packages??[]).find(zn=>zn.id===ge)?.files??[]})}).catch(()=>L({result:"failed"}))}else L({result:"ok"})}},zd={documentChanged(){const v=q.state.doc.toString();M.edit(v),hh(window.localStorage,me,v,M.snapshot()?.revision||S),Q({type:"EDITED"}),window.clearTimeout(b),b=window.setTimeout(Oe,380)}};async function ve(v,Z){if(!uh(F.save)){await v();return}try{if(window.clearTimeout(Mn),await ie(q.state.doc.toString(),()=>{}),!M.isDirty&&F.save!=="conflict"){await v();return}}catch{}window.confirm("This document has changes that are not saved on the device. A browser draft is available. Switch anyway?")?await v():Z()}i.addEventListener("change",()=>{const v=i.value;i.value=V,ve(async()=>{i.value=v,await ee()},()=>{i.value=V}).catch(Ie)}),s.addEventListener("change",()=>{const v=s.value;s.value=E,ve(async()=>{s.value=v,await H()},()=>{s.value=E}).catch(Ie)});function Ie(v){r.textContent=v.message||String(v),Q({type:"SAVE_FAILED"})}e.addEventListener("submit",async v=>{v.preventDefault(),t.textContent="";try{await j(document.querySelector("#pair-code").value),n.close(),await J()}catch(Z){t.textContent=Z.message}}),o.addEventListener("click",async()=>{try{await P("/api/v1/session",{method:"DELETE"})}catch{}Y("Disconnected. Start a new session with the code on your device.")}),document.querySelector("#new-file").addEventListener("click",async()=>{const v=window.prompt("New package-relative text file","source/helper.js")?.trim();if(v)try{await P("/api/v1/document",{method:"POST",body:JSON.stringify({package:V,path:v})}),await I(v),await H()}catch(Z){Ie(Z)}}),document.querySelector("#delete-file").addEventListener("click",async()=>{const v=g.find(Z=>Z.id===V);if(!E||E===v?.entry){window.alert("The widget entry file cannot be deleted.");return}if(window.confirm(`Delete ${E}? This cannot be undone.`))try{const Z=new URLSearchParams({package:V,path:E});await P(`/api/v1/document?${Z}`,{method:"DELETE"}),E="",await I(),await H()}catch(Z){Ie(Z)}}),document.querySelector("#clear-console").addEventListener("click",()=>document.querySelector("#console-list").replaceChildren()),document.querySelector("#restore-draft").addEventListener("click",()=>{const v=c._draft;v&&(_t(v.content,v.documentID,at+1),c.hidden=!0,hh(window.localStorage,me,v.content,S),Q({type:"EDITED"}),Oe())}),document.querySelector("#discard-draft").addEventListener("click",()=>{fo(window.localStorage,me),c.hidden=!0}),document.querySelector("#reload-server").addEventListener("click",()=>{U&&(fo(window.localStorage,me),S=U.currentRevision,w=U.currentContent,_t(w,me,at+1),M.open({documentID:me,packageID:V,path:E,revision:S,content:w}),U=null,h.hidden=!0,Q({type:"SAVED"}),Oe())}),document.querySelector("#keep-local").addEventListener("click",()=>{U&&ie(q.state.doc.toString(),()=>{},U.currentRevision)}),document.querySelector("#compare-conflict").addEventListener("click",()=>{document.querySelector("#compare-local").textContent=q.state.doc.toString(),document.querySelector("#compare-server").textContent=U?.currentContent||w,p.showModal()}),p.querySelector("button").addEventListener("click",()=>p.close());function oe(){const v=l.classList.toggle("problems-collapsed");document.querySelector("#problems-toggle").setAttribute("aria-expanded",String(!v))}function Ae(v){a.classList.toggle(`show-${v}`)}document.querySelector("#problems-toggle").addEventListener("click",oe),document.querySelector("#status-problems").addEventListener("click",()=>{l.classList.remove("problems-collapsed")}),document.querySelector("#explorer-button").addEventListener("click",()=>Ae("explorer")),document.querySelector("#inspector-button").addEventListener("click",()=>Ae("inspector")),document.querySelectorAll("[data-close-panel]").forEach(v=>v.addEventListener("click",()=>a.classList.remove(`show-${v.dataset.closePanel}`)));const le=[{name:"Save Document",keys:"⌘S",run:()=>{window.clearTimeout(Mn),ie(q.state.doc.toString(),()=>{})}},{name:"Format Document",keys:"⇧⌥F",run:lr},{name:"Toggle Problems",keys:"⌘J",run:oe},{name:"Toggle Explorer",keys:"⌘⇧E",run:()=>Ae("explorer")},{name:"Toggle Inspector",keys:"",run:()=>Ae("inspector")},{name:"Use Light Theme",keys:"",run:()=>cr("light")},{name:"Use Dark Theme",keys:"",run:()=>cr("dark")}];function We(v=""){const Z=le.filter(L=>L.name.toLowerCase().includes(v.toLowerCase()));d.replaceChildren(...Z.map(L=>{const ne=document.createElement("li"),ge=document.createElement("button");ge.type="button",ge.className="command";const it=document.createElement("span");it.textContent=L.name;const zn=document.createElement("kbd");return zn.textContent=L.keys,ge.append(it,zn),ge.addEventListener("click",()=>{u.close(),L.run()}),ne.append(ge),ne}))}function tt(){We(),u.showModal(),f.value="",f.focus()}document.querySelector("#command-button").addEventListener("click",tt),f.addEventListener("input",()=>We(f.value)),document.addEventListener("keydown",v=>{const Z=v.metaKey||v.ctrlKey;Z&&v.shiftKey&&v.key.toLowerCase()==="p"?(v.preventDefault(),tt()):Z&&v.key.toLowerCase()==="s"?(v.preventDefault(),le[0].run()):Z&&v.key.toLowerCase()==="j"?(v.preventDefault(),oe()):Z&&v.shiftKey&&v.key.toLowerCase()==="e"?(v.preventDefault(),Ae("explorer")):v.shiftKey&&v.altKey&&v.key.toLowerCase()==="f"&&(v.preventDefault(),lr())}),q.dom.addEventListener("keyup",ai),q.dom.addEventListener("mouseup",ai);function ai(){const v=q.state.selection.main.head,Z=q.state.doc.lineAt(v);document.querySelector("#cursor-position").textContent=`Ln ${Z.number}, Col ${v-Z.from+1}`}window.addEventListener("offline",()=>{r.textContent="Computer is offline",Q({type:"OFFLINE"})}),window.addEventListener("online",()=>{m&&P("/api/v1/session").then(v=>(W(v),Q({type:"CONNECTED"}),J())).catch(Ie)}),window.addEventListener("beforeunload",v=>{uh(F.save)&&(v.preventDefault(),v.returnValue="")});try{await J()}catch{Y("Pair with the code shown on your device.")}}window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener("change",()=>cr("system"));window.webkit||_t(`// ScriptWidget Studio +`;function qS(n,e){const t=i=>e?`{widgetTheme.${i}}`:JSON.stringify(or.Meadow[i]);if(n==="bloom")return`<zstack frame="40,40"><ellipse frame="15,36" color=${t("accent")}/><ellipse frame="15,36" rotation="90" color=${t("accent")}/><circle frame="11" color=${t("surface")}/></zstack>`;if(n==="leaf")return`<zstack frame="40,40"><ellipse frame="21,34" rotation="40" color=${t("accent")}/><roundedrect frame="3,28" radius="2" rotation="40" color=${t("foreground")}/></zstack>`;if(n==="pebble")return`<vstack spacing="0"><hstack spacing="20"><roundedrect frame="10,14" radius="5" rotation="-12" color=${t("accent")}/><roundedrect frame="10,14" radius="5" rotation="12" color=${t("accent")}/></hstack><zstack><ellipse frame="64,38" color=${t("accent")}/><hstack spacing="9"><circle frame="4" color=${t("foreground")}/><ellipse frame="9,3" color=${t("surface")}/><circle frame="4" color=${t("foreground")}/></hstack></zstack></vstack>`;throw new Error("Choose an original asset from the catalog.")}function zS(n,e,{id:t,kind:i,path:s},r=[]){if(n.source!==e||n.issue)throw new Error("Layout changed. Select the container again.");const o=n.nodes.find(f=>f.id===t);if(!o?.structure)throw new Error("Select a stack/grid with literal JSX children in Layout or Assets.");let a;if(i==="photo"){if(!Vd(r).includes(s))throw new Error("This image is no longer in the package resource list. Refresh images.");a=`<image name={${JSON.stringify(s.slice(6))}} mode="fill" frame="96,64" corner="12"/>`}else{if(!Object.hasOwn(jd,i))throw new Error("Choose an original asset from the catalog.");a=qS(i,!!ar(e).tokens)}const l=[{from:o.contentTo,to:o.contentTo,insert:a}];let c=o.contentTo;if(i!=="photo"&&!e.includes(po)){const f=e.startsWith("#!")?e.indexOf(` +`)+1:0;l.push({from:f,to:f,insert:po}),c+=po.length}l.sort((f,d)=>f.from-d.from);let h=e;for(const f of[...l].reverse())h=h.slice(0,f.from)+f.insert+h.slice(f.to);if(vi(h).issue)throw new Error("This asset would exceed the supported layout limits. Your source was preserved.");return{changes:l,selectedFrom:c}}const VS=n=>["string","number","number|string","date|number","boolean","enum","color","url","action-id","storage-key"].includes(n.type);function B(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function jS(n,e){const t=B("section","sw-layout"),i=B("div","sw-layout-header"),s=B("div","sw-layout-body");t.setAttribute("aria-label","Visual layout editor");let r=!1,o="layout",a=null,l=null,c="",h=null,u=!1,f=0;const d=String(Math.random()),p=(v,M)=>k=>{if(u||!t.contains(v)){k.preventDefault();return}return M(k)},m=(v,M,k)=>v.addEventListener(M,p(v,k)),g=(v,M,k=!1)=>{const z=B("button","sw-layout-button",v);return z.type="button",z.disabled=k,m(z,"click",M),z},y=g("Layout",()=>{r=o==="layout"?!r:!0,o="layout",T(),n.requestMeasure()});y.classList.add("sw-layout-toggle"),y.setAttribute("aria-expanded","false");const x=B("span","sw-layout-hint","Select layers and edit literal JSX"),b=g("Undo",()=>Ia(n)),C=g("Redo",()=>js(n)),Q=g("Theme",()=>{r=o==="theme"?!r:!0,o="theme",T(),n.requestMeasure()});Q.setAttribute("aria-expanded","false");const P=g("Assets",()=>{r=o==="assets"?!r:!0,o="assets",T(),n.requestMeasure()});P.setAttribute("aria-expanded","false"),i.append(y,Q,P,x,b,C),t.append(i,s),s.hidden=b.hidden=C.hidden=!0;const w=B("p","sw-layout-error");w.setAttribute("role","alert"),w.hidden=!0,t.append(w);function L(){a=vi(n.state.doc.toString());const v=B("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(v),v.append(B("div","sw-layout-title","Widget assets")),v.append(B("p","sw-layout-notice","Insert editable original JSX or a package image. Originals follow connected theme colors; pet artwork is static. Import photos with the app's existing image tools or Web Studio's Add image.")),a.issue){v.append(B("p","sw-layout-notice",a.issue));return}const M=a.nodes.filter(q=>q.structure),k=B("select");k.setAttribute("aria-label","Asset destination");for(const q of M){const G=B("option","",`${q.tag} · line ${n.state.doc.lineAt(q.from).number}`);G.value=q.id,k.append(G)}M.some(q=>q.id===l)?k.value=l:l=k.value,m(k,"change",()=>{l=k.value}),v.append(k);const z=n.state.readOnly||!M.length;M.length||v.append(B("p","sw-layout-notice","Add a stack/grid with literal JSX children in Code to insert assets."));function re(q,G){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const ce=zS(a,n.state.doc.toString(),{id:k.value,kind:q,path:G},n.state.field(lr));l=k.value,w.hidden=!0,n.dispatch({changes:ce.changes,selection:{anchor:ce.selectedFrom},annotations:Qs.of("full"),userEvent:"input.asset",scrollIntoView:!0})}catch(ce){w.textContent=ce.message,w.hidden=!1}}for(const[q,G]of Object.entries(jd)){const ce=B("div","sw-layout-actions");ce.append(g(`Insert ${G.name}`,()=>re(q),z),B("span","",G.description)),v.append(ce)}v.append(B("div","sw-layout-title","Package images"));const N=n.state.field(lr),ee=B("select");ee.setAttribute("aria-label","Package image");for(const q of N){const G=B("option","",q);G.value=q,ee.append(G)}ee.disabled=!N.length,v.append(ee,g("Insert package image",()=>re("photo",ee.value),z||!N.length)),N.length||v.append(B("p","sw-layout-notice","No supported images in image/. Add a PNG, JPEG or WebP to the package, then refresh or reopen the editor.")),e.refreshResources&&v.append(g("Refresh images",async()=>{const q=++f,G=n.state.doc,ce=()=>!u&&q===f&&n.state.doc===G;try{const V=await e.refreshResources();ce()&&(w.hidden=!0,rl(n,V))}catch{ce()&&(w.textContent="Images could not be refreshed. Reopen this document and try again.",w.hidden=!1)}})),v.append(B("p","sw-layout-notice","Bloom mark, Leaf mark and Pebble friend: original ScriptWidget geometry, MIT licensed. Package photos retain their own rights. See the Studio assets documentation."))}function D(v,M){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const k=n.state.doc.toString();if(k!==M)throw new Error("Source changed. Reopen Theme before editing.");const z=v(k);w.hidden=!0,z.changes.length&&n.dispatch({changes:z.changes,annotations:Qs.of("full"),userEvent:"input.theme"})}catch(k){w.textContent=k.message,w.hidden=!1}}function W(){const v=n.state.doc.toString(),M=ar(v),k=n.state.readOnly,z=B("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(z),z.append(B("div","sw-layout-title","Widget theme")),z.append(B("p","sw-layout-notice","Saved as ordinary JavaScript with your widget. Dynamic values stay in Code. Applying a theme changes the connected colors, fonts and spacing.")),M.issue){z.append(B("p","sw-layout-notice",M.issue));return}if(!M.tokens){z.append(g("Connect layout to Meadow theme",()=>D(ee=>WS(ee),v),k||!M.canInitialize)),M.canInitialize||z.append(B("p","sw-layout-notice","Use a literal top-level $render layout, or define the documented widgetTheme object in Code."));return}const re=B("div","sw-layout-actions");for(const[ee,q]of Object.entries(or))re.append(g(ee,()=>D(G=>fo(M,G,q),v),k));z.append(re);for(const[ee,q]of Object.entries(Hi)){const G=B("form","sw-layout-form"),ce=B("label","",ee),V=B(q.values?"select":"input");if(q.values)for(const oe of q.values){const Me=B("option","",oe);Me.value=oe,V.append(Me)}q.type==="number"&&(V.type="number",V.min="0",V.max=String(q.maximum),V.step="any"),V.value=String(M.tokens[ee]),V.setAttribute("aria-label",`Theme ${ee}`),V.disabled=k;const te=g(`Apply ${ee}`,()=>{},k);te.type="submit",G.append(ce,V,te),m(G,"submit",oe=>{oe.preventDefault();const Me=q.type==="number"?V.value.trim()?Number(V.value):NaN:V.value;D(Oe=>fo(M,Oe,{...M.tokens,[ee]:Me}),v)}),z.append(G)}const N=B("textarea");N.rows=5,N.setAttribute("aria-label","Reusable theme JSON"),N.value=IS(M.tokens),z.append(B("label","","Copy this JSON to reuse a theme, or paste a version 1 theme and import it."),N,g("Import theme JSON",()=>D(ee=>fo(M,ee,zd(N.value).tokens),v),k))}function F(v,M=a?.source){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");if(M!==n.state.doc.toString())throw new Error("Source changed during this operation. Select the layer again.");const k=BS(a,n.state.doc.toString(),v);if(w.hidden=!0,!k.changes.length)return;n.dispatch({changes:k.changes,selection:{anchor:k.selectedFrom},annotations:Qs.of("full"),userEvent:"input.layout",scrollIntoView:!0})}catch(k){w.textContent=k.message,w.hidden=!1}}function U(v){u||(l=v.id,c="",n.dispatch({selection:{anchor:v.from,head:v.to},scrollIntoView:!0,userEvent:"select.layout"}),T())}function T(){if(y.setAttribute("aria-expanded",String(r&&o==="layout")),Q.setAttribute("aria-expanded",String(r&&o==="theme")),P.setAttribute("aria-expanded",String(r&&o==="assets")),s.hidden=!r,b.hidden=C.hidden=!r,x.hidden=r,b.disabled=n.state.readOnly||Qc(n.state)===0,C.disabled=n.state.readOnly||Pc(n.state)===0,!r)return;if(o==="assets"){L();return}if(o==="theme"){W();return}if(a=vi(n.state.doc.toString()),s.replaceChildren(),a.issue){s.append(B("p","sw-layout-notice",a.issue));return}const v=n.state.selection.main.from,M=a.nodes.filter(V=>V.from<=v&&v<V.to).at(-1),k=a.nodes.find(V=>V.id===l&&V.from<=v&&v<=V.to)??M??a.nodes[0];l=k.id;const z=B("div","sw-layout-layers");z.setAttribute("role","tree"),z.setAttribute("aria-label","Layout layers");const re=n.state.readOnly,N=V=>{const te=V.text??V.properties.find(oe=>oe.name==="text"&&oe.editable&&typeof oe.value=="string")?.value;return`<${V.tag}>${te?` · ${te.slice(0,32)}`:""}${V.locked?" · locked":""}`};for(const[V,te]of a.nodes.entries()){const oe=a.nodes.find(ie=>ie.id===te.parentID),Me=!re&&!te.locked&&oe?.structure,Oe=g(N(te),()=>U(te));Oe.classList.add("sw-layout-layer"),Oe.dataset.layerId=te.id,Oe.style.paddingInlineStart=`${8+te.depth*14}px`,Oe.setAttribute("role","treeitem"),Oe.setAttribute("aria-level",String(te.depth+1)),Oe.setAttribute("aria-selected",String(te.id===k.id)),Oe.tabIndex=te.id===k.id?0:-1,Oe.draggable=!!Me,m(Oe,"keydown",ie=>{let ve;ie.key==="ArrowUp"&&(ve=a.nodes[Math.max(0,V-1)]),ie.key==="ArrowDown"&&(ve=a.nodes[Math.min(a.nodes.length-1,V+1)]),ie.key==="ArrowLeft"&&(ve=oe),ie.key==="ArrowRight"&&(ve=a.nodes.find(Ie=>Ie.id===te.children[0])),ie.key==="Home"&&(ve=a.nodes[0]),ie.key==="End"&&(ve=a.nodes.at(-1)),ve&&(ie.preventDefault(),ie.stopPropagation(),U(ve),ee().find(Ie=>Ie.dataset.layerId===ve.id)?.focus())}),m(Oe,"dragstart",ie=>{if(!Me){ie.preventDefault();return}h={id:te.id,source:a.source},ie.dataTransfer.setData("application/x-scriptwidget-layer",d),ie.dataTransfer.effectAllowed="move"}),m(Oe,"dragover",ie=>{h&&oe?.structure&&te.id!==h.id&&(ie.preventDefault(),ie.dataTransfer.dropEffect="move")}),m(Oe,"drop",ie=>{if(!h||ie.dataTransfer.getData("application/x-scriptwidget-layer")!==d||!oe?.structure)return;ie.preventDefault();const ve=h;h=null,F({type:"move",id:ve.id,parentID:oe.id,index:oe.children.filter(Ie=>Ie!==ve.id).indexOf(te.id)},ve.source)}),m(Oe,"dragend",()=>{h=null}),z.append(Oe)}function ee(){return[...t.querySelectorAll(".sw-layout-layer")]}const q=B("div","sw-layout-inspector"),G=B("div","sw-layout-title",`<${k.tag}>`);if(q.append(G),(re||k.locked)&&q.append(B("p","sw-layout-notice",re?"This document is read only.":k.reason)),!re&&!k.locked){let Oe=function(){c=oe.value;const ae=da(k)[c],Ae=k.properties.find(tt=>tt.name===c);if(Me.replaceChildren(),te.onsubmit=tt=>tt.preventDefault(),Ae&&!Ae.editable){Me.append(B("span","sw-layout-notice","Dynamic value: edit it in Code. Connected widgetTheme tokens can be changed in Theme."));return}const le=B(ae.values||ae.type==="boolean"?"select":"input");le.setAttribute("aria-label","Layout property value");for(const tt of ae.values??(ae.type==="boolean"?[!0,!1]:[])){const li=B("option","",String(tt));li.value=String(tt),le.append(li)}le.value=Ae?String(Ae.value):ae.values?.[0]??(ae.type==="boolean"?"true":"");const We=g("Apply",()=>{});We.type="submit",Me.append(le,We,g("Remove",()=>F({type:"property",id:k.id,name:c,remove:!0}),!Ae||ae.required)),te.onsubmit=p(te,tt=>{tt.preventDefault();const li=ae.type==="boolean"?le.value==="true":ae.type==="number"?le.value.trim()?Number(le.value):NaN:le.value;F({type:"property",id:k.id,name:c,value:li})})};if(k.textEditable){const ae=B("form","sw-layout-form"),Ae=B("label","","Text"),le=B("input");le.value=k.text,le.setAttribute("aria-label","Layer text");const We=g("Apply text",()=>{});We.type="submit",ae.append(Ae,le,We),m(ae,"submit",tt=>{tt.preventDefault(),F({type:"text",id:k.id,value:le.value})}),q.append(ae)}const V=Object.entries(da(k)).filter(([,ae])=>VS(ae)),te=B("form","sw-layout-form"),oe=B("select");oe.setAttribute("aria-label","Layout property");for(const[ae]of V){const Ae=B("option","",ae);Ae.value=ae,oe.append(Ae)}V.some(([ae])=>ae===c)||(c=k.structure?"alignment":"color"),oe.value=c,oe.value||(oe.selectedIndex=0,c=oe.value);const Me=B("div","sw-layout-property");te.append(oe,Me),m(oe,"change",Oe),Oe(),q.append(te);const ie=a.nodes.find(ae=>ae.id===k.parentID),ve=ie?.children.indexOf(k.id)??-1,Ie=B("div","sw-layout-actions");if(Ie.append(g("Move up",()=>F({type:"move",id:k.id,parentID:ie.id,index:ve-1}),!ie?.structure||ve<=0),g("Move down",()=>F({type:"move",id:k.id,parentID:ie.id,index:ve+1}),!ie?.structure||ve>=ie.children.length-1),g("Delete layer",()=>F({type:"remove",id:k.id}),!ie?.structure)),q.append(Ie),ie?.structure){const ae=a.nodes.filter(le=>le.structure&&!(le.from>=k.from&&le.to<=k.to)),Ae=B("select");Ae.setAttribute("aria-label","Move layer into container");for(const le of ae){const We=B("option","",`${le.tag} · line ${n.state.doc.lineAt(le.from).number}`);We.value=le.id,Ae.append(We)}q.append(Ae,g("Move inside",()=>{const le=a.nodes.find(We=>We.id===Ae.value);F({type:"move",id:k.id,parentID:le.id,index:le.children.filter(We=>We!==k.id).length})},!ae.length))}if(k.structure){const ae=B("div","sw-layout-actions");for(const[Ae,le]of[["text","Add text"],["stack","Add stack"],["spacer","Add spacer"],["icon","Add icon"]])ae.append(g(le,()=>F({type:"add",id:k.id,kind:Ae})));q.append(ae)}}const ce=k.properties.filter(V=>!V.editable).map(V=>V.name);ce.length&&q.append(B("p","sw-layout-notice",`Preserved in Code: ${ce.join(", ")}`)),!k.structure&&k.children.length&&q.append(B("p","sw-layout-notice","This child structure stays in Code. Reordering is available on literal stack/grid children.")),s.append(z,q)}return{dom:t,top:!0,update(v){if(!r)return;const M=n.state.selection.main.from,k=a?.nodes.filter(re=>re.from<=M&&M<re.to).at(-1)?.id,z=v.transactions.some(re=>re.effects.some(N=>N.is(sl)));(v.docChanged||z||v.startState.readOnly!==n.state.readOnly||v.selectionSet&&k!==l)&&(v.docChanged&&o!=="assets"&&(l=null),T()),b.disabled=n.state.readOnly||Qc(n.state)===0,C.disabled=n.state.readOnly||Pc(n.state)===0},destroy(){u=!0}}}const YS=K.baseTheme({".sw-layout":{fontFamily:"system-ui, sans-serif",fontSize:"12px",backgroundColor:"#f6f7fa",color:"#272a34",borderBottom:"1px solid #dce0e9"},"&dark .sw-layout":{backgroundColor:"#252830",color:"#eceef5",borderColor:"#414552"},".sw-layout-header":{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",padding:"6px 10px"},".sw-layout-toggle":{fontWeight:"600"},".sw-layout-hint":{opacity:"0.65",fontSize:"11px"},".sw-layout-button":{fontFamily:"inherit",fontSize:"11px",color:"inherit",backgroundColor:"transparent",border:"1px solid #a0a5b655",borderRadius:"6px",padding:"4px 8px",cursor:"pointer",whiteSpace:"nowrap"},".sw-layout-button:disabled":{opacity:"0.4",cursor:"default"},".sw-layout-body":{display:"grid",gridTemplateColumns:"minmax(120px, 1fr) minmax(180px, 1.6fr)",maxHeight:"280px",overflow:"auto",borderTop:"1px solid #a0a5b633"},".sw-layout-body[hidden]":{display:"none"},".sw-layout-layers":{padding:"6px 2px",overflow:"auto",borderRight:"1px solid #a0a5b633"},".sw-layout-layer":{display:"block",border:0,borderRadius:"4px",width:"100%",textAlign:"left",overflow:"hidden",textOverflow:"ellipsis",margin:"1px 0",paddingBlock:"6px"},'.sw-layout-layer[aria-selected="true"]':{backgroundColor:"#4085f52b",color:"inherit"},".sw-layout-inspector":{padding:"8px 10px",display:"flex",alignItems:"start",flexDirection:"column",gap:"8px",minWidth:0},".sw-theme-inspector":{gridColumn:"1 / -1"},".sw-theme-inspector textarea":{boxSizing:"border-box",width:"100%",fontFamily:"monospace",backgroundColor:"transparent",color:"inherit",border:"1px solid #a0a5b666",borderRadius:"5px"},".sw-layout-title":{fontWeight:"600"},".sw-layout-form":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"5px",width:"100%"},".sw-layout-property,.sw-layout-actions":{display:"flex",flexWrap:"wrap",gap:"5px",alignItems:"center"},".sw-layout input,.sw-layout select":{fontFamily:"inherit",fontSize:"12px",minWidth:0,maxWidth:"100%",padding:"4px 6px",border:"1px solid #a0a5b666",borderRadius:"5px",backgroundColor:"transparent",color:"inherit"},".sw-layout-notice":{margin:"8px",lineHeight:"1.5",fontSize:"11px",opacity:"0.7"},".sw-layout-body > .sw-layout-notice":{gridColumn:"1 / -1"},".sw-layout-error":{margin:"0 10px 6px",color:"#b32636",fontSize:"12px"},"&dark .sw-layout-error":{color:"#ff99a4"},".sw-layout button:focus-visible,.sw-layout input:focus-visible,.sw-layout select:focus-visible":{outline:"2px solid #4085f5",outlineOffset:"1px"},"@media (max-width: 480px)":{".sw-layout-body":{gridTemplateColumns:"minmax(90px, 1fr) minmax(150px, 1.6fr)"},".sw-layout-hint":{display:"none"}}});function NS(n={}){return[YS,lr,Vi.of(e=>jS(e,n))]}const Yd="scriptwidget.studio.document-state.v1.";function Nd(n,e,t){if(!n||!e)return!1;try{return n.setItem(`${Yd}${e}`,JSON.stringify({anchor:Number(t.anchor)||0,head:Number(t.head)||0,scrollTop:Number(t.scrollTop)||0})),!0}catch{return!1}}function HS(n,e,t){if(!n||!e)return null;try{const i=JSON.parse(n.getItem(`${Yd}${e}`));if(!i||typeof i!="object")return null;const s=r=>Math.max(0,Math.min(Number(r)||0,t));return{anchor:s(i.anchor),head:s(i.head),scrollTop:Math.max(0,Number(i.scrollTop)||0)}}catch{return null}}const GS="scriptwidget.web-studio.draft.v1:";function ol(n){return`${GS}${n}`}function _S(n,e){if(!e)return null;try{const t=JSON.parse(n.getItem(ol(e))||"null");return t&&typeof t.content=="string"&&typeof t.baseRevision=="string"?t:null}catch{return null}}function ph(n,e,t,i,s=Date.now()){if(!e||typeof i!="string")return null;const r={documentID:e,content:t,baseRevision:i,updatedAt:s};return n.setItem(ol(e),JSON.stringify(r)),r}function mo(n,e){e&&n.removeItem(ol(e))}function JS(n,e,t,i){const s=_S(n,e);return!s||s.content===t?null:{...s,serverContent:t,serverRevision:i,isStale:s.baseRevision!==i}}function e1(){return{connection:"connecting",save:"idle",preview:"idle",conflict:null}}function t1(n,e){switch(e.type){case"CONNECTED":return{...n,connection:"connected"};case"OFFLINE":return{...n,connection:"offline",save:n.save==="saving"?"draft":n.save};case"DISCONNECTED":return{...n,connection:"disconnected"};case"EDITED":return{...n,save:"draft",conflict:null};case"SAVING":return{...n,save:"saving"};case"SAVED":return{...n,save:"saved",preview:e.preview||"requested",conflict:null};case"SAVE_FAILED":return{...n,save:"error"};case"CONFLICT":return{...n,save:"conflict",conflict:e.conflict};default:return n}}class i1{constructor(e){this.send=e,this.epoch=0,this.context=null,this.inFlight=null,this.needsFlush=!1}open({documentID:e,packageID:t,path:i,revision:s,content:r}){return this.epoch+=1,this.context={documentID:e,packageID:t,path:i,revision:s,content:r,generation:0,savedGeneration:0},this.needsFlush=!1,this.snapshot()}edit(e){return this.context?(this.context.content=e,this.context.generation+=1,this.snapshot()):null}rebase(e){return this.context&&(this.context.revision=e),this.snapshot()}get isDirty(){return!!(this.context&&this.context.generation!==this.context.savedGeneration)}snapshot(){return this.context?{...this.context,dirty:this.isDirty}:null}async flush(){if(!this.context||!this.isDirty)return{skipped:!0,snapshot:this.snapshot()};if(this.inFlight)return this.needsFlush=!0,this.inFlight.then(()=>this.isDirty?this.flush():{skipped:!0,snapshot:this.snapshot()});const e=this.epoch,t={...this.context};this.needsFlush=!1,this.inFlight=this.send({documentID:t.documentID,packageID:t.packageID,path:t.path,content:t.content,baseRevision:t.revision}).then(s=>this.epoch!==e||this.context?.documentID!==t.documentID?{ignored:!0,result:s,snapshot:this.snapshot()}:(this.context.revision=s.revision,this.context.savedGeneration=t.generation,{result:s,snapshot:this.snapshot()})).finally(()=>{this.inFlight=null});const i=await this.inFlight;return this.needsFlush&&this.isDirty?this.flush():i}}function mh(n){return["draft","saving","error","conflict"].includes(n)}class n1 extends Error{constructor(e,t,i={}){super(e),this.name="StudioAPIError",this.status=t,this.body=i}}class s1{constructor({fetchImpl:e=globalThis.fetch,token:t=()=>"",onUnauthorized:i=()=>{}}={}){if(typeof e!="function")throw new TypeError("A fetch implementation is required");this.fetchImpl=e,this.token=t,this.onUnauthorized=i}async request(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t)),s=await i.json().catch(()=>({}));return this.validate(i,e,s),s}async requestBlob(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t));if(!i.ok){const s=await i.json().catch(()=>({}));this.validate(i,e,s)}return i.blob()}authorizedOptions(e){return{...e,headers:{"Content-Type":"application/json","X-Studio-Token":this.token(),...e.headers||{}}}}validate(e,t,i){if(!e.ok){const s=new n1(i.message||`Request failed (${e.status})`,e.status,i);throw e.status===401&&t!=="/api/v1/pair"&&this.onUnauthorized(s),s}}}const al=/^https?:$/.test(window.location.protocol)&&!window.ScriptWidgetAndroid,r1=document.querySelector(al?"#editor":"#native-editor"),ll=new Gi,cr=new Gi;let qt=null,me=null,Et=null,at=0,wi=0,pa=!1,En=null,gh=null;const Oh=document.querySelector("#save-status");let Hd=null;function Un(n,e="idle"){Oh.textContent=n,Oh.dataset.state=e}function o1(){window.clearTimeout(gh),gh=window.setTimeout(()=>{const n=j.state.selection.main;Nd(window.localStorage,me,{anchor:n.anchor,head:n.head,scrollTop:j.scrollDOM.scrollTop})},180)}function Gd(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function cl(){window.clearTimeout(En),Un("Saving…","saving"),En=window.setTimeout(()=>{const n=j.state.doc.toString(),e=at,t=me,i=Et,s=wi;nn(qt,Ue.documentSave,{content:n,version:e},t,(r={})=>{al||t!==me||i!==Et||s!==wi||e!==at||Un(r.result==="ok"||r.result==="unavailable"?"Saved":"Save failed",r.result==="failed"?"error":"saved")},i)},700)}function a1(n){if((n.selectionSet||n.viewportChanged||n.docChanged)&&o1(),!n.docChanged||pa)return;at+=1,Hd?.documentChanged();const e=[];n.changes.iterChanges((t,i,s,r,o)=>{e.push({from:t,to:i,insert:o.toString(),newFrom:s,newTo:r})}),nn(qt,Ue.documentChanged,{changes:e,version:at},me,void 0,Et),cl()}const _d=[lO(),uO(),Pg(),T0(),NS({refreshResources:()=>new Promise((n,e)=>{const t=me,i=wi,s=Et,r=window.setTimeout(()=>e(new Error("Resource refresh timed out")),5e3);nn(qt,Ue.documentResources,{},t,(o={})=>{window.clearTimeout(r),t!==me||i!==wi||o.result!=="ok"||o.documentID!==t||!Array.isArray(o.resources)?e(new Error("Document resources are unavailable")):n(o.resources)},s)})}),t0(),mg(),Sg(),J.allowMultipleSelections.of(!0),BO(),p0(),gA(),PA({override:[RS],activateOnTyping:!0}),Lg(),Ig(),Zg(),$b(),OS(),aS(Ld,{delay:350}),Lu($S),vb({jsx:!0}),Or.of([Ky,...bA,...$y,..._b,...D0,...GO,...ad]),ll.of(J.readOnly.of(!1)),cr.of(Xd(Gd())),K.updateListener.of(a1),K.contentAttributes.of({autocapitalize:"off",autocomplete:"off",spellcheck:"false"})],j=new K({state:J.create({doc:"",extensions:_d}),parent:r1});function Jt(n,e=me,t=0,i=!1){window.clearTimeout(En),wi+=1;const s=j.state.selection.main;Nd(window.localStorage,me,{anchor:s.anchor,head:s.head,scrollTop:j.scrollDOM.scrollTop}),pa=!0;const r=e!==me;me=e,at=t;const o=HS(window.localStorage,me,(n??"").length),a=o?{anchor:o.anchor,head:o.head}:{anchor:0};if(r){const l=cr.get(j.state),c=j.state.readOnly;let h=J.create({doc:n??"",extensions:_d,selection:a});h=h.update({effects:[cr.reconfigure(l),ll.reconfigure(J.readOnly.of(c))]}).state,j.setState(h)}else j.dispatch({changes:{from:0,to:j.state.doc.length,insert:n??""},selection:a,scrollIntoView:!0});o&&window.requestAnimationFrame(()=>{j.scrollDOM.scrollTop=o.scrollTop}),pa=!1,i&&nn(qt,Ue.documentChanged,{content:j.state.doc.toString(),version:at},me,void 0,Et),Un("Saved","saved")}function yh(n){if(j.state.readOnly)return!1;const e=j.state.selection.main;return j.dispatch({changes:{from:e.from,to:e.to,insert:n},selection:{anchor:e.from+n.length},userEvent:"input"}),j.focus(),!0}async function hr(){if(j.state.readOnly)return!1;const n=j.state.doc.toString(),e=wi,t=at,i=()=>!j.state.readOnly&&e===wi&&t===at&&n===j.state.doc.toString();try{const[{format:s},{default:r},{default:o}]=await Promise.all([Rr(()=>import("./standalone-Cayz_KD-.js"),[],import.meta.url),Rr(()=>import("./babel-BktJt1uC.js"),[],import.meta.url),Rr(()=>import("./estree-DFfjoHvx.js"),[],import.meta.url)]),a=await s(n,{parser:"babel",plugins:[r,o],semi:!0,singleQuote:!0,trailingComma:"es5"});return i()?(Jt(a,me,at+1,!0),cl(),!0):!1}catch(s){return i()&&nn(qt,"diagnostics.publish",{message:String(s),severity:"error"},me,void 0,Et),!1}}function Xi(n){j.dispatch({effects:ll.reconfigure(J.readOnly.of(!!n))})}function ur(n){const e=n==="dark"||n==="light"?n:Gd();document.documentElement.dataset.theme=e,j.dispatch({effects:cr.reconfigure(Xd(e))})}function l1(n=[]){const e=n.map(t=>({from:Math.max(0,Math.min(t.from??0,j.state.doc.length)),to:Math.max(0,Math.min(t.to??t.from??0,j.state.doc.length)),severity:t.severity??"error",message:t.message??"Unknown error"}));j.dispatch(Pd(j.state,e))}function rt(n,e){qt.registerHandler(n,async(t={},i=()=>{})=>{try{if(Et!==null&&n!==Ue.documentOpen&&n!==Ue.editorSetTheme&&(t.documentID!==me||t.sessionID!==Et))throw new Error("The editor session changed.");i({result:"ok",...await e(t)})}catch(s){i({result:"failed",message:String(s)})}})}AS(n=>{qt=n,rt(Ue.documentOpen,({payload:e={},documentID:t,sessionID:i=null})=>(Et=i,Jt(e.content,t,e.version??0),rl(j,e.resources??[]),Xi(e.readOnly),e.dirty&&(Un("Restored unsaved edits","editing"),e.readOnly||cl()),{protocolVersion:Fd})),rt(Ue.documentReplace,({payload:e={},documentID:t})=>{if(j.state.readOnly||e.expectedContent!==void 0&&e.expectedContent!==j.state.doc.toString())throw new Error("The file changed or is read only.");return Jt(e.content,t,e.version??at,!0),{}}),rt(Ue.documentSetReadOnly,({payload:e={}})=>(Xi(e.readOnly),{readOnly:!!e.readOnly})),rt(Ue.editorInsert,({payload:e={}})=>({inserted:yh(e.content??"")})),rt(Ue.editorFormat,async()=>({formatted:await hr()})),rt(Ue.editorSetTheme,({payload:e={}})=>(ur(e.theme),{})),rt(Ue.editorGetState,()=>({content:j.state.doc.toString(),version:at,documentID:me,sessionID:Et,selection:{from:j.state.selection.main.from,to:j.state.selection.main.to}})),rt(Ue.diagnosticsPublish,({payload:e={}})=>(l1(e.items),{})),rt("editor_setValue",({value:e})=>(Jt(e),{})),rt("editor_insertValue",({value:e})=>({inserted:yh(e??"")})),rt("editor_getValue",()=>({value:j.state.doc.toString()})),rt("editor_setReadonly",({readonly:e})=>(Xi(e),{readonly:!!e})),rt("editor_formatCode",async()=>({formatted:await hr()})),bS(qt)});al&&(document.querySelector("#native-editor").hidden=!0,document.querySelector("#web-studio").hidden=!1,c1());async function c1(){const n=document.querySelector("#pair-dialog"),e=document.querySelector("#pair-form"),t=document.querySelector("#pair-error"),i=document.querySelector("#package-select"),s=document.querySelector("#file-select"),r=document.querySelector("#connection-status"),o=document.querySelector("#disconnect-button"),a=document.querySelector("#studio-grid"),l=document.querySelector(".editor-column"),c=document.querySelector("#recovery-banner"),h=document.querySelector("#conflict-banner"),u=document.querySelector("#command-dialog"),f=document.querySelector("#command-search"),d=document.querySelector("#command-list"),p=document.querySelector("#compare-dialog");let m=window.sessionStorage.getItem("scriptwidget.web-studio.token")||"",g=[],y=null,x=null,b=null,C=0,Q=null,P="",w="",L=null,D=e1(),W="",F="",U=null;function T(S="Session ended. Enter the new code shown on your device."){m="",window.sessionStorage.removeItem("scriptwidget.web-studio.token"),o.hidden=!0,v({type:"DISCONNECTED"}),r.textContent=S,Xi(!0),n.open||n.showModal()}function v(S){D=t1(D,S);const E={connecting:"Connecting",connected:"Connected",offline:"Offline",disconnected:"Disconnected"},X={idle:"Ready",draft:"Draft saved locally",saving:"Saving…",saved:"Saved",error:"Save failed",conflict:"Conflict"};r.dataset.state=D.connection,document.querySelector("#status-connection").textContent=E[D.connection]||D.connection,Un(X[D.save]||D.save,D.save),document.querySelector("#dirty-indicator").hidden=!["draft","saving","error","conflict"].includes(D.save),document.querySelector("#status-preview").textContent=D.preview==="requested"?"Preview requested":"Preview idle",document.querySelector("#preview-detail").textContent=D.preview==="requested"?"Requested on device":"Not requested"}const M=new s1({token:()=>m,onUnauthorized:()=>T()}),k=(S,E)=>M.request(S,E);U=new i1(({packageID:S,path:E,content:X,baseRevision:ne})=>k("/api/v1/document",{method:"PUT",body:JSON.stringify({package:S,path:E,content:X,baseRevision:ne})}));async function z(S){m=(await k("/api/v1/pair",{method:"POST",body:JSON.stringify({code:S})})).token,window.sessionStorage.setItem("scriptwidget.web-studio.token",m),o.hidden=!1,v({type:"CONNECTED"}),re()}function re(){window.clearInterval(y),y=window.setInterval(async()=>{if(m)try{const S=await k("/api/v1/session");if(!navigator.onLine)return;V(S),v({type:"CONNECTED"})}catch(S){S.status!==401&&(r.textContent=`Interrupted · ${S.message}`,v({type:"OFFLINE"}))}},5e3)}async function N(){if(g=(await k("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(E=>new Option(E.name,E.id))),!g.length){r.textContent="No editable widgets",Xi(!0);return}await ee()}async function ee(){const S=g.find(ne=>ne.id===i.value),E=S?.files||[];s.replaceChildren(...E.map(ne=>new Option(ne,ne)));const X=E.includes(S?.entry)?S.entry:E[0];X&&(s.value=X),await G()}async function q(S=""){g=(await k("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(ge=>new Option(ge.name,ge.id))),W&&(i.value=W);const X=g.find(ge=>ge.id===i.value),ne=X?.files||[];s.replaceChildren(...ne.map(ge=>new Option(ge,ge))),s.value=ne.includes(S)?S:ne.includes(F)?F:X?.entry||ne[0]}async function G(){if(!i.value||!s.value)return;const S=new URLSearchParams({package:i.value,path:s.value}),E=await k(`/api/v1/document?${S}`),X=`${i.value}/${s.value}`;W=i.value,F=s.value,P=E.revision,w=E.content,L=null,h.hidden=!0,Jt(E.content,X,0),rl(j,g.find(ge=>ge.id===W)?.files??[]),U.open({documentID:X,packageID:W,path:F,revision:E.revision,content:E.content}),Xi(!!E.readOnly),ce(E);const ne=JS(window.localStorage,X,E.content,E.revision);c.hidden=!ne,c._draft=ne,document.querySelector("#recovery-message").textContent=ne?.isStale?"The device version also changed. Review before saving.":"Restore it or keep the device version.",r.textContent="Connected",v({type:"CONNECTED"}),o.hidden=!1,Oe(),re(),Me()}function ce(S){document.querySelector("#breadcrumb-package").textContent=S.packageName||i.value,document.querySelector("#breadcrumb-file").textContent=s.value,document.querySelector("#editor-tab-name").textContent=s.value,document.querySelector("#revision-detail").textContent=P?P.slice(0,8):"—",document.querySelector("#access-detail").textContent=S.readOnly?"Read only":"Editable"}function V(S){S.device&&(document.querySelector("#device-name").textContent=S.device.name||S.device.model,document.querySelector("#device-system").textContent=`${S.device.model} · ${S.device.system}`),S.preview?.package&&(document.querySelector("#preview-target").textContent=S.preview.package),S.preview?.snapshotSequence&&te()}async function te(){try{const S=await M.requestBlob("/api/v1/preview"),E=URL.createObjectURL(S),X=document.querySelector("#device-preview"),ne=Q;Q=E,X.onload=()=>{ne&&URL.revokeObjectURL(ne)},X.src=E,X.hidden=!1,document.querySelector("#preview-detail").textContent="Rendered on device"}catch{}}function oe(S){const E=document.querySelector("#console-list"),X=document.createElement("li");for(X.className=S.level||"info",X.textContent=S.message||"",E.append(X);E.children.length>200;)E.firstChild.remove();E.scrollTop=E.scrollHeight}function Me(){window.clearTimeout(b);const S=async()=>{if(m)try{const E=await k(`/api/v1/events?after=${C}`);C=E.nextSequence??C;for(const X of E.events||[])X.type==="console"&&oe(X.payload||{}),X.type==="preview.snapshot"&&te(),X.type==="preview.requested"&&(document.querySelector("#status-preview").textContent="Preview requested",document.querySelector("#preview-detail").textContent="Requested on device"),X.type==="files.changed"&&X.payload?.package===W&&q(F).catch(Ie);v({type:"CONNECTED"})}catch(E){E.status!==401&&v({type:"OFFLINE"})}finally{m&&(b=window.setTimeout(S,1e3))}};S()}function Oe(){const S=Ld(j);document.querySelector("#problems-list").replaceChildren(...S.map(X=>{const ne=j.state.doc.lineAt(X.from),ge=document.createElement("li");ge.className=`problem-item ${X.severity}`;const it=document.createElement("button");return it.type="button",it.innerHTML=`<span class="problem-severity">${X.severity==="error"?"●":"▲"}</span><span></span><span class="problem-location">Ln ${ne.number}</span>`,it.children[1].textContent=X.message,it.addEventListener("click",()=>{j.dispatch({selection:{anchor:X.from},scrollIntoView:!0}),j.focus()}),ge.append(it),ge})),document.querySelector("#problems-count").textContent=String(S.length),document.querySelector("#status-problem-count").textContent=String(S.length),document.querySelector("#problems-summary").textContent=S.length?`${S.filter(X=>X.severity==="error").length} errors, ${S.filter(X=>X.severity!=="error").length} warnings`:"No problems detected"}async function ie(S,E,X=null){U.snapshot()?.content!==S&&U.edit(S),X&&U.rebase(X),v({type:"SAVING"});try{const ne=await U.flush();if(ne.ignored){E({result:"ok",ignored:!0});return}if(ne.skipped){v({type:"SAVED"}),E({result:"ok",skipped:!0});return}const ge=ne.result||{},it=U.snapshot();P=it?.revision||P,w=it?.content||S,mo(window.localStorage,me),L=null,h.hidden=!0,document.querySelector("#revision-detail").textContent=P?.slice(0,8)||"—",v({type:"SAVED",preview:ge.preview?.state}),E({result:"ok",...ge})}catch(ne){ne.status===409?(L=ne.body,h.hidden=!1,v({type:"CONFLICT",conflict:L})):v({type:"SAVE_FAILED"}),E({result:"failed",message:ne.message})}}qt={registerHandler(){},callHandler(S,E,X=()=>{}){if(S===Ue.documentSave)ie(E.payload.content,X);else if(S===Ue.documentResources){const ne=me,ge=W;k("/api/v1/packages").then(it=>{if(ne!==me||E.documentID!==me||ge!==W){X({result:"failed"});return}X({result:"ok",documentID:ne,resources:(it.packages??[]).find(Vn=>Vn.id===ge)?.files??[]})}).catch(()=>X({result:"failed"}))}else X({result:"ok"})}},Hd={documentChanged(){const S=j.state.doc.toString();U.edit(S),ph(window.localStorage,me,S,U.snapshot()?.revision||P),v({type:"EDITED"}),window.clearTimeout(x),x=window.setTimeout(Oe,380)}};async function ve(S,E){if(!mh(D.save)){await S();return}try{if(window.clearTimeout(En),await ie(j.state.doc.toString(),()=>{}),!U.isDirty&&D.save!=="conflict"){await S();return}}catch{}window.confirm("This document has changes that are not saved on the device. A browser draft is available. Switch anyway?")?await S():E()}i.addEventListener("change",()=>{const S=i.value;i.value=W,ve(async()=>{i.value=S,await ee()},()=>{i.value=W}).catch(Ie)}),s.addEventListener("change",()=>{const S=s.value;s.value=F,ve(async()=>{s.value=S,await G()},()=>{s.value=F}).catch(Ie)});function Ie(S){r.textContent=S.message||String(S),v({type:"SAVE_FAILED"})}e.addEventListener("submit",async S=>{S.preventDefault(),t.textContent="";try{await z(document.querySelector("#pair-code").value),n.close(),await N()}catch(E){t.textContent=E.message}}),o.addEventListener("click",async()=>{try{await k("/api/v1/session",{method:"DELETE"})}catch{}T("Disconnected. Start a new session with the code on your device.")}),document.querySelector("#new-file").addEventListener("click",async()=>{const S=window.prompt("New package-relative text file","source/helper.js")?.trim();if(S)try{await k("/api/v1/document",{method:"POST",body:JSON.stringify({package:W,path:S})}),await q(S),await G()}catch(E){Ie(E)}}),document.querySelector("#delete-file").addEventListener("click",async()=>{const S=g.find(E=>E.id===W);if(!F||F===S?.entry){window.alert("The widget entry file cannot be deleted.");return}if(window.confirm(`Delete ${F}? This cannot be undone.`))try{const E=new URLSearchParams({package:W,path:F});await k(`/api/v1/document?${E}`,{method:"DELETE"}),F="",await q(),await G()}catch(E){Ie(E)}}),document.querySelector("#clear-console").addEventListener("click",()=>document.querySelector("#console-list").replaceChildren()),document.querySelector("#restore-draft").addEventListener("click",()=>{const S=c._draft;S&&(Jt(S.content,S.documentID,at+1),c.hidden=!0,ph(window.localStorage,me,S.content,P),v({type:"EDITED"}),Oe())}),document.querySelector("#discard-draft").addEventListener("click",()=>{mo(window.localStorage,me),c.hidden=!0}),document.querySelector("#reload-server").addEventListener("click",()=>{L&&(mo(window.localStorage,me),P=L.currentRevision,w=L.currentContent,Jt(w,me,at+1),U.open({documentID:me,packageID:W,path:F,revision:P,content:w}),L=null,h.hidden=!0,v({type:"SAVED"}),Oe())}),document.querySelector("#keep-local").addEventListener("click",()=>{L&&ie(j.state.doc.toString(),()=>{},L.currentRevision)}),document.querySelector("#compare-conflict").addEventListener("click",()=>{document.querySelector("#compare-local").textContent=j.state.doc.toString(),document.querySelector("#compare-server").textContent=L?.currentContent||w,p.showModal()}),p.querySelector("button").addEventListener("click",()=>p.close());function ae(){const S=l.classList.toggle("problems-collapsed");document.querySelector("#problems-toggle").setAttribute("aria-expanded",String(!S))}function Ae(S){a.classList.toggle(`show-${S}`)}document.querySelector("#problems-toggle").addEventListener("click",ae),document.querySelector("#status-problems").addEventListener("click",()=>{l.classList.remove("problems-collapsed")}),document.querySelector("#explorer-button").addEventListener("click",()=>Ae("explorer")),document.querySelector("#inspector-button").addEventListener("click",()=>Ae("inspector")),document.querySelectorAll("[data-close-panel]").forEach(S=>S.addEventListener("click",()=>a.classList.remove(`show-${S.dataset.closePanel}`)));const le=[{name:"Save Document",keys:"⌘S",run:()=>{window.clearTimeout(En),ie(j.state.doc.toString(),()=>{})}},{name:"Format Document",keys:"⇧⌥F",run:hr},{name:"Toggle Problems",keys:"⌘J",run:ae},{name:"Toggle Explorer",keys:"⌘⇧E",run:()=>Ae("explorer")},{name:"Toggle Inspector",keys:"",run:()=>Ae("inspector")},{name:"Use Light Theme",keys:"",run:()=>ur("light")},{name:"Use Dark Theme",keys:"",run:()=>ur("dark")}];function We(S=""){const E=le.filter(X=>X.name.toLowerCase().includes(S.toLowerCase()));d.replaceChildren(...E.map(X=>{const ne=document.createElement("li"),ge=document.createElement("button");ge.type="button",ge.className="command";const it=document.createElement("span");it.textContent=X.name;const Vn=document.createElement("kbd");return Vn.textContent=X.keys,ge.append(it,Vn),ge.addEventListener("click",()=>{u.close(),X.run()}),ne.append(ge),ne}))}function tt(){We(),u.showModal(),f.value="",f.focus()}document.querySelector("#command-button").addEventListener("click",tt),f.addEventListener("input",()=>We(f.value)),document.addEventListener("keydown",S=>{const E=S.metaKey||S.ctrlKey;E&&S.shiftKey&&S.key.toLowerCase()==="p"?(S.preventDefault(),tt()):E&&S.key.toLowerCase()==="s"?(S.preventDefault(),le[0].run()):E&&S.key.toLowerCase()==="j"?(S.preventDefault(),ae()):E&&S.shiftKey&&S.key.toLowerCase()==="e"?(S.preventDefault(),Ae("explorer")):S.shiftKey&&S.altKey&&S.key.toLowerCase()==="f"&&(S.preventDefault(),hr())}),j.dom.addEventListener("keyup",li),j.dom.addEventListener("mouseup",li);function li(){const S=j.state.selection.main.head,E=j.state.doc.lineAt(S);document.querySelector("#cursor-position").textContent=`Ln ${E.number}, Col ${S-E.from+1}`}window.addEventListener("offline",()=>{r.textContent="Computer is offline",v({type:"OFFLINE"})}),window.addEventListener("online",()=>{m&&k("/api/v1/session").then(S=>(V(S),v({type:"CONNECTED"}),N())).catch(Ie)}),window.addEventListener("beforeunload",S=>{mh(D.save)&&(S.preventDefault(),S.returnValue="")});try{await N()}catch{T("Pair with the code shown on your device.")}}window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener("change",()=>ur("system"));window.webkit||Jt(`// ScriptWidget Studio const widget = ( <VStack> <Text text="Hello, ScriptWidget" /> diff --git a/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/index.html b/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/index.html index 8ce4827a..e6b4066a 100644 --- a/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/index.html +++ b/iOS/ScriptWidget/View/CodeEditor/MirrorEditor/StudioEditor.bundle/index.html @@ -5,7 +5,7 @@ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, viewport-fit=cover" /> <meta name="color-scheme" content="light dark" /> <title>ScriptWidget Web Studio - + diff --git a/macOS/ScriptWidgetMac/StudioEditor.bundle/assets/index-5y-iWtKj.js b/macOS/ScriptWidgetMac/StudioEditor.bundle/assets/index-Bc_zNuTW.js similarity index 72% rename from macOS/ScriptWidgetMac/StudioEditor.bundle/assets/index-5y-iWtKj.js rename to macOS/ScriptWidgetMac/StudioEditor.bundle/assets/index-Bc_zNuTW.js index 9a73af91..594c1da9 100644 --- a/macOS/ScriptWidgetMac/StudioEditor.bundle/assets/index-5y-iWtKj.js +++ b/macOS/ScriptWidgetMac/StudioEditor.bundle/assets/index-Bc_zNuTW.js @@ -1,14 +1,14 @@ -(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();const Yd="modulepreload",Nd=function(n,e){return new URL(n,e).href},al={},Cr=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let c=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=c(t.map(h=>{if(h=Nd(h,i),h in al)return;al[h]=!0;const u=h.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(i)for(let p=o.length-1;p>=0;p--){const m=o[p];if(m.href===h&&(!u||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${f}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Yd,u||(d.as="script"),d.crossOrigin="",d.href=h,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((p,m)=>{d.addEventListener("load",p),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};let po=[],mh=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=mh[i])e=i+1;else return!0;if(e==t)return!1}}function ll(n){return n>=127462&&n<=127487}const cl=8205;function Gd(n,e,t=!0,i=!0){return(t?gh:_d)(n,e,i)}function gh(n,e,t){if(e==n.length)return e;e&&Oh(n.charCodeAt(e))&&yh(n.charCodeAt(e-1))&&e--;let i=Tr(n,e);for(e+=hl(i);e=0&&ll(Tr(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function _d(n,e,t){for(;e>1;){let i=gh(n,e-2,t);if(i=56320&&n<57344}function yh(n){return n>=55296&&n<56320}function hl(n){return n<65536?1:2}class se{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Bi(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),kt.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Bi(this,e,t);let i=[];return this.decompose(e,t,i,0),kt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new pn(this),r=new pn(e);for(let o=t,a=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(a+=s.value.length,s.done||a>=i)return!0}}iter(e=1){return new pn(this,e)}iterRange(e,t=this.length){return new Ah(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new bh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?se.empty:e.length<=32?new we(e):kt.from(we.split(e,[]))}}class we extends se{constructor(e,t=Jd(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],a=s+o.length;if((t?i:a)>=e)return new ep(s,a,i,o);s=a+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new we(ul(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),a=gs(r.text,o.text.slice(),0,r.length);if(a.length<=32)i.push(new we(a,o.length+r.length));else{let l=a.length>>1;i.push(new we(a.slice(0,l)),new we(a.slice(l)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof we))return super.replace(e,t,i);[e,t]=Bi(this,e,t);let s=gs(this.text,gs(i.text,ul(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new we(s,r):kt.from(we.split(s,[]),r)}sliceString(e,t=this.length,i=` +(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))i(s);new MutationObserver(s=>{for(const r of s)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function t(s){const r={};return s.integrity&&(r.integrity=s.integrity),s.referrerPolicy&&(r.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?r.credentials="include":s.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(s){if(s.ep)return;s.ep=!0;const r=t(s);fetch(s.href,r)}})();const Jd="modulepreload",ep=function(n,e){return new URL(n,e).href},hl={},Rr=function(e,t,i){let s=Promise.resolve();if(t&&t.length>0){let c=function(h){return Promise.all(h.map(u=>Promise.resolve(u).then(f=>({status:"fulfilled",value:f}),f=>({status:"rejected",reason:f}))))};const o=document.getElementsByTagName("link"),a=document.querySelector("meta[property=csp-nonce]"),l=a?.nonce||a?.getAttribute("nonce");s=c(t.map(h=>{if(h=ep(h,i),h in hl)return;hl[h]=!0;const u=h.endsWith(".css"),f=u?'[rel="stylesheet"]':"";if(i)for(let p=o.length-1;p>=0;p--){const m=o[p];if(m.href===h&&(!u||m.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${h}"]${f}`))return;const d=document.createElement("link");if(d.rel=u?"stylesheet":Jd,u||(d.as="script"),d.crossOrigin="",d.href=h,l&&d.setAttribute("nonce",l),document.head.appendChild(d),u)return new Promise((p,m)=>{d.addEventListener("load",p),d.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${h}`)))})}))}function r(o){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=o,window.dispatchEvent(a),!a.defaultPrevented)throw o}return s.then(o=>{for(const a of o||[])a.status==="rejected"&&r(a.reason);return e().catch(r)})};let go=[],Ah=[];(()=>{let n="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(n=Ah[i])e=i+1;else return!0;if(e==t)return!1}}function ul(n){return n>=127462&&n<=127487}const fl=8205;function ip(n,e,t=!0,i=!0){return(t?bh:np)(n,e,i)}function bh(n,e,t){if(e==n.length)return e;e&&Sh(n.charCodeAt(e))&&xh(n.charCodeAt(e-1))&&e--;let i=$r(n,e);for(e+=dl(i);e=0&&ul($r(n,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function np(n,e,t){for(;e>1;){let i=bh(n,e-2,t);if(i=56320&&n<57344}function xh(n){return n>=55296&&n<56320}function dl(n){return n<65536?1:2}class se{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=Bi(this,e,t);let s=[];return this.decompose(0,e,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(t,this.length,s,1),kt.from(s,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=Bi(this,e,t);let i=[];return this.decompose(e,t,i,0),kt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),s=new pn(this),r=new pn(e);for(let o=t,a=t;;){if(s.next(o),r.next(o),o=0,s.lineBreak!=r.lineBreak||s.done!=r.done||s.value!=r.value)return!1;if(a+=s.value.length,s.done||a>=i)return!0}}iter(e=1){return new pn(this,e)}iterRange(e,t=this.length){return new vh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let s=this.line(e).from;i=this.iterRange(s,Math.max(s,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new wh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?se.empty:e.length<=32?new we(e):kt.from(we.split(e,[]))}}class we extends se{constructor(e,t=sp(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.text[r],a=s+o.length;if((t?i:a)>=e)return new rp(s,a,i,o);s=a+1,i++}}decompose(e,t,i,s){let r=e<=0&&t>=this.length?this:new we(pl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(s&1){let o=i.pop(),a=ys(r.text,o.text.slice(),0,r.length);if(a.length<=32)i.push(new we(a,o.length+r.length));else{let l=a.length>>1;i.push(new we(a.slice(0,l)),new we(a.slice(l)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof we))return super.replace(e,t,i);[e,t]=Bi(this,e,t);let s=ys(this.text,ys(i.text,pl(this.text,0,e)),t),r=this.length+i.length-(t-e);return s.length<=32?new we(s,r):kt.from(we.split(s,[]),r)}sliceString(e,t=this.length,i=` `){[e,t]=Bi(this,e,t);let s="";for(let r=0,o=0;r<=t&&oe&&o&&(s+=i),er&&(s+=a.slice(Math.max(0,e-r),t-r)),r=l+1}return s}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],s=-1;for(let r of e)i.push(r),s+=r.length+1,i.length==32&&(t.push(new we(i,s)),i=[],s=-1);return s>-1&&t.push(new we(i,s)),t}}class kt extends se{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,s){for(let r=0;;r++){let o=this.children[r],a=s+o.length,l=i+o.lines-1;if((t?l:a)>=e)return o.lineInner(e,t,i,s);s=a+1,i=l+1}}decompose(e,t,i,s){for(let r=0,o=0;o<=t&&r=o){let c=s&((o<=e?1:0)|(l>=t?2:0));o>=e&&l<=t&&!c?i.push(a):a.decompose(e-o,t-o,i,c)}o=l+1}}replace(e,t,i){if([e,t]=Bi(this,e,t),i.lines=r&&t<=a){let l=o.replace(e-r,t-r,i),c=this.lines-o.lines+l.lines;if(l.lines>4&&l.lines>c>>6){let h=this.children.slice();return h[s]=l,new kt(h,this.length-(t-e)+i.length)}return super.replace(r,a,l)}r=a+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` -`){[e,t]=Bi(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=a.sliceString(e-o,t-o,i)),o=l+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof kt))return 0;let i=0,[s,r,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==a)return i;let l=this.children[s],c=e.children[r];if(l!=c)return i+l.scanIdentical(c,t);i+=l.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new we(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,a=[],l=0,c=-1,h=[];function u(d){let p;if(d.lines>r&&d instanceof kt)for(let m of d.children)u(m);else d.lines>o&&(l>o||!l)?(f(),a.push(d)):d instanceof we&&l&&(p=h[h.length-1])instanceof we&&d.lines+p.lines<=32?(l+=d.lines,c+=d.length+1,h[h.length-1]=new we(p.text.concat(d.text),p.length+1+d.length)):(l+d.lines>s&&f(),l+=d.lines,c+=d.length+1,h.push(d))}function f(){l!=0&&(a.push(h.length==1?h[0]:kt.from(h,c)),c=-1,l=h.length=0)}for(let d of e)u(d);return f(),a.length==1?a[0]:new kt(a,t)}}se.empty=new we([""],0);function Jd(n){let e=-1;for(let t of n)e+=t.length+1;return e}function gs(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(l>i&&(a=a.slice(0,i-s)),s0?1:(e instanceof we?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,a=s instanceof we?s.text.length:s.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` -`,this;e--}else if(s instanceof we){let l=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=s.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof we?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Ah{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new pn(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class bh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(se.prototype[Symbol.iterator]=function(){return this.iter()},pn.prototype[Symbol.iterator]=Ah.prototype[Symbol.iterator]=bh.prototype[Symbol.iterator]=function(){return this});class ep{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}}function Bi(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function Ze(n,e,t=!0,i=!0){return Gd(n,e,t,i)}function tp(n){return n>=56320&&n<57344}function ip(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!ip(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return tp(i)?(t-55296<<10)+(i-56320)+65536:t}function fa(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Qt(n){return n<65536?1:2}const mo=/\r\n?|\n/;var De=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(De||(De={}));class Zt{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=a}else{if(i!=De.Simple&&c>=e&&(i==De.TrackDel&&se||i==De.TrackBefore&&se))return null;if(c>e||c==e&&t<0&&!a)return e==s||t<0?r:r+l;r+=l}s=c}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&a>=e)return st?"cover":!0;s=a}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Zt(e)}static create(e){return new Zt(e)}}class Re extends Zt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return go(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Oo(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=a,t[s+1]=o;let l=s>>1;for(;i.length0&&Ht(i,t,r.text),r.forward(h),a+=h}let c=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,a=null;function l(h=!1){if(!h&&!s.length)return;of||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let p=d?typeof d=="string"?se.of(d.split(i||mo)):d:se.empty,m=p.length;if(u==f&&m==0)return;uo&&Xe(s,u-o,-1),Xe(s,f-u,m),Ht(r,s,p),o=f}}return c(e),l(!a),a}static empty(e){return new Re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sa&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function Ht(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(s,c,r,h,u),s=c,r=h}}}function Oo(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Sn(n),a=new Sn(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);Xe(s,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let c=0,h=o.len;for(;h;)if(a.ins==-1){let u=Math.min(h,a.len);c+=u,h-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||i.length>c),r.forward2(l),o.forward(l)}}}}class Sn{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?se.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?se.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Yt{constructor(e,t,i,s){this.from=e,this.to=t,this.flags=i,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new Yt(i,s,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return A.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return A.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return A.range(e.anchor,e.head)}static create(e,t,i,s){return new Yt(e,t,i,s)}}class A{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:A.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new A(e.ranges.map(t=>Yt.fromJSON(t)),e.main)}static single(e,t=e){return new A([A.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?A.range(l,a):A.range(a,l))}}return new A(e,t)}}function xh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let da=0;class K{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=da++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new K(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:pa),!!e.static,e.enables)}of(e){return new Os([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Os(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new Os(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function pa(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class Os{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=da++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,a=this.type==2,l=!1,c=!1,h=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?c=!0:(((t=e[u.id])!==null&&t!==void 0?t:1)&1)==0&&h.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||c&&(f.docChanged||f.selection)||yo(u,h)){let d=i(u);if(a?!fl(d,u.values[o],s):!s(d,u.values[o]))return u.values[o]=d,1}return 0},reconfigure:(u,f)=>{let d,p=f.config.address[r];if(p!=null){let m=Cs(f,p);if(this.dependencies.every(g=>g instanceof K?f.facet(g)===u.facet(g):g instanceof Te?f.field(g,!1)==u.field(g,!1):!0)||(a?fl(d=i(u),m,s):s(d=i(u),m)))return u.values[o]=m,0}else d=i(u);return u.values[o]=d,1}}}get extension(){return this}}function fl(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[l.id]),s=t.map(l=>l.type),r=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let c=[];for(let h=0;hi===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(Vn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(Vn),o=s.facet(Vn),a;return(a=r.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(i.values[t]=a.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,Vn.of({field:this,create:e})]}get extension(){return this}}const fi={lowest:4,low:3,default:2,high:1,highest:0};function sn(n){return e=>new vh(e,n)}const ri={highest:sn(fi.highest),high:sn(fi.high),default:sn(fi.default),low:sn(fi.low),lowest:sn(fi.lowest)};class vh{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class Gi{of(e){return new Ao(this,e)}reconfigure(e){return Gi.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Ao{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class Ps{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let f of sp(e,t,o))f instanceof Te?s.push(f):(r[f.facet.id]||(r[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],c=[];for(let f of s)a[f.id]=c.length<<1,c.push(d=>f.slot(d));let h=i?.config.facets;for(let f in r){let d=r[f],p=d[0].facet,m=h&&h[f]||[];if(d.every(g=>g.type==0))if(a[p.id]=l.length<<1|1,pa(m,d))l.push(i.facet(p));else{let g=p.combine(d.map(y=>y.value));l.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(a[g.id]=l.length<<1|1,l.push(g.value)):(a[g.id]=c.length<<1,c.push(y=>g.dynamicSlot(y)));a[p.id]=c.length<<1,c.push(g=>np(g,p,d))}}let u=c.map(f=>f(a));return new Ps(e,o,u,a,l,r)}}function sp(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,a){let l=s.get(o);if(l!=null){if(l<=a)return;let c=i[l].indexOf(o);c>-1&&i[l].splice(c,1),o instanceof Ao&&t.delete(o.compartment)}if(s.set(o,a),Array.isArray(o))for(let c of o)r(c,a);else if(o instanceof Ao){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;t.set(o.compartment,c),r(c,a)}else if(o instanceof vh)r(o.inner,o.prec);else if(o instanceof Te)i[a].push(o),o.provides&&r(o.provides,a);else if(o instanceof Os)i[a].push(o),o.facet.extensions&&r(o.facet.extensions,fi.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(c==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(c,a)}}return r(n,fi.default),i.reduce((o,a)=>o.concat(a))}function mn(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Cs(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const wh=K.define(),bo=K.define({combine:n=>n.some(e=>e),static:!0}),kh=K.define({combine:n=>n.length?n[0]:void 0,static:!0}),Qh=K.define(),Ph=K.define(),Ch=K.define(),Th=K.define({combine:n=>n.length?n[0]:!1});class qt{constructor(e,t){this.type=e,this.value=t}static define(){return new rp}}class rp{of(e){return new qt(this,e)}}class op{constructor(e){this.map=e}of(e){return new z(this,e)}}class z{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new z(this.type,t)}is(e){return this.type==e}static define(e={}){return new op(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}}z.reconfigure=z.define();z.appendConfig=z.define();class Pe{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&xh(i,t.newLength),r.some(a=>a.type==Pe.time)||(this.annotations=r.concat(Pe.time.of(Date.now())))}static create(e,t,i,s,r,o){return new Pe(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(Pe.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}Pe.time=qt.define();Pe.userEvent=qt.define();Pe.addToHistory=qt.define();Pe.remote=qt.define();function ap(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof Pe?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof Pe?n=r[0]:n=$h(e,Zi(r),!1)}return n}function cp(n){let e=n.startState,t=e.facet(Ch),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=Rh(i,So(e,r,n.changes.newLength),!0))}return i==n?n:Pe.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const hp=[];function Zi(n){return n==null?hp:Array.isArray(n)?n:[n]}var ye=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(ye||(ye={}));const up=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let xo;try{xo=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function fp(n){if(xo)return xo.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||up.test(t)))return!0}return!1}function dp(n){return e=>{if(!/\S/.test(e))return ye.Space;if(fp(e))return ye.Word;for(let t=0;t-1)return ye.Word;return ye.Other}}class _{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let a=0;as.set(c,l)),t=null),s.set(a.value.compartment,a.value.extension)):a.is(z.reconfigure)?(t=null,i=a.value):a.is(z.appendConfig)&&(t=null,i=Zi(i).concat(a.value));let r;t?r=e.startState.values.slice():(t=Ps.resolve(i,s,this),r=new _(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(bo)?e.newSelection:e.newSelection.asSingle();new _(t,e.newDoc,o,r,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:A.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Zi(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return _.create({doc:e.doc,selection:A.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=Ps.resolve(e.extensions||[],new Map),i=e.doc instanceof se?e.doc:se.of((e.doc||"").split(t.staticFacet(_.lineSeparator)||mo)),s=e.selection?e.selection instanceof A?e.selection:A.single(e.selection.anchor,e.selection.head):A.single(0);return xh(s,i.length),t.staticFacet(bo)||(s=s.asSingle()),new _(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(_.tabSize)}get lineBreak(){return this.facet(_.lineSeparator)||` -`}get readOnly(){return this.facet(Th)}phrase(e,...t){for(let i of this.facet(_.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(wh))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return dp(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,a=e-i;for(;o>0;){let l=Ze(t,o,!1);if(r(t.slice(l,o))!=ye.Word)break;o=l}for(;an.length?n[0]:4});_.lineSeparator=kh;_.readOnly=Th;_.phrases=K.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});_.languageData=wh;_.changeFilter=Qh;_.transactionFilter=Ph;_.transactionExtender=Ch;Gi.reconfigure=z.define();function yt(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],a=i[r];if(a===void 0)i[r]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](a,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}class Jt{eq(e){return this==e}range(e,t=e){return vo.create(e,t,this)}}Jt.prototype.startSide=Jt.prototype.endSide=0;Jt.prototype.point=!1;Jt.prototype.mapMode=De.TrackDel;function ma(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}let vo=class Kh{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new Kh(e,t,i)}};function wo(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class ga{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,a=r.length;;){if(o==a)return o;let l=o+a>>1,c=r[l]-e||(i?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||f==d&&c.startSide>0&&c.endSide<=0)continue;(d-f||c.endSide-c.startSide)<0||(o<0&&(o=f),c.point&&(a=Math.max(a,d-f)),i.push(c),s.push(f-o),r.push(d-o))}return{mapped:i.length?new ga(s,r,i,a):null,pos:o}}}class N{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new N(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(wo)),this.isEmpty)return t.length?N.of(t):this;let a=new Zh(this,null,-1).goto(0),l=0,c=[],h=new Bt;for(;a.value||l=0){let u=t[l++];h.addInner(u.from,u.to,u.value)||c.push(u)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||ra.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return xn.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return xn.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),l=dl(o,a,i),c=new rn(o,l,r),h=new rn(a,l,r);i.iterGaps((u,f,d)=>pl(c,u,h,f,d,s)),i.empty&&i.length==0&&pl(c,0,h,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),o=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let a=dl(r,o),l=new rn(r,a,0).goto(i),c=new rn(o,a,0).goto(i);for(;;){if(l.to!=c.to||!ko(l.active,c.active)||l.point&&(!c.point||!ma(l.point,c.point)))return!1;if(l.to>s)return!0;l.next(),c.next()}}static spans(e,t,i,s,r=-1){let o=new rn(e,null,r).goto(t),a=t,l=o.openStart;for(;;){let c=Math.min(o.to,i);if(o.point){let h=o.activeForPoint(o.to),u=o.pointFroma&&(s.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>i)return l+(o.point&&o.to>i?1:0);a=o.to,o.next()}}static of(e,t=!1){let i=new Bt;for(let s of e instanceof vo?[e]:t?pp(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return N.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=N.empty;s=s.nextLayer)t=new N(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}}N.empty=new N([],[],null,-1);function pp(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(wo);e=i}return n}N.empty.nextLayer=N.empty;class Bt{finishChunk(e){this.chunks.push(new ga(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new Bt)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(N.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=N.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function dl(n,e,t){let i=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&s.push(new Zh(o,t,i,r));return s.length==1?s[0]:new xn(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Rr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Rr(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Rr(this.heap,0)}}}function Rr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}class rn{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=xn.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){jn(this.active,e),jn(this.activeTo,e),jn(this.activeRank,e),this.minActive=ml(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;Yn(this.active,t,i),Yn(this.activeTo,t,s),Yn(this.activeRank,t,r),e&&Yn(e,t,this.cursor.from),this.minActive=ml(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&jn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function pl(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,a=i,l=i-e,c=!!r.boundChange;for(let h=!1;;){let u=n.to+l-t.to,f=u||n.endSide-t.endSide,d=f<0?n.to+l:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&ma(n.point,t.point)&&ko(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(a,p,n.point,t.point),h=!1):(h&&r.boundChange(a),p>a&&!ko(n.active,t.active)&&r.compareRange(a,p,n.active,t.active),c&&po)break;a=d,f<=0&&n.next(),f>=0&&t.next()}}function ko(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function ml(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=Ze(n,s)}return i===!0?-1:n.length}const Po="ͼ",gl=typeof Symbol>"u"?"__"+Po:Symbol.for(Po),Co=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Ol=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class ei{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,a,l,c){let h=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let d in a){let p=a[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,l);else if(p&&typeof p=="object"){if(!u)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,h,f)}else p!=null&&h.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(h.length||f)&&l.push((i&&!u&&!c?o.map(i):o).join(", ")+" {"+h.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` -`)}static newName(){let e=Ol[gl]||1;return Ol[gl]=e+1,Po+e.toString(36)}static mount(e,t,i){let s=e[Co],r=i&&i.nonce;s?r&&s.setNonce(r):s=new mp(e,r),s.mount(Array.isArray(t)?t:[t],e)}}let yl=new Map;class mp{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=yl.get(i);if(r)return e[Co]=r;this.sheet=new s.CSSStyleSheet,yl.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Co]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o-1&&(this.modules.splice(l,1),r--,l=-1),l==-1){if(this.modules.splice(r++,0,a),i)for(let c=0;c",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"',229:"Q"},Al=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),gp=typeof navigator<"u"&&/Apple Computer/.test(navigator.vendor),Op=typeof navigator<"u"&&/Gecko\/\d+/.test(navigator.userAgent),bl=typeof navigator<"u"&&/Mac/.test(navigator.platform),yp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Ap=Al&&(bl||+Al[1]<57)||Op&&bl;for(var Fe=0;Fe<10;Fe++)ti[48+Fe]=ti[96+Fe]=String(Fe);for(var Fe=1;Fe<=24;Fe++)ti[Fe+111]="F"+Fe;for(var Fe=65;Fe<=90;Fe++)ti[Fe]=String.fromCharCode(Fe+32),vn[Fe]=String.fromCharCode(Fe);for(var $r in ti)vn.hasOwnProperty($r)||(vn[$r]=ti[$r]);function bp(n){var e=Ap&&(n.ctrlKey||n.altKey||n.metaKey)||(gp||yp)&&n.shiftKey&&n.key&&n.key.length==1,t=!e&&n.key||(n.shiftKey?vn:ti)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function he(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e2);var R={mac:vl||/Mac/.test(qe.platform),windows:/Win/.test(qe.platform),linux:/Linux|X11/.test(qe.platform),ie:hr,ie_version:Eh?To.documentMode||6:$o?+$o[1]:Ro?+Ro[1]:0,gecko:Sl,gecko_version:Sl?+(/Firefox\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,chrome:!!Kr,chrome_version:Kr?+Kr[1]:0,ios:vl,android:/Android\b/.test(qe.userAgent),webkit:xl,webkit_version:xl?+(/\bAppleWebKit\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,safari:Ko,safari_version:Ko?+(/\bVersion\/(\d+(\.\d+)?)/.exec(qe.userAgent)||[0,0])[1]:0,tabSize:To.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Oa(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}const Ts=Object.create(null);function ya(n,e,t){if(n==e)return!0;n||(n=Ts),e||(e=Ts);let i=Object.keys(n),s=Object.keys(e);if(i.length-0!=s.length-0)return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function Sp(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function wl(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function xp(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Ai(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Uh(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Ai(e,i,s,t,e.widget||null,!0)}static line(e){return new Fn(e)}static set(e,t=!1){return N.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}B.none=N.empty;class Un extends B{constructor(e){let{start:t,end:i}=Uh(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Oa(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||Ts}eq(e){return this==e||e instanceof Un&&this.tagName==e.tagName&&ya(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Un.prototype.point=!1;class Fn extends B{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Fn&&this.spec.class==e.spec.class&&ya(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Fn.prototype.mapMode=De.TrackBefore;Fn.prototype.point=!0;class Ai extends B{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?De.TrackBefore:De.TrackAfter:De.TrackDel}get type(){return this.startSide!=this.endSide?Le.WidgetRange:this.startSide<=0?Le.WidgetBefore:Le.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof Ai&&vp(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Ai.prototype.point=!0;function Uh(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function vp(n,e){return n==e||!!(n&&e&&n.compare(e))}function Mi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}class wn extends Jt{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof wn&&this.tagName==e.tagName&&ya(this.attributes,e.attributes)}static create(e){return new wn(e.tagName,e.attributes||Ts,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return N.of(e,t)}}wn.prototype.startSide=wn.prototype.endSide=-1;function kn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Zo(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function gn(n,e){if(!e.anchorNode)return!1;try{return Zo(n,e.anchorNode)}catch{return!1}}function ys(n){return n.nodeType==3?Qn(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function On(n,e,t,i){return t?kl(n,e,t,i,-1)||kl(n,e,t,i,1):!1}function ii(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Rs(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function kl(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:It(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=ii(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?It(n):0}else return!1}}function It(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function $s(n,e){let{left:t,right:i}=n;if(t==i)return n;let s=e?t:i;return{left:s,right:s,top:n.top,bottom:n.bottom}}function wp(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Fh(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function kp(n,e,t,i,s,r,o,a){let l=n.ownerDocument,c=l.defaultView||window;for(let h=n,u=!1;h&&!u;)if(h.nodeType==1){let f,d=h==l.body,p=1,m=1;if(d)f=wp(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(h).position)&&(u=!0),h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let b=h.getBoundingClientRect();({scaleX:p,scaleY:m}=Fh(h,b)),f={left:b.left,right:b.left+h.clientWidth*p,top:b.top,bottom:b.top+h.clientHeight*m}}let g=0,y=0;if(s=="nearest")e.top0&&e.bottom>f.bottom+y&&(y=e.bottom-f.bottom+o)):e.bottom>f.bottom-o&&(y=e.bottom-f.bottom+o,t<0&&e.top-y0&&e.right>f.right+g&&(g=e.right-f.right+r)):e.right>f.right-r&&(g=e.right-f.right+r,t<0&&e.leftf.bottom||e.leftf.right)&&(e={left:Math.max(e.left,f.left),right:Math.min(e.right,f.right),top:Math.max(e.top,f.top),bottom:Math.min(e.bottom,f.bottom)}),h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function Dh(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}class Qp{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?It(t):0),i,Math.min(e.focusOffset,i?It(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}}function Lh(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function Xh(n,e=!0){for(let{node:t,left:i,top:s}of n)e&&t.scrollTop!=s&&(t.scrollTop=s),t.scrollLeft!=i&&(t.scrollLeft=i)}let ui=null;R.safari&&R.safari_version>=26&&(ui=!1);function Bh(n){if(n.setActive)return n.setActive();if(ui)return n.focus(ui);let e=Lh(n);n.focus(ui==null?{get preventScroll(){return ui={preventScroll:!0},!0}}:void 0),ui||(ui=!1,Xh(e))}let Ql;function Qn(n,e,t=e){let i=Ql||(Ql=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function Ei(n,e,t,i){let s={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=i);let r=new KeyboardEvent("keydown",s);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function Pp(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function Cp(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,It(t));;)if(i){if(t.nodeType!=1)return!1;let s=t.childNodes[i-1];s.contentEditable=="false"?i--:(t=s,i=It(t))}else{if(t==n)return!0;i=ii(t),t=t.parentNode}}function Ih(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function Wh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=It(t)}else if(t.parentNode&&!Rs(t))i=ii(t),t=t.parentNode;else return null}}function qh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(a.level==i)return o;(r<0||(s!=0?s<0?a.fromt:e[r].level>a.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}function jh(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;m-=3)if(St[m+1]==-d){let g=St[m+2],y=g&2?s:g&4?g&1?r:s:0;y&&(ue[u]=ue[St[m]]=y),a=m;break}}else{if(St.length==189)break;St[a++]=u,St[a++]=f,St[a++]=l}else if((p=ue[u])==2||p==1){let m=p==s;l=m?0:1;for(let g=a-3;g>=0;g-=3){let y=St[g+2];if(y&2)break;if(m)St[g+2]|=2;else{if(y&4)break;St[g+2]|=4}}}}}function Mp(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,a=sl;)p==g&&(p=t[--m].from,g=m?t[m-1].to:n),ue[--p]=d;l=h}else r=c,l++}}}function Eo(n,e,t,i,s,r,o){let a=i%2?2:1;if(i%2==s%2)for(let l=e,c=0;ll&&o.push(new Ct(l,m.from,d));let g=m.direction==bi!=!(d%2);Uo(n,g?i+1:i,s,m.inner,m.from,m.to,o),l=m.to}p=m.to}else{if(p==t||(h?ue[p]!=a:ue[p]==a))break;p++}f?Eo(n,l,p,i+1,s,f,o):le;){let h=!0,u=!1;if(!c||l>r[c-1].to){let m=ue[l-1];m!=a&&(h=!1,u=m==16)}let f=!h&&a==1?[]:null,d=h?i:i+1,p=l;e:for(;;)if(c&&p==r[c-1].to){if(u)break e;let m=r[--c];if(!h)for(let g=m.from,y=c;;){if(g==e)break e;if(y&&r[y-1].to==g)g=r[--y].from;else{if(ue[g-1]==a)break e;break}}if(f)f.push(m);else{m.toue.length;)ue[ue.length]=256;let i=[],s=e==bi?0:1;return Uo(n,s,s,t,0,n.length,i),i}function Yh(n){return[new Ct(0,n,0)]}let Nh="";function Up(n,e,t,i,s){var r;let o=i.head-n.from,a=Ct.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),l=e[a],c=l.side(s,t);if(o==c){let f=a+=s?1:-1;if(f<0||f>=e.length)return null;l=e[a=f],o=l.side(!s,t),c=l.side(s,t)}let h=Ze(n.text,o,l.forward(s,t));(hl.to)&&(h=c),Nh=n.text.slice(Math.min(o,h),Math.max(o,h));let u=a==(s?e.length-1:0)?null:e[a+(s?1:-1)];return u&&h==c&&u.level+(s?0:1)n.some(e=>e)}),nu=K.define({combine:n=>n.some(e=>e)}),su=K.define();class Ui{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new Ui(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Ui(A.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Nn=z.define({map:(n,e)=>n.map(e)}),ru=z.define();function ze(n,e,t){let i=n.facet(Jh);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const Dt=K.define({combine:n=>n.length?n[0]:!0});let Dp=0;const Ti=K.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let l=[];return o&&l.push(ur.of(c=>{let h=c.plugin(a);return h?o(h):B.none})),r&&l.push(r(a)),l})}static fromClass(e,t){return xe.define((i,s)=>new e(i,s),t)}}class Zr{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ze(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ze(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ze(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const ou=K.define(),xa=K.define(),ur=K.define(),au=K.define(),va=K.define(),Dn=K.define(),lu=K.define();function Pl(n,e){let t=n.state.facet(lu);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return N.spans(i,e.from,e.to,{point(){},span(r,o,a,l){let c=r-e.from,h=o-e.from,u=s;for(let f=a.length-1;f>=0;f--,l--){let d=a[f].spec.bidiIsolate,p;if(d==null&&(d=Fp(e.text,c,h)),l>0&&u.length&&(p=u[u.length-1]).to==c&&p.direction==d)p.to=h,u=p.inner;else{let m={from:c,to:h,direction:d,inner:[]};u.push(m),u=m.inner}}}}),s}const cu=K.define();function wa(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(cu)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}const hn=K.define();class ct{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new ct(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new ct(r,o,a,l))),this.changedRanges=s}static create(e,t,i){return new Ks(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const Lp=[];class Se{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return Lp}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Sp(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=ii(this.dom),s=this.length?e>0:t>0;return new pt(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof dr)return e;return null}static get(e){return e.cmTile}}class fr extends Se{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=a.dom&&(r.written=!0),a.dom.parentNode==t)for(;s&&s!=a.dom;)s=Cl(s);else t.insertBefore(a.dom,s);i=a.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=Cl(s);this.length=o}}function Cl(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class dr extends fr{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Se.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof Lt)t.push(s),i=o,s=0;else{let a=r+o.length,l=e(o,r);if(l!==void 0)return l;r=a+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&t>=-1&&t<=1){if(a.flags&32)return!0;a.flags&16&&(i=void 0)}(le||e==l&&(t>1?a.length:a.covers(-1)))&&(!r||!a.isWidget()&&r.isWidget())&&(r=a,o=e-l)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}}class Lt extends fr{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new Lt(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class Ii extends fr{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new Ii(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,a=-1;function l(h,u){for(let f=0,d=0;f=u&&(p.isComposite()?l(p,u-d):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Bp(o,p)))&&(m>u||p.flags&32&&t<=1)?(o=p,a=u-d):(d=-1)&&(s=p,r=u-d)),d=m}}l(this,e);let c=(t<0?s:o)||s||o;return c?{tile:c,offset:c==s?r:a}:null}coordsIn(e,t,i){let s=this.resolveInline(e,t,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),t,i):Xp(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:s,offset:r}=i;if(this.dom.contains(s.dom))return s.isText()?new pt(s.dom,Math.min(s.dom.nodeValue.length,r)):s.domPosFor(r,s.flags&16?1:s.flags&32?-1:t);let o=i.tile.parent,a=!1;for(let l of o.children){if(a)return new pt(l.dom,0);l==i.tile&&(a=!0)}}return new pt(this.dom,0)}}function Xp(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=ys(e);return t[t.length-1]||null}function Bp(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.tops&&(e=s);let r=e,o=e,a=0;e==0&&t<0||e==s&&t>=0?R.chrome||R.gecko||(e?(r--,a=1):o=0)?0:l.length-1];return R.safari&&!a&&c.width==0&&(c=Array.prototype.find.call(l,h=>h.width)||c),i==null?c:$s(c,(a?a>0:t<0)==i)}static of(e,t){let i=new pi(t||document.createTextNode(e),e);return t||(i.flags|=2),i}}class Si extends Se{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return $s(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?r.length-1:0;o=r[l],!(e>0?l==0:l==r.length-1||o.top0==i)}}class Ip{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:s,index:r,beforeBreak:o,parents:a}=this;for(;e||t>0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!a.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=a.pop(),r++}else{let l=s.children[r],c=l.breakAfter;(t>0?l.length<=e:l.length=0;a--){let l=t.marks[a],c=s.lastChild;if(c instanceof Ge&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(Mr(l.dom)),s=c;else{if(this.cache.reused.get(l)){let u=Se.get(l.dom);u&&u.setDOM(Mr(l.dom))}let h=Ge.of(l.mark,l.dom);s.append(h),s=h}this.cache.reused.set(l,2)}let r=Se.get(e.text);r&&this.cache.reused.set(r,2);let o=new pi(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=hu);let s=Ii.start(e,t||((i=this.cache.find(Ii))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],a;if(t>0&&(a=s.lastChild)&&a instanceof Ge&&a.mark.eq(o))s=a,t--;else{let l=Ge.of(o,(i=this.cache.find(Ge,c=>c.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(l),s=l,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Tl(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(R.ios&&Tl(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Er,0,32)||new Si(Er.toDOM(),0,Er,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new Wp(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(Zs,void 0,1);return i&&(i.flags=t),i||new Zs(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class zp{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let a=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,a)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}}const Ms=[Si,Ii,pi,Ge,Zs,Lt,dr];for(let n=0;n[]),this.index=Ms.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let a=0;a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let a=os){let c=l-s;this.preserve(c,!o,!a),s=l,r+=c}if(!a)break;t&&a.fromA<=t.range.fromA&&a.toA>=t.range.toA?(this.forward(a.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Ge&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof Ge&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=-1,o=N.spans(this.decorations,e,t,{point:(a,l,c,h,u,f)=>{if(c instanceof Ai){if(this.disallowBlockEffectsFor[f]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=h.length,u>h.length)s.continueWidget(l-a);else{let d=c.widget||(c.block?Wi.block:Wi.inline),p=Yp(c),m=this.cache.findWidget(d,l-a,p)||Si.of(d,this.view,l-a,p);c.block?(c.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,h,u))}i=null}else i=Np(i,c);l>a&&this.text.skip(l-a)},span:(a,l,c,h)=>{for(let u=a;u-1&&(this.openWidget=o>r),this.openWidget||s.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=Se.get(s);if(s==this.view.contentDOM)break;r instanceof Ge?t.push(r):r?.isLine()?i=r:r instanceof Lt||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new Ii(s,hu):i||t.push(Ge.of(new Un({tagName:s.nodeName.toLowerCase(),attributes:xp(s)}),s)))}return{line:i,marks:t}}}function Tl(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Yp(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}const hu={class:"cm-line"};function Np(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&Oa(t,n),i&&(n.class+=" "+i)),n}function Hp(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof Ge&&e.push(i.mark)}return e}function Mr(n){let e=Se.get(n);return e&&e.setDOM(n.cloneNode()),n}class Wi extends Ut{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}Wi.inline=new Wi("span");Wi.block=new Wi("div");const Er=new class extends Ut{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class Rl{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=B.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new dr(e,e.contentDOM),this.updateInner([new ct(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:h,toA:u})=>uthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!rm(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?_p(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:h,to:u}=this.hasComposition;i=new ct(h,u,e.changes.mapPos(h,-1),e.changes.mapPos(u,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(R.ie||R.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=tm(o,this.decorations,e.changes);l.length&&(i=ct.extendWithRanges(i,l));let c=nm(a,this.blockWrappers,e.changes);return c.length&&(i=ct.extendWithRanges(i,c)),r&&!i.some(h=>h.fromA<=r.range.fromA&&h.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,a=new jp(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Se.get(t.text)&&a.cache.reused.set(Se.get(t.text),2),this.tile=a.run(e,t),Do(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=R.chrome||R.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&gn(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,h;if(l.empty?h=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(h=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),R.gecko&&l.empty&&!this.hasComposition&&Gp(c)){let f=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(f,c.node.childNodes[c.offset]||null)),c=h=new pt(f,0),a=!0}let u=this.view.observer.selectionRange;(a||!u.focusNode||(!On(c.node,c.offset,u.anchorNode,u.anchorOffset)||!On(h.node,h.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,l))&&(this.view.observer.ignore(()=>{R.android&&R.chrome&&i.contains(u.focusNode)&&sm(u.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let f=kn(this.view.root);if(f)if(l.empty){if(R.gecko){let d=Jp(c.node,c.offset);if(d&&d!=3){let p=(d==1?Wh:qh)(c.node,c.offset);p&&(c=new pt(p.node,p.offset))}}f.collapse(c.node,c.offset),l.bidiLevel!=null&&f.caretBidiLevel!==void 0&&(f.caretBidiLevel=l.bidiLevel)}else if(f.extend){f.collapse(c.node,c.offset);try{f.extend(h.node,h.offset)}catch{}}else{let d=document.createRange();l.anchor>l.head&&([c,h]=[h,c]),d.setEnd(h.node,h.offset),d.setStart(c.node,c.offset),f.removeAllRanges(),f.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(c,h)),this.impreciseAnchor=c.precise?null:new pt(u.anchorNode,u.anchorOffset),this.impreciseHead=h.precise?null:new pt(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&On(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=kn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!l||!c||l.bottom>c.top)return;let h=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(h.node,h.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=It(e)==0?0:t==0?-1:1;for(;;){let a=e.parentNode;if(a==i.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!Se.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,a=s;;o++){let l=i.children[o];if(l.dom==r)return a;a+=l.length+l.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(s,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,h)=>{if(c.isWidget()){if(c.flags&32&&h>=e)return!0;c.flags&16&&(r=!0)}else{let u=h+c.length;if(h<=e&&(i=c,s=e-h,r=u=e&&!o&&(o=c,a=e-h,l=h>e),h>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:l&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(a,t))}coordsAt(e,t,i){let{tile:s,offset:r}=this.tile.resolveBlock(e,t);return s.isWidget()?s.widget instanceof Ur?null:s.coordsInWidget(r,t,!0):s.coordsIn(r,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let a of r.children){if(a.length>=o){let l=s(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==fe.LTR,c=0,h=(u,f,d)=>{for(let p=0;ps);p++){let m=u.children[p],g=f+m.length,y=m.dom.getBoundingClientRect(),{height:b}=y;if(d&&!p&&(c+=y.top-d.top),m instanceof Lt)g>i&&h(m,f,y);else if(f>=i&&(c>0&&t.push(-c),t.push(b+c),c=0,o)){let x=m.dom.lastChild,C=x?ys(x):[];if(C.length){let k=C[C.length-1],S=l?k.right-y.left:y.right-k.left;S>a&&(a=S,this.minWidth=r,this.minWidthFrom=f,this.minWidthTo=g)}}d&&p==u.children.length-1&&(c+=d.bottom-y.bottom),f=g+m.breakAfter}};return h(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?fe.RTL:fe.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let h=ys(c.dom);if(h.length!=1)return;a+=h[0].width,l=h[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=ys(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(B.replace({widget:new Ur(a),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return B.set(e)}updateDeco(){let e=1,t=this.view.state.facet(ur).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(va).map((r,o)=>{let a=typeof r=="function";return a&&(i=!0),a?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(N.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(su))try{if(c(this.view,e.range,e))return!0}catch(h){ze(this.view.state,h,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=wa(this.view),o={left:i.left-r.left,top:i.top-r.top,right:i.right+r.right,bottom:i.bottom+r.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;if(kp(this.view.scrollDOM,o,t.head1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){Do(this.tile)}}function Do(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)Do(i,e)}}function Gp(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function uu(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=Wh(t.focusNode,t.focusOffset),s=qh(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let a=Se.get(s.node);if(!a||a.isText()&&a.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let l=Se.get(i.node);!l||l.isText()&&l.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function _p(n,e,t){let i=uu(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,a=s.nodeValue;if(/[\n\r]/.test(a)||n.state.doc.sliceString(i.from,i.to)!=a)return null;let l=e.invertedDesc;return{range:new ct(l.mapPos(r),l.mapPos(o),r,o),text:s}}function Jp(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}class Ur extends Ut{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function om(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return A.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,a=r;t<0?o=Ze(s.text,r,!1):a=Ze(s.text,r);let l=i(s.text.slice(o,a));for(;o>0;){let c=Ze(s.text,o,!1);if(i(s.text.slice(c,o))!=l)break;o=c}for(;an.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((s-t.top-(n.defaultLineHeight-a)*.5)/a);r+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Qo(o,r,n.state.tabSize)}function Lo(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==Le.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function lm(n,e,t,i){let s=Lo(n,e.head,e.assoc||-1),r=!i||s.type!=Le.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(s.from),l=n.posAtCoords({x:t==(a==fe.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(l!=null)return A.cursor(l,t?-1:1)}return A.cursor(t?s.to:s.from,t?-1:1)}function $l(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let a=e,l=null;;){let c=Up(s,r,o,a,t),h=Nh;if(!c){if(s.number==(t?n.state.doc.lines:1))return a;h=` -`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),c=n.visualLineSide(s,!t)}if(l){if(!l(h))return a}else{if(!i)return c;l=i(h)}a=c}}function cm(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==ye.Space&&(s=o),s==o}}function hm(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return A.cursor(s,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),c=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),h=n.documentTop;if(c)o==null&&(o=c.left-l.left),a=r<0?c.top:c.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(s-p.from))),a=(r<0?p.top:p.bottom)+h}let u=l.left+o,f=n.viewState.heightOracle.textHeight>>1,d=i??f;for(let p=0;;p+=f){let m=a+(d+p)*r,g=Xo(n,{x:u,y:m},!1,r);if(t?m>l.bottom:ma:b{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:A.cursor(i,in.viewState.docHeight)return new Pt(n.state.doc.length,-1);if(c=n.elementAtHeight(l),i==null)break;if(c.type==Le.Text){if(i<0?c.ton.viewport.to)break;let f=n.docView.coordsAt(i<0?c.from:c.to,i>0?-1:1);if(f&&(i<0?f.top<=l+r:f.bottom>=l+r))break}let u=n.viewState.heightOracle.textHeight/2;l=i>0?c.bottom+u:c.top-u}if(n.viewport.from>=c.to||n.viewport.to<=c.from){if(t)return null;if(c.type==Le.Text){let u=am(n,s,c,o,a);return new Pt(u,u==c.from?1:-1)}}if(c.type!=Le.Text)return l<(c.top+c.bottom)/2?new Pt(c.from,1):new Pt(c.to,-1);let h=n.docView.lineAt(c.from,2);return(!h||h.length!=c.length)&&(h=n.docView.lineAt(c.from,-2)),new um(n,o,a,n.textDirectionAt(c.from)).scanTile(h,c.from)}class um{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(o.has(m)){for(let b=1;b=r&&(x-=p),!o.has(x)){m=x;break t}}break e}o.add(m);let g=t(m),y=0;if(g)for(let b=0;b1))if(x.bottomthis.y)(!c||c.top>x.top)&&(c=x),y=-1;else{let C=x.left>this.x?this.x-x.left:x.right(p+p+m)/3)return this.y=l.bottom-1,this.scan(e,t,!0);if(c&&c.top<(p+m+m)/3)return this.y=c.top+1,this.scan(e,t,!0)}let d=(a?this.dirAt(e[h],1):this.baseDir)==fe.LTR;return{i:h,after:this.x>(f.left+f.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,a=i[r+1]-t;return Qn(e.dom,o,a).getClientRects()});return s.after?new Pt(i[s.i+1],-1):new Pt(i[s.i],1)}scanTile(e,t){if(!e.length)return new Pt(t,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,t);if(a.isComposite())return this.scanTile(a,t)}let i=[t];for(let a=0,l=t;a{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:Qn(l.dom,0,l.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Pt(i[s.i+1],-1):new Pt(o,1)}}const ki="￿";class fm{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(_.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=ki}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=Se.get(s),a=s.nextSibling;if(a==t){o?.breakAfter&&!a&&i!=this.view.contentDOM&&this.lineBreak();break}let l=Se.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:Rs(s))||Rs(a)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!pm(a,t)&&this.lineBreak(),s=a}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,a;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(a=s.exec(t))&&(r=a.index,o=a[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);i=r+o}}readNode(e){let t=Se.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(dm(e,i.node,i.offset)?t:0))}}function dm(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=du(e.docView.tile,t,i,0))){let l=r||o?[]:Om(e),c=new fm(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=ym(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!Zo(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),h=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Zo(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),u=e.viewport;if((R.ios||R.chrome)&&c!=h&&Math.min(c,h)<=a.main.from&&Math.max(c,h)>=a.main.to&&(u.from>0||u.to-1&&a.ranges.length>1)this.newSel=a.replaceRange(A.range(h,c));else if(e.lineWrapping&&h==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let f=e.coordsAtPos(c,-1),d=0;f&&(d=e.inputState.lastTouchY<=f.bottom?-1:1),this.newSel=A.create([A.cursor(c,d)])}else this.newSel=A.single(h,c)}}}function du(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,a=-1;for(let l=0,c=i,h=i;lt)return du(u,e,t,c);if(f>=e&&s==-1&&(s=l,r=c),c>t&&u.dom.parentNode==n.dom){o=l,a=h;break}h=f,c=f+u.breakAfter}return{from:r,to:a<0?i+n.length:a,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function pu(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=r.from,h=null;(o===8||R.android&&e.text.length=a&&r.to<=l&&(e.typeOver||u!=e.text)&&u.slice(0,r.from-a)==e.text.slice(0,r.from-a)&&u.slice(r.to-a)==e.text.slice(f=e.text.length-(u.length-(r.to-a)))?t={from:r.from,to:r.to,insert:se.of(e.text.slice(r.from-a,f).split(ki))}:(d=mu(u,e.text,c-a,h))&&(R.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==ki+ki&&d.toB--,t={from:a+d.from,to:a+d.toA,insert:se.of(e.text.slice(d.from,d.toB).split(ki))})}else i&&(!n.hasFocus&&s.facet(Dt)||Es(i,r))&&(i=null);if(!t&&!i)return!1;if((R.mac||R.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:se.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:R.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` - `&&n.lineWrapping&&(i&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:se.of([" "])}),t)return ka(n,t,i,o);if(i&&!Es(i,r)){let a=!1,l="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(a=!0),l=n.inputState.lastSelectionOrigin,l=="select.pointer"&&(i=fu(s.facet(Dn).map(c=>c(n)),i))),n.dispatch({selection:i,scrollIntoView:a,userEvent:l}),!0}else return!1}function ka(n,e,t,i=-1){if(R.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if(R.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Ei(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&Ei(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&Ei(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,a=()=>o||(o=gm(n,e,t));return n.state.facet(eu).some(l=>l(n,e.from,e.to,r,a))||n.dispatch(a()),!0}function gm(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let l=e.fromu(n)),c,l);e.from==h&&(o=h)}if(o>-1)i={changes:e,selection:A.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let l=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(l+e.insert.sliceString(0,void 0,n.state.lineBreak)+c))}else{let l=s.changes(e),c=t&&t.main.to<=l.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let h=n.state.sliceDoc(e.from,e.to),u,f=t&&uu(n,t.main.head);if(f){let p=e.insert.length-(e.to-e.from);u={from:f.from,to:f.to-p}}else u=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:l,range:c||p.map(l)};let m=p.to-d,g=m-h.length;if(n.state.sliceDoc(g,m)!=h||m>=u.from&&g<=u.to)return{range:p};let y=s.changes({from:g,to:m,insert:e.insert}),b=p.to-r.to;return{changes:y,range:c?A.range(Math.max(0,c.anchor+b),Math.max(0,c.head+b)):p.map(y)}})}else i={changes:l,selection:c&&s.selection.replaceRange(c)}}let a="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:a,scrollIntoView:!0})}function mu(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(i=="end"){let l=Math.max(0,r-Math.min(o,a));t-=o+l-r}if(o=o?r-t:0;r-=l,a=r+(a-o),o=r}else if(a=a?r-t:0;r-=l,o=r+(o-a),a=r}return{from:r,toA:o,toB:a}}function Om(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new Kl(t,i)),(s!=t||r!=i)&&e.push(new Kl(s,r))),e}function ym(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?A.single(t+e,i+e):null}function Es(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}class Am{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,R.safari&&e.contentDOM.addEventListener("input",()=>null),R.gecko&&Em(e.contentDOM.ownerDocument)}handleEvent(e){!Cm(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Sm(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,a=i[r];a&&o!=!a.handlers.length&&(s.removeEventListener(r,this.handleEvent),a=null),a||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Ou.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),R.android&&R.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if(R.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(gu.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||xm.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&R.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&bm(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from0?!0:R.safari&&!R.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function bm(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Zl(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ze(t.state,s)}}}function Sm(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let a in r){let l=r[a];l&&t(a).handlers.push(Zl(i.value,l))}if(o)for(let a in o){let l=o[a];l&&t(a).observers.push(Zl(i.value,l))}}for(let i in Ot)t(i).handlers.push(Ot[i]);for(let i in je)t(i).observers.push(je[i]);return e}const gu=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],xm="dthko",Ou=[16,17,18,20,91,92,224,225],Hn=6;function Gn(n){return Math.max(0,n)*.7+8}function vm(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class wm{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Dh(e.contentDOM),this.atoms=e.state.facet(Dn).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(_.allowMultipleSelections)&&km(e,t),this.dragging=Pm(e,t)&&bu(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&vm(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=wa(this.view);e.clientX-l.left<=s+Hn?t=-Gn(s-e.clientX):e.clientX+l.right>=o-Hn&&(t=Gn(e.clientX-o)),e.clientY-l.top<=r+Hn?i=-Gn(r-e.clientY):e.clientY+l.bottom>=a-Hn&&(i=Gn(e.clientY-a)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=fu(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function km(n,e){let t=n.state.facet(Hh);return t.length?t[0](e):R.mac?e.metaKey:e.ctrlKey}function Qm(n,e){let t=n.state.facet(Gh);return t.length?t[0](e):R.mac?!e.altKey:!e.ctrlKey}function Pm(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=kn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Cm(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=Se.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}const Ot=Object.create(null),je=Object.create(null),yu=R.ie&&R.ie_version<15||R.ios&&R.webkit_version<604;function Tm(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),Au(n,t.value)},50)}function pr(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function Au(n,e){e=pr(n.state,ba,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(Bo!=null&&t.selection.ranges.every(l=>l.empty)&&Bo==r.toString()){let l=-1;i=t.changeByRange(c=>{let h=t.doc.lineAt(c.from);if(h.from==l)return{range:c};l=h.from;let u=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:u},range:A.cursor(c.from+u.length)}})}else o?i=t.changeByRange(l=>{let c=r.line(s++);return{changes:{from:l.from,to:l.to,insert:c.text},range:A.cursor(l.from+c.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}je.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,R.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};je.wheel=je.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ot.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);je.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};je.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};je.touchend=(n,e)=>{n.inputState.touchActive=!1};Ot.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(_h))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=$m(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new wm(n,e,t,i)),i&&n.observer.ignore(()=>{Bh(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Ml(n,e,t,i){if(i==1)return A.cursor(e,t);if(i==2)return om(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,a=s?s.posAtEnd:r.to;return aDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Ul+1)%3:1}function $m(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=bu(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,a){let l=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),c,h=Ml(n,l.pos,l.assoc,i);if(t.pos!=l.pos&&!o){let u=Ml(n,t.pos,t.assoc,i),f=Math.min(u.from,h.from),d=Math.max(u.to,h.to);h=f1&&(c=Km(s,l.pos))?c:a?s.addRange(h):A.create([h])}}}function Km(n,e){for(let t=0;t=e)return A.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ot.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=A.undirectionalRange(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",pr(n.state,Sa,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ot.dragend=n=>(n.inputState.draggedContent=null,!1);function Dl(n,e,t,i){if(t=pr(n.state,ba,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&Qm(n,e)?{from:r.from,to:r.to}:null,a={from:s,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ot.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Dl(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(i[o]=a.result),r()},a.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Dl(n,e,i,!0),!0}return!1};Ot.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=yu?null:e.clipboardData;return t?(Au(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Tm(n),!1)};function Zm(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Mm(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:pr(n,Sa,e.join(n.lineBreak)),ranges:t,linewise:i}}let Bo=null;Ot.copy=Ot.cut=(n,e)=>{if(!gn(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=Mm(n.state);if(!t&&!s)return!1;Bo=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=yu?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(Zm(n,t),!1)};const Su=qt.define();function xu(n,e){let t=[];for(let i of n.facet(tu)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:Su.of(!0)}):null}function vu(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=xu(n.state,e);t?n.dispatch(t):n.update([])}},10)}je.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),vu(n)};je.blur=n=>{n.observer.clearSelectionRange(),vu(n)};je.compositionstart=je.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};je.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,R.chrome&&R.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};je.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ot.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let a=o[0],l=n.posAtDOM(a.startContainer,a.startOffset),c=n.posAtDOM(a.endContainer,a.endOffset);return ka(n,{from:l,to:c,insert:n.state.toText(r)},null),!0}}let s;if(R.chrome&&R.android&&(s=gu.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return R.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),R.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>je.compositionend(n,e),20),!1};const Ll=new Set;function Em(n){Ll.has(n)||(Ll.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const Xl=["pre-wrap","normal","pre-line","break-spaces"];let qi=!1;function Bl(){qi=!1}class Um{constructor(e){this.lineWrapping=e,this.doc=se.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Xl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,l=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,l){this.heightSamples={};for(let c=0;c0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>As&&(qi=!0),this.height=e)}replace(e,t,i){return Ve.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let a=s.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:h,toB:u}=s[a],f=r.lineAt(l,pe.ByPosNoHeight,i.setDoc(t),0,0),d=f.to>=c?f:r.lineAt(c,pe.ByPosNoHeight,i,0,0);for(u+=d.to-c,c=d.to;a>0&&f.from<=s[a-1].toA;)l=s[a-1].fromA,h=s[a-1].fromB,a--,lr*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),i+=1+a.break,s-=a.size}else if(r>s*2){let a=e[i];a.break?e.splice(i,1,a.left,null,a.right):e.splice(i,1,a.left,a.right),i+=2+a.break,r-=a.size}else break;else if(s=r&&o(this.lineAt(0,pe.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}}class ot extends wu{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new dt(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof ot||s instanceof Ee&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof Ee?s=new ot(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Ve.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class Ee extends Ve{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*r);o=l/r,this.length>r+1&&(a=(this.height-l)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:a}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,s);if(t.lineWrapping){let c=s+(e0){let r=i[i.length-1];r instanceof Ee?i[i.length-1]=new Ee(r.length+s):i.push(null,new Ee(s-1))}if(e>0){let r=i[0];r instanceof Ee?i[0]=new Ee(e+r.length):i.unshift(new Ee(e-1),null)}return Ve.of(i)}decomposeLeft(e,t){t.push(new Ee(e-1),null)}decomposeRight(e,t){t.push(null,new Ee(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],a=Math.max(t,s.from),l=-1;for(s.from>t&&o.push(new Ee(s.from-t-1).updateHeight(e,t));a<=r&&s.more;){let h=e.doc.lineAt(a).length;o.length&&o.push(null);let u=s.heights[s.index++],f=0;u<0&&(f=-u,u=s.heights[s.index++]),l==-1?l=u:Math.abs(u-l)>=As&&(l=-2);let d=new ot(h,u,f);d.outdated=!1,o.push(d),a+=h+1}a<=r&&o.push(null,new Ee(r-a).updateHeight(e,a));let c=Ve.of(o);return(l<0||Math.abs(c.height-this.height)>=As||Math.abs(l-this.heightMetrics(e,t).perLine)>=As)&&(qi=!0),Us(this,c)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class Lm extends Ve{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return ea))return c;let h=t==pe.ByPosNoHeight?pe.ByPosNoHeight:pe.ByPos;return l?c.join(this.right.lineAt(a,h,i,o,a)):this.left.lineAt(a,h,i,s,r).join(c)}forEachLine(e,t,i,s,r,o){let a=s+this.left.height,l=r+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,t,i,a,l,o);else{let c=this.lineAt(l,pe.ByPos,i,s,r);e=e&&c.from<=t&&o(c),t>c.to&&this.right.forEachLine(c.to+1,t,i,a,l,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let a of i)r.push(a);if(e>0&&Il(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?Ve.of(this.break?[e,null,t]:[e,t]):(this.left=Us(this.left,e),this.right=Us(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,a=t+r.length+this.break,l=null;return s&&s.from<=t+r.length&&s.more?l=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=a+o.length&&s.more?l=o=o.updateHeight(e,a,i,s):o.updateHeight(e,a,i),l?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function Il(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof Ee&&(i=n[e+1])instanceof Ee&&n.splice(e-1,3,new Ee(t.length+1+i.length))}const Xm=5;class Qa{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof ot?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new ot(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=Xm)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new ot(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new Ee(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ot)return e;let t=new ot(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ot)&&!this.isCovered?this.nodes.push(new ot(0,-1,0)):(this.writtenToh.clientHeight||h.scrollWidth>h.clientWidth)&&u.overflow!="visible"){let f=h.getBoundingClientRect();r=Math.max(r,f.left),o=Math.min(o,f.right),a=Math.max(a,f.top),l=Math.min(c==n.parentNode?s.innerHeight:l,f.bottom)}c=u.position=="absolute"||u.position=="fixed"?h.offsetParent:h.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function qm(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function zm(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class Dr{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new Um(i),this.stateDeco=zl(t),this.heightMap=Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle.setDoc(t.doc),[new ct(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=B.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new _n(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?ql:new Pa(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(un(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=zl(this.state);let s=e.changedRanges,r=ct.extendWithRanges(s,Bm(i,this.stateDeco,e?e.changes:Re.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);Bl(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||qi)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(nu)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?fe.RTL:fe.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,h=0;if(a.width&&a.height){let{scaleX:k,scaleY:S}=Fh(t,a);(k>.005&&Math.abs(this.scaleX-k)>.005||S>.005&&Math.abs(this.scaleY-S)>.005)&&(this.scaleX=k,this.scaleY=S,c|=16,o=l=!0)}let u=(parseInt(i.paddingTop)||0)*this.scaleY,f=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=f)&&(this.paddingTop=u,this.paddingBottom=f,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let d=Dh(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=Ih(this.scrollParent||e.win);let m=(this.printing?zm:Wm)(t,this.paddingTop),g=m.top-this.pixelViewport.top,y=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let b=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(b!=this.inView&&(this.inView=b,b&&(l=!0)),!this.inView&&!this.scrollTarget&&!qm(e.dom))return 0;let x=a.width;if((this.contentDOMWidth!=x||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let k=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(k)&&(o=!0),o||s.lineWrapping&&Math.abs(x-this.contentDOMWidth)>s.charWidth){let{lineHeight:S,charWidth:w,textHeight:U}=e.docView.measureTextSize();o=S>0&&s.refresh(r,S,w,U,Math.max(5,x/w),k),o&&(e.docView.minWidth=0,c|=16)}g>0&&y>0?h=Math.max(g,y):g<0&&y<0&&(h=Math.min(g,y)),Bl();for(let S of this.viewports){let w=S.from==this.viewport.from?k:e.docView.measureVisibleLineHeights(S);this.heightMap=(o?Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle,[new ct(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Fm(S.from,w))}qi&&(c|=2)}let C=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return C&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(h,this.scrollTarget),c|=this.updateForViewport()),(c&2||C)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new _n(s.lineAt(o-i*1e3,pe.ByHeight,r,0,0).from,s.lineAt(a+(1-i)*1e3,pe.ByHeight,r,0,0).to);if(t){let{head:c}=t.range;if(cl.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=s.lineAt(c,pe.ByPos,r,0,0),f;t.y=="center"?f=(u.top+u.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&c=a+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=fe.LTR&&!i)return[];let a=[],l=(h,u,f,d)=>{if(u-hh&&yy.from>=f.from&&y.to<=f.to&&Math.abs(y.from-h)y.fromb));if(!g){if(ux.from<=u&&x.to>=u)){let x=t.moveToLineBoundary(A.cursor(u),!1,!0).head;x>h&&(u=x)}let y=this.gapSize(f,h,u,d),b=i||y<2e6?y:2e6;g=new Dr(h,u,y,b)}a.push(g)},c=h=>{if(h.length2e6)for(let S of e)S.from>=h.from&&S.fromh.from&&l(h.from,d,h,u),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];N.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||un(this.heightMap.lineAt(e,pe.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||un(this.heightMap.lineAt(this.scaler.fromDOM(e),pe.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return un(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class _n{constructor(e,t){this.from=e,this.to=t}}function jm(n,e,t){let i=[],s=n,r=0;return N.spans(t,n,e,{span(){},point(o,a){o>s&&(i.push({from:s,to:o}),r+=o-s),s=a}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],a=o-r;if(i<=a)return r+i;i-=a}}function es(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Ym(n,e){for(let t of n)if(e(t))return t}const ql={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function zl(n){let e=n.facet(ur).filter(i=>typeof i!="function"),t=n.facet(va).filter(i=>typeof i!="function");return t.length&&e.push(N.join(t)),e}class Pa{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:a,to:l})=>{let c=t.lineAt(a,pe.ByPos,e,0,0).top,h=t.lineAt(l,pe.ByPos,e,0,0).bottom;return s+=h-c,{from:a,to:l,top:c,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let a of this.viewports)a.domTop=o+(a.top-r)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),r=a.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}}function un(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new dt(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>un(s,e)):n._content)}const ts=K.define({combine:n=>n.join(" ")}),Io=K.define({combine:n=>n.indexOf(!0)>-1}),Wo=ei.newName(),ku=ei.newName(),Qu=ei.newName(),Pu={"&light":"."+ku,"&dark":"."+Qu};function qo(n,e,t){return new ei(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}const Nm=qo("."+Wo,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},Pu),Hm={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Lr=R.ie&&R.ie_version<=11;class Gm{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new Qp,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(R.ie&&R.ie_version<=11||R.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&R.android&&e.constructor.EDIT_CONTEXT!==!1&&!(R.chrome&&R.chrome_version<126)&&(this.editContext=new Jm(e),e.state.facet(Dt)&&(e.contentDOM.editContext=this.editContext.editContext)),Lr&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(Dt)?i.root.activeElement!=this.dom:!gn(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(R.ie&&R.ie_version<=11||R.android&&R.chrome)&&!i.state.selection.main.empty&&s.focusNode&&On(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=kn(e.root);if(!t)return!1;let i=R.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&_m(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=gn(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&Ei(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&gn(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new mm(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=pu(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Es(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Vl(t,e.previousSibling||e.target.previousSibling,-1),s=Vl(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Dt)!=e.state.facet(Dt)&&(e.view.contentDOM.editContext=e.state.facet(Dt)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function Vl(n,e,t){for(;e;){let i=Se.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function jl(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return On(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function _m(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return jl(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?jl(n,t):null}class Jm{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,a=this.toEditorPos(i.updateRangeStart),l=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>i.text.length;a==this.from&&rthis.to&&(l=r);let h=mu(e.state.sliceDoc(a,l),i.text,(c?s.from:s.to)-a,c?"end":null);if(!h){let f=A.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Es(f,s)||e.dispatch({selection:f,userEvent:"select"});return}let u={from:h.from+a,to:h.toA+a,insert:se.of(i.text.slice(h.from,h.toB).split(` -`))};if((R.mac||R.android)&&u.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(u={from:a,to:l,insert:se.of([i.text.replace("."," ")])}),this.pendingContextChange=u,!e.state.readOnly){let f=this.to-this.from+(u.to-u.from+u.insert.length);ka(e,u,A.single(this.toEditorPos(i.selectionStart,f),this.toEditorPos(i.selectionEnd,f)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),a=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,a=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(r.rangeStart),c=this.toEditorPos(r.rangeEnd);if(l{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let s=kn(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,a,l,c)=>{if(i)return;let h=c.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(c)){s=this.pendingContextChange=null,t+=h,this.to+=h;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=h,this.to+=h;else if(rthis.to||this.to-this.from+c.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),c.toString()),this.to+=h}t+=h}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class ${get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Pp(e.parent)||document,this.viewState=new Wl(this,e.state||_.create(e)),e.scrollTo&&e.scrollTo.is(Nn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ti).map(s=>new Zr(s));for(let s of this.plugins)s.update(this);this.observer=new Gm(this),this.inputState=new Am(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Rl(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof Pe?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let f of e){if(f.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=f.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,a=0,l=null;e.some(f=>f.annotation(Su))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=xu(r,o),l||(a=1));let c=this.observer.delayedAndroidKey,h=null;if(c?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(h=null)):this.observer.clear(),r.facet(_.phrases)!=this.state.facet(_.phrases))return this.setState(r);s=Ks.create(this,r,e),s.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(u&&(u=u.map(f.changes)),f.scrollIntoView){let{main:d}=f.state.selection,{x:p,y:m}=this.state.facet($.cursorScrollMargin);u=new Ui(d.empty?d:A.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of f.effects)d.is(Nn)&&(u=d.value.clip(this.state))}this.viewState.update(s,u),this.bidiCache=Fs.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(hn)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(ts)!=s.state.facet(ts)&&(this.viewState.mustMeasureContent=!0),(t||i||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let f of this.state.facet(Fo))try{f(s)}catch(d){ze(this.state,d,"update listener")}(l||h)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),h&&!pu(this,h)&&c.force&&Ei(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Wl(this,e),this.plugins=e.facet(Ti).map(i=>new Zr(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new Rl(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ti),i=e.state.facet(Ti);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Zr(r));else{let a=this.plugins[o];a.mustUpdate=e,s.push(a)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(Ih(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let h=c.map(d=>{try{return d.read(this)}catch(p){return ze(this.state,p),Yl}}),u=Ks.create(this,this.state,[]),f=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),f=this.docView.update(u),f&&this.docViewUpdate());for(let d=0;d1||p<-1)&&!(R.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Fo))a(t)}get themeClasses(){return Wo+" "+(this.state.facet(Io)?Qu:ku)+" "+this.state.facet(ts)}updateAttrs(){let e=Nl(this,ou,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Dt)?"true":"false",class:"cm-content",style:`${R.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),Nl(this,xa,t);let i=this.observer.ignore(()=>{let s=wl(this.contentDOM,this.contentAttrs,t),r=wl(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is($.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(hn);let e=this.state.facet($.cspNonce);ei.mount(this.root,this.styleModules.concat(Nm).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Fr(this,e,$l(this,e,t,i))}moveByGroup(e,t){return Fr(this,e,$l(this,e,t,i=>cm(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return A.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return lm(this,e,t,i)}moveVertically(e,t,i){return Fr(this,e,hm(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=Xo(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),Xo(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),r=s[Ct.find(s,e-i.from,-1,t)];return this.docView.coordsAt(e,t,r.dir==fe.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(iu)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>eg)return Yh(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||jh(r.isolates,i=Pl(this,e))))return r.order;i||(i=Pl(this,e));let s=Ep(e.text,t,i);return this.bidiCache.push(new Fs(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||R.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Bh(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return Nn.of(new Ui(typeof e=="number"?A.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Nn.of(new Ui(A.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return xe.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return xe.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=ei.newName(),s=[ts.of(i),hn.of(qo(`.${i}`,e))];return t&&t.dark&&s.push(Io.of(!0)),s}static baseTheme(e){return ri.lowest(hn.of(qo("."+Wo,e,Pu)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&Se.get(i)||Se.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}}$.styleModule=hn;$.inputHandler=eu;$.clipboardInputFilter=ba;$.clipboardOutputFilter=Sa;$.scrollHandler=su;$.focusChangeEffect=tu;$.perLineTextDirection=iu;$.exceptionSink=Jh;$.updateListener=Fo;$.editable=Dt;$.mouseSelectionStyle=_h;$.dragMovesSelection=Gh;$.clickAddsSelectionRange=Hh;$.decorations=ur;$.blockWrappers=au;$.outerDecorations=va;$.atomicRanges=Dn;$.bidiIsolatedRanges=lu;$.cursorScrollMargin=K.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});$.scrollMargins=cu;$.darkTheme=Io;$.cspNonce=K.define({combine:n=>n.length?n[0]:""});$.contentAttributes=xa;$.editorAttributes=ou;$.lineWrapping=$.contentAttributes.of({class:"cm-lineWrapping"});$.announce=z.define();const eg=4096,Yl={};class Fs{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:fe.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&Oa(o,t)}return t}const tg=R.mac?"mac":R.windows?"win":R.linux?"linux":"key";function ig(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,a;for(let l=0;li.concat(s),[]))),t}function sg(n,e,t){return Tu(Cu(n.state),e,n,t)}let Nt=null;const rg=4e3;function og(n,e=tg){let t=Object.create(null),i=Object.create(null),s=(o,a)=>{let l=i[o];if(l==null)i[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,a,l,c,h)=>{var u,f;let d=t[o]||(t[o]=Object.create(null)),p=a.split(/ (?!$)/).map(y=>ig(y,e));for(let y=1;y{let C=Nt={view:x,prefix:b,scope:o};return setTimeout(()=>{Nt==C&&(Nt=null)},rg),!0}]})}let m=p.join(" ");s(m,!1);let g=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((f=(u=d._any)===null||u===void 0?void 0:u.run)===null||f===void 0?void 0:f.slice())||[]});l&&g.run.push(l),c&&(g.preventDefault=!0),h&&(g.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let h=t[c]||(t[c]=Object.create(null));h._any||(h._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:u}=o;for(let f in h)h[f].run.push(d=>u(d,zo))}let l=o[e]||o.key;if(l)for(let c of a)r(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}let zo=null;function Tu(n,e,t,i){zo=e;let s=bp(e),r=Ne(s,0),o=Qt(r)==s.length&&s!=" ",a="",l=!1,c=!1,h=!1;Nt&&Nt.view==t&&Nt.scope==i&&(a=Nt.prefix+" ",Ou.indexOf(e.keyCode)<0&&(c=!0,Nt=null));let u=new Set,f=g=>{if(g){for(let y of g.run)if(!u.has(y)&&(u.add(y),y(t)))return g.stopPropagation&&(h=!0),!0;g.preventDefault&&(g.stopPropagation&&(h=!0),c=!0)}return!1},d=n[i],p,m;return d&&(f(d[a+is(s,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(R.windows&&e.ctrlKey&&e.altKey)&&!(R.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=ti[e.keyCode])&&p!=s?(f(d[a+is(p,e,!0)])||e.shiftKey&&(m=vn[e.keyCode])!=s&&m!=p&&f(d[a+is(m,e,!1)]))&&(l=!0):o&&e.shiftKey&&f(d[a+is(s,e,!0)])&&(l=!0),!l&&f(d._any)&&(l=!0)),c&&(l=!0),l&&h&&e.stopPropagation(),zo=null,l}class gi{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=Ru(e);return[new gi(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return ag(e,t,i)}}function Ru(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==fe.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function Gl(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,a=n.posAtCoords({x:r.left+1,y:o}),l=n.posAtCoords({x:r.right-1,y:o});return a==null||l==null?i:{from:Math.max(i.from,Math.min(a,l)),to:Math.min(i.to,Math.max(a,l))}}function ag(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==fe.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=Ru(n),c=o.querySelector(".cm-line"),h=c&&window.getComputedStyle(c),u=a.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),f=a.right-(h?parseInt(h.paddingRight):0),d=Lo(n,i,1),p=Lo(n,s,-1),m=d.type==Le.Text?d:null,g=p.type==Le.Text?p:null;if(m&&(n.lineWrapping||d.widgetLineBreaks)&&(m=Gl(n,i,1,m)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=Gl(n,s,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return b(x(t.from,t.to,m));{let k=m?x(t.from,null,m):C(d,!1),S=g?x(null,t.to,g):C(p,!0),w=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&k.bottom+n.defaultLineHeight/2M&&Q.from=P)break;ee>D&&E(Math.max(J,D),k==null&&J<=M,Math.min(ee,P),S==null&&ee>=Y,ae.dir)}if(D=j.to+1,D>=P)break}return V.length==0&&E(M,k==null,Y,S==null,n.textDirection),{top:U,bottom:F,horizontal:V}}function C(k,S){let w=a.top+(S?k.top:k.bottom);return{top:w,bottom:w,horizontal:[]}}}function lg(n,e){return n.constructor==e.constructor&&n.eq(e)}class cg{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(bs)!=e.state.facet(bs)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(bs);for(;t!lg(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,R.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const bs=K.define();function $u(n){return[xe.define(e=>new cg(e,n)),bs.of(n)]}const zi=K.define({combine(n){return yt(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function hg(n={}){return[zi.of(n),ug,fg,pg,nu.of(!0)]}function Ku(n){return n.startState.facet(zi)!=n.state.facet(zi)}const ug=$u({above:!0,markers(n){let{state:e}=n,t=e.facet(zi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&R.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=s.empty?s:A.cursor(s.head,s.assoc);for(let l of gi.forRange(n,o,a))i.push(l)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Ku(n);return t&&_l(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){_l(e.state,n)},class:"cm-cursorLayer"});function _l(n,e){e.style.animationDuration=n.facet(zi).cursorBlinkRate+"ms"}const fg=$u({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of gi.forRange(n,"cm-selectionBackground",s))e.push(r);if(R.ios&&!t.empty&&n.state.facet(zi).iosSelectionHandles){for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-start",A.cursor(t.from,1)))e.push(s);for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-end",A.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Ku(n)},class:"cm-selectionLayer"}),dg=R.gecko&&R.gecko_version==153?"#ffffff01":"transparent",pg=ri.highest($.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${dg} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Zu=z.define({map(n,e){return n==null?null:e.mapPos(n)}}),fn=Te.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(Zu)?i.value:t,n)}}),mg=xe.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(fn);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(fn)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(fn),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(fn)!=n&&this.view.dispatch({effects:Zu.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function gg(){return[fn,mg]}function Jl(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,a;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;a=e.exec(r.value);)s(o+a.index,a)}function Og(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}class yg{constructor(e){const{regexp:t,decoration:i,decorate:s,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,s)this.addMatch=(a,l,c,h)=>s(h,c,c+a[0].length,a,l);else if(typeof i=="function")this.addMatch=(a,l,c,h)=>{let u=i(a,l,c);u&&h(c,c+a[0].length,u)};else if(i)this.addMatch=(a,l,c,h)=>h(c,c+a[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new Bt,i=t.add.bind(t);for(let{from:s,to:r}of Og(e,this.maxLength))Jl(e.state.doc,this.regexp,s,r,(o,a)=>this.addMatch(a,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,a,l)=>{l>=e.view.viewport.from&&a<=e.view.viewport.to&&(i=Math.min(a,i),s=Math.max(l,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),a=Math.min(r.to,s);if(a>=o){let l=e.state.doc.lineAt(o),c=l.tol.from;o--)if(this.boundary.test(l.text[o-1-l.from])){h=o;break}for(;af.push(y.range(m,g));if(l==c)for(this.regexp.lastIndex=h-l.from;(d=this.regexp.exec(l.text))&&d.indexthis.addMatch(g,e,m,p));t=t.update({filterFrom:h,filterTo:u,filter:(m,g)=>mu,add:f})}}return t}}const Vo=/x/.unicode!=null?"gu":"g",Ag=new RegExp(`[\0-\b ---Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,Vo),bg={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Xr=null;function Sg(){var n;if(Xr==null&&typeof document<"u"&&document.body){let e=document.body.style;Xr=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Xr||!1}const Ss=K.define({combine(n){let e=yt(n,{render:null,specialChars:Ag,addSpecialChars:null});return(e.replaceTabs=!Sg())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Vo)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Vo)),e}});function xg(n={}){return[Ss.of(n),vg()]}let ec=null;function vg(){return ec||(ec=xe.fromClass(class{constructor(n){this.view=n,this.decorations=B.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(Ss)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new yg({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=Ne(e[0],0);if(r==9){let o=s.lineAt(i),a=t.state.tabSize,l=_i(o.text,a,i-o.from);return B.replace({widget:new Pg((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=B.replace({widget:new Qg(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(Ss);n.startState.facet(Ss)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const wg="•";function kg(n){return n>=32?wg:n==10?"␤":String.fromCharCode(9216+n)}class Qg extends Ut{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=kg(this.code),i=e.state.phrase("Control character")+" "+(bg[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}}class Pg extends Ut{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Cg(){return Rg}const Tg=B.line({class:"cm-activeLine"}),Rg=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(Tg.range(s.from)),e=s.from)}return B.set(t)}},{decorations:n=>n.decorations}),jo=2e3;function $g(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>jo||t.off>jo||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=i;l<=s;l++){let c=n.doc.line(l);c.length<=a&&r.push(A.range(c.from+o,c.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=i;l<=s;l++){let c=n.doc.line(l),h=Qo(c.text,o,n.tabSize,!0);if(h<0)r.push(A.cursor(c.to));else{let u=Qo(c.text,a,n.tabSize);r.push(A.range(c.from+h,c.from+u))}}}return r}function Kg(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function tc(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>jo?-1:s==i.length?Kg(n,e.clientX):_i(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function Zg(n,e){let t=tc(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let a=tc(n,s);if(!a)return i;let l=$g(n.state,t,a);return l.length?o?A.create(l.concat(i.ranges)):A.create(l):i}}:null}function Mg(n){let e=(t=>t.altKey&&t.button==0);return $.mouseSelectionStyle.of((t,i)=>e(i)?Zg(t,i):null)}const Eg={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},Ug={style:"cursor: crosshair"};function Fg(n={}){let[e,t]=Eg[n.key||"Alt"],i=xe.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,$.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?Ug:null})]}const ns="-10000px";class Mu{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(l=>l);if(s===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;lt[c]=l),t.length=a.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}}function Dg(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const Br=K.define({combine:n=>{var e,t,i;return{position:R.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||Dg}}}),ic=new WeakMap,Ca=xe.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Br);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new Mu(n,gr,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Br);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=ns,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(R.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=wa(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let a=this.manager.tooltipViews[o];return a.getCoords?a.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Br).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let a=0;a=Math.min(t.bottom,i.bottom)||u.rightMath.min(t.right,i.right)+.1)){h.style.top=ns;continue}let d=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=f.right-f.left,g=(e=ic.get(c))!==null&&e!==void 0?e:f.bottom-f.top,y=c.offset||Xg,b=this.view.textDirection==fe.LTR,x=f.width>i.right-i.left?b?i.left:i.right-f.width:b?Math.max(i.left,Math.min(u.left-(d?14:0)+y.x,i.right-m)):Math.min(Math.max(i.left,u.left-m+(d?14:0)-y.x),i.right-m),C=this.above[a];!l.strictSide&&(C?u.top-g-p-y.yi.bottom)&&C==i.bottom-u.bottom>u.top-i.top&&(C=this.above[a]=!C);let k=(C?u.top-i.top:i.bottom-u.bottom)-p;if(kx&&U.topS&&(S=C?U.top-g-2-p:U.bottom+p+2);if(this.position=="absolute"?(h.style.top=(S-n.parent.top)/r+"px",nc(h,(x-n.parent.left)/s)):(h.style.top=S/r+"px",nc(h,x/s)),d){let U=u.left+(b?y.x:-y.x)-(x+14-7);d.style.left=U/s+"px"}c.overlap!==!0&&o.push({left:x,top:S,right:w,bottom:S+g}),h.classList.toggle("cm-tooltip-above",C),h.classList.toggle("cm-tooltip-below",!C),c.positioned&&c.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=ns}},{eventObservers:{scroll(){this.maybeMeasure()}}});function nc(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}const Lg=$.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Xg={x:0,y:0},gr=K.define({enables:[Ca,Lg]}),Ds=K.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])});class Or{static create(e){return new Or(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Mu(e,Ds,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Bg=gr.compute([Ds],n=>{let e=n.facet(Ds);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:Or.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),Ig=K.define();class Wg{constructor(e,t,i,s,r,o){this.view=e,this.source=t,this.field=i,this.locked=s,this.setHover=r,this.hoverTime=o,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;eo.bottom||t.xo.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(s)).find(c=>c.from<=s&&c.to>=s),l=a&&a.dir==fe.RTL?-1:1;r=t.x{if(a&&!(Array.isArray(a)&&!a.length)){let l=Array.isArray(a)?a:[a];s&&this.locked.set(l,s),e.dispatch({effects:this.setHover.of(l)})}};if(r&&"then"in r){let a=this.pending={pos:t};r.then(l=>{this.pending==a&&(this.pending=null,o(l))},l=>ze(e.state,l,"hover tooltip"))}else o(r)}get tooltip(){let e=this.view.plugin(Ca),t=e?e.manager.tooltips.findIndex(i=>i.create==Or.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:s,tooltip:r}=this;if(s.length&&!this.locked.has(s)&&r&&!qg(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,a=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==a?this.view.posAtCoords(this.lastMove)!=o:!zg(this.view,o,a,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t);let{active:s}=this;s.length&&!this.locked.has(s)&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const ss=4;function qg(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let a=o.getBoundingClientRect();s=Math.min(a.top,s),r=Math.max(a.bottom,r)}return e.clientX>=t-ss&&e.clientX<=i+ss&&e.clientY>=s-ss&&e.clientY<=r+ss}function zg(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),a=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rights||Math.min(o.bottom,a)=e&&l<=t}function Eu(n,e={}){let t=z.define(),i=new WeakMap,s=Te.define({create(){return[]},update(o,a){let l=i.get(o);if(o.length&&(e.hideOnChange&&(a.docChanged||a.selection)?o=[]:l&&l(a)?o=[]:e.hideOn&&(o=o.filter(c=>!e.hideOn(a,c)))),a.docChanged&&o.length){let c=[];for(let h of o){let u=a.changes.mapPos(h.pos,-1,De.TrackDel);if(u!=null){let f=Object.assign(Object.create(null),h);f.pos=u,f.end!=null&&(f.end=a.changes.mapPos(f.end)),c.push(f)}}o=c}for(let c of a.effects)c.is(t)&&(o=c.value,l=void 0),(c.is(Vg)&&!c.value||c.value==s)&&(o=[]);return o.length&&l&&i.set(o,l),o},provide:o=>Ds.from(o)});const r=xe.define(o=>new Wg(o,n,s,i,t,e.hoverTime||300));return{active:s,extension:[s,r,Ig.of(r),Bg]}}function Uu(n,e){let t=n.plugin(Ca);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const Vg=z.define(),sc=K.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Fu(n,e){let t=n.plugin(Du),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Du=xe.fromClass(class{constructor(n){this.input=n.state.facet(Vi),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(sc);this.top=new rs(n,!0,e.topContainer),this.bottom=new rs(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(sc);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new rs(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new rs(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Vi);if(t!=this.input){let i=t.filter(l=>l),s=[],r=[],o=[],a=[];for(let l of i){let c=this.specs.indexOf(l),h;c<0?(h=l(n.view),a.push(h)):(h=this.panels[c],h.update&&h.update(n)),s.push(h),(h.top?r:o).push(h)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>$.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class rs{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=rc(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=rc(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function rc(n){let e=n.nextSibling;return n.remove(),e}const Vi=K.define({enables:Du});function jg(n,e){let t,i=new Promise(o=>t=o),s=o=>Yg(o,e,t);n.state.field(Ir,!1)?n.dispatch({effects:Lu.of(s)}):n.dispatch({effects:z.appendConfig.of(Ir.init(()=>[s]))});let r=Xu.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(l=>n.win.setTimeout(l,10)))(()=>{n.state.field(Ir).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}const Ir=Te.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(Lu)?n=[t.value].concat(n):t.is(Xu)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>Vi.computeN([n],e=>e.field(n))}),Lu=z.define(),Xu=z.define();function Yg(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=he("form"),e.input){let a=he("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),i.appendChild(he("label",(e.label||"")+": ",a))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(he("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let a=0;a{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let r=he("div",i,he("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(a){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(a)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=i.querySelector(e.focus):a=i.querySelector("input")||i.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}class Mt extends Jt{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Mt.prototype.elementClass="";Mt.prototype.toDOM=void 0;Mt.prototype.mapMode=De.TrackBefore;Mt.prototype.startSide=Mt.prototype.endSide=-1;Mt.prototype.point=!0;const xs=K.define(),Ng=K.define(),Hg={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>N.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},An=K.define();function Bu(n){return[Iu(),An.of({...Hg,...n})]}const oc=K.define({combine:n=>n.some(e=>e)});function Iu(n){return[Gg]}const Gg=xe.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(An).map(e=>new lc(n,e)),this.fixed=!n.state.facet(oc);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(oc)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=N.iter(this.view.state.facet(xs),this.view.viewport.from),i=[],s=this.gutters.map(r=>new _g(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let a of r.type)if(a.type==Le.Text&&o){Yo(t,i,a.from);for(let l of s)l.line(this.view,a,i);o=!1}else if(a.widget)for(let l of s)l.widget(this.view,a)}else if(r.type==Le.Text){Yo(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(An),t=n.state.facet(An),i=n.docChanged||n.heightChanged||n.viewportChanged||!N.eq(n.startState.facet(xs),n.state.facet(xs),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new lc(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>$.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==fe.LTR?{left:i,right:s}:{right:i,left:s}})});function ac(n){return Array.isArray(n)?n:[n]}function Yo(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class _g{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=N.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let a=new Wu(e,o,r,i);s.elements.push(a),s.dom.appendChild(a.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Yo(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(Ng)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class lc{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let l=r.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=s.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,a,s)&&s.preventDefault()});this.markers=ac(t.markers(e)),t.initialSpacer&&(this.spacer=new Wu(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=ac(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!N.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class Wu{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),Jg(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let a=o,l=rr(a,l,c)||o(a,l,c):o}return i}})}});class Wr extends Mt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function qr(n,e){return n.state.facet(Ri).formatNumber(e,n.state)}const iO=An.compute([Ri],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(eO)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new Wr(qr(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(tO)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(Ri)!=e.state.facet(Ri),initialSpacer(e){return new Wr(qr(e,cc(e.state.doc.lines)))},updateSpacer(e,t){let i=qr(t.view,cc(t.view.state.doc.lines));return i==e.number?e:new Wr(i)},domEventHandlers:n.facet(Ri).domEventHandlers,side:"before"}));function nO(n={}){return[Ri.of(n),Iu(),iO]}function cc(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(sO.range(s)))}return N.of(e)});function oO(){return rO}const qu=1024;let aO=0;class zr{constructor(e,t){this.from=e,this.to=t}}class G{constructor(e={}){this.id=aO++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=et.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}G.closedBy=new G({deserialize:n=>n.split(" ")});G.openedBy=new G({deserialize:n=>n.split(" ")});G.group=new G({deserialize:n=>n.split(" ")});G.isolate=new G({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});G.contextHash=new G({perNode:!0});G.lookAhead=new G({perNode:!0});G.mounted=new G({perNode:!0});class bn{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[G.mounted.id]}}const lO=Object.create(null);class et{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):lO,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new et(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(G.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(G.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}}et.none=new et("",Object.create(null),0,8);class Ta{constructor(e){this.types=e;for(let t=0;t0;for(let l=this.cursor(o|be.IncludeAnonymous);;){let c=!1;if(l.from<=r&&l.to>=s&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&i&&(a||!l.type.isAnonymous)&&i(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Ka(et.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new ke(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new ke(et.none,t,i,s)))}static build(e){return fO(e)}}ke.empty=new ke(et.none,[],[],0);class Ra{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Ra(this.buffer,this.index)}}class ni{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return et.none}toString(){let e=[];for(let t=0;t0));l=o[l+3]);return a}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let a=e,l=0;a=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Pn(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?a.length:-1;e!=c;e+=t){let h=a[e],u=l[e]+o.from,f;if(!(!(r&be.EnterBracketed&&h instanceof ke&&(f=bn.get(h))&&!f.overlay&&f.bracketed&&i>=u&&i<=u+h.length)&&!zu(s,i,u,u+h.length))){if(h instanceof ni){if(r&be.ExcludeBuffers)continue;let d=h.findChild(0,h.buffer.length,t,i-u,s);if(d>-1)return new Tt(new cO(o,h,e,u),null,d)}else if(r&be.IncludeAnonymous||!h.type.isAnonymous||$a(h)){let d;if(!(r&be.IgnoreMounts)&&(d=bn.get(h))&&!d.overlay)return new Je(d.tree,u,e,o);let p=new Je(h,u,e,o);return r&be.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?h.children.length-1:0,t,i,s,r)}}}if(r&be.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&be.IgnoreOverlays)&&(s=bn.get(this._tree))&&s.overlay){let r=e-this.from,o=i&be.EnterBracketed&&s.bracketed;for(let{from:a,to:l}of s.overlay)if((t>0||o?a<=r:a=r:l>r))return new Je(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function uc(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function No(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class cO{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}}class Tt extends Vu{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new Tt(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&be.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new Tt(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Tt(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new Tt(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new ke(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function ju(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let a=new Je(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(Pn(a,e,t,!1))}}return s?ju(s):i}class Ho{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~be.EnterBracketed,e instanceof Je)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof Je?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&be.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&be.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&be.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let a=i._tree.children[r];if(this.mode&be.IncludeAnonymous||a instanceof ni||!a.type.isAnonymous||$a(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return No(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}}function $a(n){return n.children.some(e=>e instanceof ni||!e.type.isAnonymous||$a(e))}function fO(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=qu,reused:r=[],minRepeatType:o=i.types.length}=n,a=Array.isArray(t)?new Ra(t,t.length):t,l=i.types,c=0,h=0;function u(k,S,w,U,F,V){let{id:E,start:M,end:Y,size:Q}=a,D=h,P=c;if(Q<0)if(a.next(),Q==-1){let I=r[E];w.push(I),U.push(M-k);return}else if(Q==-3){c=E;return}else if(Q==-4){h=E;return}else throw new RangeError(`Unrecognized record size: ${Q}`);let j=l[E],ae,J,ee=M-k;if(Y-M<=s&&(J=g(a.pos-S,F))){let I=new Uint16Array(J.size-J.skip),H=a.pos-J.size,ce=I.length;for(;a.pos>H;)ce=y(J.start,I,ce);ae=new ni(I,Y-J.start,i),ee=J.start-k}else{let I=a.pos-Q;a.next();let H=[],ce=[],W=E>=o?E:-1,te=0,re=Y;for(;a.pos>I;)W>=0&&a.id==W&&a.size>=0?(a.end<=re-s&&(p(H,ce,M,te,a.end,re,W,D,P),te=H.length,re=a.end),a.next()):V>2500?f(M,I,H,ce):u(M,I,H,ce,W,V+1);if(W>=0&&te>0&&te-1&&te>0){let Me=d(j,P);ae=Ka(j,H,ce,0,H.length,0,Y-M,Me,Me)}else ae=m(j,H,ce,Y-M,D-Y,P)}w.push(ae),U.push(ee)}function f(k,S,w,U){let F=[],V=0,E=-1;for(;a.pos>S;){let{id:M,start:Y,end:Q,size:D}=a;if(D>4)a.next();else{if(E>-1&&Y=0;Q-=3)M[D++]=F[Q],M[D++]=F[Q+1]-Y,M[D++]=F[Q+2]-Y,M[D++]=D;w.push(new ni(M,F[2]-Y,i)),U.push(Y-k)}}function d(k,S){return(w,U,F)=>{let V=0,E=w.length-1,M,Y;if(E>=0&&(M=w[E])instanceof ke){if(!E&&M.type==k&&M.length==F)return M;(Y=M.prop(G.lookAhead))&&(V=U[E]+M.length+Y)}return m(k,w,U,F,V,S)}}function p(k,S,w,U,F,V,E,M,Y){let Q=[],D=[];for(;k.length>U;)Q.push(k.pop()),D.push(S.pop()+w-F);k.push(m(i.types[E],Q,D,V-F,M-V,Y)),S.push(F-w)}function m(k,S,w,U,F,V,E){if(V){let M=[G.contextHash,V];E=E?[M].concat(E):[M]}if(F>25){let M=[G.lookAhead,F];E=E?[M].concat(E):[M]}return new ke(k,S,w,U,E)}function g(k,S){let w=a.fork(),U=0,F=0,V=0,E=w.end-s,M={size:0,start:0,skip:0};e:for(let Y=w.pos-k;w.pos>Y;){let Q=w.size;if(w.id==S&&Q>=0){M.size=U,M.start=F,M.skip=V,V+=4,U+=4,w.next();continue}let D=w.pos-Q;if(Q<0||D=o?4:0,j=w.start;for(w.next();w.pos>D;){if(w.size<0)if(w.size==-3||w.size==-4)P+=4;else break e;else w.id>=o&&(P+=4);w.next()}F=j,U+=Q,V+=P}return(S<0||U==k)&&(M.size=U,M.start=F,M.skip=V),M.size>4?M:void 0}function y(k,S,w){let{id:U,start:F,end:V,size:E}=a;if(a.next(),E>=0&&U4){let Y=a.pos-(E-4);for(;a.pos>Y;)w=y(k,S,w)}S[--w]=M,S[--w]=V-k,S[--w]=F-k,S[--w]=U}else E==-3?c=U:E==-4&&(h=U);return w}let b=[],x=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,b,x,-1,0);let C=(e=n.length)!==null&&e!==void 0?e:b.length?x[0]+b[0].length:0;return new ke(l[n.topID],b.reverse(),x.reverse(),C)}const fc=new WeakMap;function vs(n,e){if(!n.isAnonymous||e instanceof ni||e.type!=n)return 1;let t=fc.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof ke)){t=1;break}t+=vs(n,i)}fc.set(e,t)}return t}function Ka(n,e,t,i,s,r,o,a,l){let c=0;for(let p=i;p=h)break;S+=w}if(x==C+1){if(S>h){let w=p[C];d(w.children,w.positions,0,w.children.length,m[C]+b);continue}u.push(p[C])}else{let w=m[x-1]+p[x-1].length-k;u.push(Ka(n,p,m,C,x,k,w,null,l))}f.push(k+b-r)}}return d(e,t,i,s,0),(a||l)(u,f,o)}class dO{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Tt?this.setBuffer(e.context.buffer,e.index,t):e instanceof Je&&this.map.set(e.tree,t)}get(e){return e instanceof Tt?this.getBuffer(e.context.buffer,e.index):e instanceof Je?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Oi{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new Oi(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let h=a=i)for(;o&&o.from=f.from||u<=f.to||c){let d=Math.max(f.from,l)-c,p=Math.min(f.to,u)-c;f=d>=p?null:new Oi(d,p,f.tree,f.offset+c,a>0,!!h)}if(f&&s.push(f),o.to>u)break;o=rnew zr(s.from,s.to)):[new zr(0,0)]:[new zr(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}}class pO{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new G({perNode:!0});let mO=0;class lt{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=mO++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof lt&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new lt(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new Ls(e);return i=>i.modified.indexOf(t)>-1?i:Ls.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}}let gO=0;class Ls{constructor(e){this.name=e,this.instances=[],this.id=gO++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(a=>a.base==e&&OO(t,a.modified));if(i)return i;let s=[],r=new lt(e.name,s,e,t);for(let a of t)a.instances.push(r);let o=yO(t);for(let a of e.set)if(!a.modified.length)for(let l of o)s.push(Ls.get(a,l));return r}}function OO(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function yO(n){let e=[[]];for(let t=0;ti.length-t.length)}function Nu(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,a=s;for(let u=0;;){if(a=="..."&&u>0&&u+3==s.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!f)throw new RangeError("Invalid path: "+s);if(r.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),u+=f[0].length,u==s.length)break;let d=s[u++];if(u==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);a=s.slice(u)}let l=r.length-1,c=r[l];if(!c)throw new RangeError("Invalid path: "+s);let h=new Cn(i,o,l>0?r.slice(0,l):null);e[c]=h.sort(e[c])}}return Hu.add(e)}const Hu=new G({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Cn(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}});class Cn{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let a of r)for(let l of a.set){let c=t[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:i}}function AO(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function bO(n,e,t,i=0,s=n.length){let r=new SO(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}class SO{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:a,to:l}=e;if(a>=i||l<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let c=s,h=xO(e)||Cn.empty,u=AO(r,h.tags);if(u&&(c&&(c+=" "),c+=u,h.mode==1&&(s+=(s?" ":"")+u)),this.startSpan(Math.max(t,a),c),h.opaque)return;let f=e.tree&&e.tree.prop(G.mounted);if(f&&f.overlay){let d=e.node.enter(f.overlay[0].from+a,1),p=this.highlighters.filter(g=>!g.scope||g.scope(f.tree.type)),m=e.firstChild();for(let g=0,y=a;;g++){let b=g=x||!e.nextSibling())););if(!b||x>i)break;y=b.to+a,y>t&&(this.highlightRange(d.cursor(),Math.max(t,b.from+a),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),c))}m&&e.parent()}else if(e.firstChild()){f&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),c)}while(e.nextSibling());e.parent()}}}function xO(n){let e=n.type.prop(Hu);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const T=lt.define,as=T(),Vt=T(),dc=T(Vt),pc=T(Vt),jt=T(),ls=T(jt),Vr=T(jt),wt=T(),li=T(wt),xt=T(),vt=T(),Go=T(),on=T(Go),cs=T(),O={comment:as,lineComment:T(as),blockComment:T(as),docComment:T(as),name:Vt,variableName:T(Vt),typeName:dc,tagName:T(dc),propertyName:pc,attributeName:T(pc),className:T(Vt),labelName:T(Vt),namespace:T(Vt),macroName:T(Vt),literal:jt,string:ls,docString:T(ls),character:T(ls),attributeValue:T(ls),number:Vr,integer:T(Vr),float:T(Vr),bool:T(jt),regexp:T(jt),escape:T(jt),color:T(jt),url:T(jt),keyword:xt,self:T(xt),null:T(xt),atom:T(xt),unit:T(xt),modifier:T(xt),operatorKeyword:T(xt),controlKeyword:T(xt),definitionKeyword:T(xt),moduleKeyword:T(xt),operator:vt,derefOperator:T(vt),arithmeticOperator:T(vt),logicOperator:T(vt),bitwiseOperator:T(vt),compareOperator:T(vt),updateOperator:T(vt),definitionOperator:T(vt),typeOperator:T(vt),controlOperator:T(vt),punctuation:Go,separator:T(Go),bracket:on,angleBracket:T(on),squareBracket:T(on),paren:T(on),brace:T(on),content:wt,heading:li,heading1:T(li),heading2:T(li),heading3:T(li),heading4:T(li),heading5:T(li),heading6:T(li),contentSeparator:T(wt),list:T(wt),quote:T(wt),emphasis:T(wt),strong:T(wt),link:T(wt),monospace:T(wt),strikethrough:T(wt),inserted:T(),deleted:T(),changed:T(),invalid:T(),meta:cs,documentMeta:T(cs),annotation:T(cs),processingInstruction:T(cs),definition:lt.defineModifier("definition"),constant:lt.defineModifier("constant"),function:lt.defineModifier("function"),standard:lt.defineModifier("standard"),local:lt.defineModifier("local"),special:lt.defineModifier("special")};for(let n in O){let e=O[n];e instanceof lt&&(e.name=n)}Gu([{tag:O.link,class:"tok-link"},{tag:O.heading,class:"tok-heading"},{tag:O.emphasis,class:"tok-emphasis"},{tag:O.strong,class:"tok-strong"},{tag:O.keyword,class:"tok-keyword"},{tag:O.atom,class:"tok-atom"},{tag:O.bool,class:"tok-bool"},{tag:O.url,class:"tok-url"},{tag:O.labelName,class:"tok-labelName"},{tag:O.inserted,class:"tok-inserted"},{tag:O.deleted,class:"tok-deleted"},{tag:O.literal,class:"tok-literal"},{tag:O.string,class:"tok-string"},{tag:O.number,class:"tok-number"},{tag:[O.regexp,O.escape,O.special(O.string)],class:"tok-string2"},{tag:O.variableName,class:"tok-variableName"},{tag:O.local(O.variableName),class:"tok-variableName tok-local"},{tag:O.definition(O.variableName),class:"tok-variableName tok-definition"},{tag:O.special(O.variableName),class:"tok-variableName2"},{tag:O.definition(O.propertyName),class:"tok-propertyName tok-definition"},{tag:O.typeName,class:"tok-typeName"},{tag:O.namespace,class:"tok-namespace"},{tag:O.className,class:"tok-className"},{tag:O.macroName,class:"tok-macroName"},{tag:O.propertyName,class:"tok-propertyName"},{tag:O.operator,class:"tok-operator"},{tag:O.comment,class:"tok-comment"},{tag:O.meta,class:"tok-meta"},{tag:O.invalid,class:"tok-invalid"},{tag:O.punctuation,class:"tok-punctuation"}]);var jr;const $i=new G;function _u(n){return K.define({combine:n?e=>e.concat(n):void 0})}const Za=new G;class mt{constructor(e,t,i=[],s=""){this.data=e,this.name=s,_.prototype.hasOwnProperty("tree")||Object.defineProperty(_.prototype,"tree",{get(){return Ce(this)}}),this.parser=t,this.extension=[si.of(this),_.languageData.of((r,o,a)=>{let l=mc(r,o,a),c=l.type.prop($i);if(!c)return[];let h=r.facet(c),u=l.type.prop(Za);if(u){let f=l.resolve(o-l.from,a);for(let d of u)if(d.test(f,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(h)}}return h})].concat(i)}isActiveAt(e,t,i=-1){return mc(e,t,i).type.prop($i)==this.data}findRegions(e){let t=e.facet(si);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop($i)==this.data){i.push({from:o,to:o+r.length});return}let a=r.prop(G.mounted);if(a){if(a.tree.prop($i)==this.data){if(a.overlay)for(let l of a.overlay)i.push({from:l.from+o,to:l.to+o});else i.push({from:o,to:o+r.length});return}else if(a.overlay){let l=i.length;if(s(a.tree,a.overlay[0].from+o),i.length>l)return}}for(let l=0;li.isTop?t:void 0)]}),e.name)}configure(e,t){return new Xs(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Ce(n){let e=n.field(mt.state,!1);return e?e.tree:ke.empty}class vO{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let an=null;class Bs{constructor(e,t,i=[],s,r,o,a,l){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new Bs(e,t,[],ke.empty,0,i,[],null)}startParse(){return this.parser.startParse(new vO(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=ke.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Oi.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=an;an=this;try{return e()}finally{an=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=gc(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,h,u,f)=>l.push({fromA:c,toA:h,fromB:u,toB:f})),i=Oi.applyChanges(i,l),s=ke.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let h=e.mapPos(c.from,1),u=e.mapPos(c.to,-1);he.from&&(this.fragments=gc(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends Yu{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let l=an;if(l){for(let c of s)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new ke(et.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return an}}function gc(n,e,t){return Oi.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class ji{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new ji(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Bs.create(e.facet(si).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new ji(i)}}mt.state=Te.define({create:ji.init,update(n,e){for(let t of e.effects)if(t.is(mt.setState))return t.value;return e.startState.facet(si)!=e.state.facet(si)?ji.init(e.state):n.apply(e)}});let Ju=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(Ju=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const Yr=typeof navigator<"u"&&(!((jr=navigator.scheduling)===null||jr===void 0)&&jr.isInputPending)?()=>navigator.scheduling.isInputPending():null,wO=xe.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(mt.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(mt.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=Ju(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,l=r.context.work(()=>Yr&&Yr()||Date.now()>o,s+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:mt.setState.of(new ji(r.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ze(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),si=K.define({combine(n){return n.length?n[0]:null},enables:n=>[mt.state,wO,$.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class kO{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}const QO=K.define(),yr=K.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function Is(n){let e=n.facet(yr);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Tn(n,e){let t="",i=n.tabSize,s=n.facet(yr)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?PO(n,t,e):null}class Ar{constructor(e,t={}){this.state=e,this.options=t,this.unit=Is(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return _i(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const ef=new G;function PO(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return tf(i,n,t)}function tf(n,e,t){for(let i=n;i;i=i.next){let s=TO(i.node);if(s)return s(Ea.create(e,t,i))}return 0}function CO(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function TO(n){let e=n.type.prop(ef);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(G.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>nf(o,!0,1,void 0,r&&!CO(o)?s.from:void 0)}return n.parent==null?RO:null}function RO(){return 0}class Ea extends Ar{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new Ea(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if($O(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return tf(this.context.next,this.base,this.pos)}}function $O(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function KO(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==i)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+c}}a=l.to}}function ZO({closing:n,align:e=!0,units:t=1}){return i=>nf(i,e,t,n)}function nf(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,a=i&&r.slice(o,o+i.length)==i||s==n.pos+o,l=e?KO(n):null;return l?a?n.column(l.from):n.column(l.to):n.baseIndent+(a?0:n.unit*t)}const MO=n=>n.baseIndent;function Nr({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const EO=200;function UO(){return _.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+EO)return n;let r=t.sliceString(s.from,i);if(!e.some(c=>c.test(r)))return n;let{state:o}=n,a=-1,l=[];for(let{head:c}of o.selection.ranges){let h=o.doc.lineAt(c);if(h.from==a)continue;a=h.from;let u=Ma(o,h.from);if(u==null)continue;let f=/^\s*/.exec(h.text)[0],d=Tn(o,u);f!=d&&l.push({from:h.from,to:h.from+f.length,insert:d})}return l.length?[n,{changes:l,sequential:!0}]:n})}const FO=K.define(),sf=new G;function DO(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(r&&a.from=e&&c.to>t&&(r=c)}}return r}function XO(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function Ws(n,e,t){for(let i of n.facet(FO)){let s=i(n,e,t);if(s)return s}return LO(n,e,t)}function rf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const br=z.define({map:rf}),Ln=z.define({map:rf});function of(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const xi=Te.define({create(){return B.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((i,s)=>n=Oc(n,i,s)),n=n.map(e.changes);let t=[];for(let i of e.effects)i.is(br)&&!BO(n,i.value.from,i.value.to)?t.push(i.value):i.is(Ln)&&(n=n.update({filter:(s,r)=>i.value.from!=s||i.value.to!=r,filterFrom:i.value.from,filterTo:i.value.to}));if(t.length){let{preparePlaceholder:i}=e.state.facet(cf),s=t.map(r=>(i?B.replace({widget:new YO(i(e.state,r))}):yc).range(r.from,r.to));n=n.update({add:s})}return e.selection&&(n=Oc(n,e.selection.main.head)),n},provide:n=>$.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{se&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function qs(n,e,t){var i;let s=null;return(i=n.field(xi,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function BO(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function af(n,e){return n.field(xi,!1)?e:e.concat(z.appendConfig.of(hf()))}const IO=n=>{for(let e of of(n)){let t=Ws(n.state,e.from,e.to);if(t)return n.dispatch({effects:af(n.state,[br.of(t),lf(n,t)])}),!0}return!1},WO=n=>{if(!n.state.field(xi,!1))return!1;let e=[];for(let t of of(n)){let i=qs(n.state,t.from,t.to);i&&e.push(Ln.of(i),lf(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function lf(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return $.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}const qO=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(xi,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(Ln.of({from:i,to:s}))}),n.dispatch({effects:t}),!0},VO=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:IO},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:WO},{key:"Ctrl-Alt-[",run:qO},{key:"Ctrl-Alt-]",run:zO}],jO={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},cf=K.define({combine(n){return yt(n,jO)}});function hf(n){return[xi,GO]}function uf(n,e){let{state:t}=n,i=t.facet(cf),s=o=>{let a=n.lineBlockAt(n.posAtDOM(o.target)),l=qs(n.state,a.from,a.to);l&&n.dispatch({effects:Ln.of(l)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}const yc=B.replace({widget:new class extends Ut{toDOM(n){return uf(n,null)}}});class YO extends Ut{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return uf(e,this.value)}}const NO={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class Hr extends Mt{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function HO(n={}){let e={...NO,...n},t=new Hr(e,!0),i=new Hr(e,!1),s=xe.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(si)!=o.state.facet(si)||o.startState.field(xi,!1)!=o.state.field(xi,!1)||Ce(o.startState)!=Ce(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new Bt;for(let l of o.viewportLineBlocks){let c=qs(o.state,l.from,l.to)?i:Ws(o.state,l.from,l.to)?t:null;c&&a.add(l.from,l.from,c)}return a.finish()}}),{domEventHandlers:r}=e;return[s,Bu({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(s))===null||a===void 0?void 0:a.markers)||N.empty},initialSpacer(){return new Hr(e,!1)},domEventHandlers:{...r,click:(o,a,l)=>{if(r.click&&r.click(o,a,l))return!0;let c=qs(o.state,a.from,a.to);if(c)return o.dispatch({effects:Ln.of(c)}),!0;let h=Ws(o.state,a.from,a.to);return h?(o.dispatch({effects:br.of(h)}),!0):!1}}}),hf()]}const GO=$.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class Xn{constructor(e,t){this.specs=e;let i;function s(a){let l=ei.newName();return(i||(i=Object.create(null)))["."+l]=a,l}const r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof mt?a=>a.prop($i)==o.data:o?a=>a==o:void 0,this.style=Gu(e.map(a=>({tag:a.tag,class:a.class||s(Object.assign({},a,{tag:null}))})),{all:r}).style,this.module=i?new ei(i):null,this.themeType=t.themeType}static define(e,t){return new Xn(e,t||{})}}const _o=K.define(),_O=K.define({combine(n){return n.length?[n[0]]:null}});function Gr(n){let e=n.facet(_o);return e.length?e:n.facet(_O)}function JO(n,e){let t=[t0],i;return n instanceof Xn&&(n.module&&t.push($.styleModule.of(n.module)),i=n.themeType),i?t.push(_o.computeN([$.darkTheme],s=>s.facet($.darkTheme)==(i=="dark")?[n]:[])):t.push(_o.of(n)),t}class e0{constructor(e){this.markCache=Object.create(null),this.tree=Ce(e.state),this.decorations=this.buildDeco(e,Gr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=Ce(e.state),i=Gr(e.state),s=i!=Gr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return B.none;let i=new Bt;for(let{from:s,to:r}of e.visibleRanges)bO(this.tree,t,(o,a,l)=>{i.add(o,a,this.markCache[l]||(this.markCache[l]=B.mark({class:l})))},s,r);return i.finish()}}const t0=ri.high(xe.fromClass(e0,{decorations:n=>n.decorations})),i0=Xn.define([{tag:O.meta,color:"#404740"},{tag:O.link,textDecoration:"underline"},{tag:O.heading,textDecoration:"underline",fontWeight:"bold"},{tag:O.emphasis,fontStyle:"italic"},{tag:O.strong,fontWeight:"bold"},{tag:O.strikethrough,textDecoration:"line-through"},{tag:O.keyword,color:"#708"},{tag:[O.atom,O.bool,O.url,O.contentSeparator,O.labelName],color:"#219"},{tag:[O.literal,O.inserted],color:"#164"},{tag:[O.string,O.deleted],color:"#a11"},{tag:[O.regexp,O.escape,O.special(O.string)],color:"#e40"},{tag:O.definition(O.variableName),color:"#00f"},{tag:O.local(O.variableName),color:"#30a"},{tag:[O.typeName,O.namespace],color:"#085"},{tag:O.className,color:"#167"},{tag:[O.special(O.variableName),O.macroName],color:"#256"},{tag:O.definition(O.propertyName),color:"#00c"},{tag:O.comment,color:"#940"},{tag:O.invalid,color:"#f00"}]),n0=$.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),ff=1e4,df="()[]{}",pf=K.define({combine(n){return yt(n,{afterCursor:!0,brackets:df,maxScanDistance:ff,renderMatch:o0})}}),s0=B.mark({class:"cm-matchingBracket"}),r0=B.mark({class:"cm-nonmatchingBracket"});function o0(n){let e=[],t=n.matched?s0:r0;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function Ac(n){let e=[],t=n.facet(pf);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Rt(n,i.head,-1,t)||i.head>0&&Rt(n,i.head-1,1,t)||t.afterCursor&&(Rt(n,i.head,1,t)||i.headn.decorations}),l0=[a0,n0];function c0(n={}){return[pf.of(n),l0]}const h0=new G;function Jo(n,e,t){let i=n.prop(e<0?G.openedBy:G.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function ea(n){let e=n.type.prop(h0);return e?e(n.node):n}function Rt(n,e,t,i={}){let s=i.maxScanDistance||ff,r=i.brackets||df,o=Ce(n),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let c=Jo(l.type,t,r);if(c&&l.from0?e>=h.from&&eh.from&&e<=h.to))return u0(n,e,t,l,h,c,r)}}return f0(n,e,t,o,a.type,s,r)}function u0(n,e,t,i,s,r,o){let a=i.parent,l={from:s.from,to:s.to},c=0,h=a?.cursor();if(h&&(t<0?h.childBefore(i.from):h.childAfter(i.to)))do if(t<0?h.to<=i.from:h.from>=i.to){if(c==0&&r.indexOf(h.type.name)>-1&&h.from0)return null;let c={from:t<0?e-1:e,to:t>0?e+1:e},h=n.doc.iterRange(e,t>0?n.doc.length:0),u=0;for(let f=0;!h.next().done&&f<=r;){let d=h.value;t<0&&(f+=d.length);let p=e+f*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let y=o.indexOf(d[m]);if(!(y<0||i.resolveInner(p+m,1).type!=s))if(y%2==0==t>0)u++;else{if(u==1)return{start:c,end:{from:p+m,to:p+m+1},matched:y>>1==l>>1};u--}}t>0&&(f+=d.length)}return h.done?{start:c,matched:!1}:null}const d0=Object.create(null),bc=[et.none],Sc=[],xc=Object.create(null),p0=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])p0[n]=m0(d0,e);function _r(n,e){Sc.indexOf(n)>-1||(Sc.push(n),console.warn(e))}function m0(n,e){let t=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let h=n[c]||O[c];h?typeof h=="function"?l.length?l=l.map(h):_r(c,`Modifier ${c} used at start of tag`):l.length?_r(c,`Tag ${c} used as modifier`):l=Array.isArray(h)?h:[h]:_r(c,`Unknown highlighting tag ${c}`)}for(let c of l)t.push(c)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(a=>a.id),r=xc[s];if(r)return r.id;let o=xc[s]=et.define({id:bc.length,name:i,props:[Nu({[i]:t})]});return bc.push(o),o.id}fe.RTL,fe.LTR;const g0=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=Fa(n.state,t.from);return i.line?O0(n):i.block?A0(n):!1};function Ua(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}const O0=Ua(x0,0),y0=Ua(mf,0),A0=Ua((n,e)=>mf(n,e,S0(e)),0);function Fa(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const ln=50;function b0(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-ln,i),o=n.sliceDoc(s,s+ln),a=/\s*$/.exec(r)[0].length,l=/^\s*/.exec(o)[0].length,c=r.length-a;if(r.slice(c-e.length,c)==e&&o.slice(l,l+t.length)==t)return{open:{pos:i-a,margin:a&&1},close:{pos:s+l,margin:l&&1}};let h,u;s-i<=2*ln?h=u=n.sliceDoc(i,s):(h=n.sliceDoc(i,i+ln),u=n.sliceDoc(s-ln,s));let f=/^\s*/.exec(h)[0].length,d=/\s*$/.exec(u)[0].length,p=u.length-d-t.length;return h.slice(f,f+e.length)==e&&u.slice(p,p+t.length)==t?{open:{pos:i+f+e.length,margin:/\s/.test(h.charAt(f+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(u.charAt(p-1))?1:0}}:null}function S0(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function mf(n,e,t=e.selection.ranges){let i=t.map(r=>Fa(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>b0(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,a;os&&(r==o||o>u.from)){s=u.from;let f=/^\s*/.exec(u.text)[0].length,d=f==u.length,p=u.text.slice(f,f+c.length)==c?f:-1;fr.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:a,token:l,indent:c,empty:h,single:u}of i)(u||!h)&&r.push({from:a.from+c,insert:l+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:a,token:l}of i)if(a>=0){let c=o.from+a,h=c+l.length;o.text[h-o.from]==" "&&h++,r.push({from:c,to:h})}return{changes:r}}return null}const ta=qt.define(),ws=qt.define(),v0=K.define(),gf=K.define({combine(n){return yt(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),Da=Te.define({create(){return $t.empty},update(n,e){let t=e.state.facet(gf),i=e.annotation(ta);if(i){let l=_e.fromTransaction(e,i.selection),c=i.side,h=c==0?n.undone:n.done;return l?h=Vs(h,h.length,t.minDepth,l):h=Af(h,e.startState.selection),new $t(c==0?i.rest:h,c==0?h:i.rest)}let s=e.annotation(ws);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(Pe.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=_e.fromTransaction(e),o=e.annotation(Pe.time),a=e.annotation(Pe.userEvent);return r?n=n.addChanges(r,o,a,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new $t(n.done.map(_e.fromJSON),n.undone.map(_e.fromJSON))}});function w0(n={}){return[Da,gf.of(n),$.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?La:e.inputType=="historyRedo"?zs:null;return i?(e.preventDefault(),i(t)):!1}})]}function Sr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(Da,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}const La=Sr(0,!1),zs=Sr(1,!1),k0=Sr(0,!0),Q0=Sr(1,!0);function Of(n){return function(e){let t=e.field(Da,!1);if(!t)return 0;let i=n==0?t.done:t.undone;return i.length-(i.length&&!i[0].changes?1:0)}}const vc=Of(0),wc=Of(1);class _e{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new _e(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new _e(e.changes&&Re.fromJSON(e.changes),[],e.mapped&&Zt.fromJSON(e.mapped),e.startSelection&&A.fromJSON(e.startSelection),e.selectionsAfter.map(A.fromJSON))}static fromTransaction(e,t){let i=ht;for(let s of e.startState.facet(v0)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new _e(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,ht)}static selection(e){return new _e(void 0,ht,void 0,void 0,e)}}function Vs(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function P0(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,a)=>{for(let l=0;l=c&&o<=h&&(i=!0)}}),i}function C0(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function yf(n,e){return n.length?e.length?n.concat(e):n:e}const ht=[],T0=200;function Af(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-T0));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),Vs(n,n.length-1,1e9,t.setSelAfter(i)))}else return[_e.selection([e])]}function R0(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function Jr(n,e){if(!n.length)return n;let t=n.length,i=ht;for(;t;){let s=$0(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[_e.selection(i)]:ht}function $0(n,e,t){let i=yf(n.selectionsAfter.length?n.selectionsAfter.map(a=>a.map(e)):ht,t);if(!n.changes)return _e.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new _e(s,z.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}const K0=/^(input\.type|delete)($|\.)/;class $t{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new $t(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!i||K0.test(i))&&(!a.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):xr(t,e))}function Be(n){return n.textDirectionAt(n.state.selection.main.head)==fe.LTR}const Sf=n=>bf(n,!Be(n)),xf=n=>bf(n,Be(n));function vf(n,e){return bt(n,t=>t.empty?n.moveByGroup(t,e):xr(t,e))}const M0=n=>vf(n,!Be(n)),E0=n=>vf(n,Be(n));function U0(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function vr(n,e,t){let i=Ce(n).resolveInner(e.head),s=t?G.closedBy:G.openedBy;for(let l=e.head;;){let c=t?i.childAfter(l):i.childBefore(l);if(!c)break;U0(n,c,s)?i=c:l=t?c.to:c.from}let r=i.type.prop(s),o,a;return r&&(o=t?Rt(n,i.from,1):Rt(n,i.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?i.to:i.from,A.cursor(a,t?-1:1)}const F0=n=>bt(n,e=>vr(n.state,e,!Be(n))),D0=n=>bt(n,e=>vr(n.state,e,Be(n)));function wf(n,e){return bt(n,t=>{if(!t.empty)return xr(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const kf=n=>wf(n,!1),Qf=n=>wf(n,!0);function Pf(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):xr(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),a=n.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,c=a.bottom-t.marginBottom;o&&o.top>l&&o.bottomCf(n,!1),ia=n=>Cf(n,!0);function oi(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=A.cursor(i.from+r))}return s}const L0=n=>bt(n,e=>oi(n,e,!0)),X0=n=>bt(n,e=>oi(n,e,!1)),B0=n=>bt(n,e=>oi(n,e,!Be(n))),I0=n=>bt(n,e=>oi(n,e,Be(n))),W0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).from,1)),q0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).to,-1));function z0(n,e,t){let i=!1,s=Ji(n.selection,r=>{let o=Rt(n,r.head,-1)||Rt(n,r.head,1)||r.head>0&&Rt(n,r.head-1,1)||r.headz0(n,e);function ft(n,e,t){let i=Ji(n.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=A.range(s.head,s.anchor));let r=t(s);return A.range(s.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(At(n.state,i)),!0)}function Tf(n,e){return ft(n,e,t=>n.moveByChar(t,e))}const Rf=n=>Tf(n,!Be(n)),$f=n=>Tf(n,Be(n));function Kf(n,e){return ft(n,e,t=>n.moveByGroup(t,e))}const j0=n=>Kf(n,!Be(n)),Y0=n=>Kf(n,Be(n)),N0=n=>{let e=!Be(n);return ft(n,e,t=>vr(n.state,t,e))},H0=n=>{let e=Be(n);return ft(n,e,t=>vr(n.state,t,e))};function Zf(n,e){return ft(n,e,t=>n.moveVertically(t,e))}const Mf=n=>Zf(n,!1),Ef=n=>Zf(n,!0);function Uf(n,e){return ft(n,e,t=>n.moveVertically(t,e,Pf(n).height))}const Qc=n=>Uf(n,!1),Pc=n=>Uf(n,!0),G0=n=>ft(n,!0,e=>oi(n,e,!0)),_0=n=>ft(n,!1,e=>oi(n,e,!1)),J0=n=>{let e=!Be(n);return ft(n,e,t=>oi(n,t,e))},ey=n=>{let e=Be(n);return ft(n,e,t=>oi(n,t,e))},ty=n=>ft(n,!1,e=>A.cursor(n.lineBlockAt(e.head).from)),iy=n=>ft(n,!0,e=>A.cursor(n.lineBlockAt(e.head).to)),Cc=({state:n,dispatch:e})=>(e(At(n,{anchor:0})),!0),Tc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.doc.length})),!0),Rc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:0})),!0),$c=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),ny=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),sy=({state:n,dispatch:e})=>{let t=wr(n).map(({from:i,to:s})=>A.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:A.create(t),userEvent:"select"})),!0},ry=({state:n,dispatch:e})=>{let t=Ji(n.selection,i=>{let s=Ce(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:a}=o;if((a.from=i.to||a.to>i.to&&a.from<=i.from)&&o.next)return A.range(a.to,a.from)}return i});return t.eq(n.selection)?!1:(e(At(n,t)),!0)};function Ff(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let a=r;;){let l=n.moveVertically(a,e);if(l.heado.to){s.some(c=>c.head==l.head)||s.push(l);break}else{if(l.head==a.head)break;a=l}}}return s.length==i.ranges.length?!1:(n.dispatch(At(t,A.create(s,s.length-1))),!0)}const oy=n=>Ff(n,!1),ay=n=>Ff(n,!0),ly=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=A.create([t.main]):t.main.empty||(i=A.create([A.cursor(t.main.head)])),i?(e(At(n,i)),!0):!1};function Bn(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:a}=r;if(o==a){let l=e(r);lo&&(t="delete.forward",l=hs(n,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=hs(n,o,!1),a=hs(n,a,!0);return o==a?{range:r}:{changes:{from:o,to:a},range:A.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}const Df=(n,e,t)=>Bn(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),a,l;if(t&&!e&&s>o.from&&sDf(n,!1,!0),Lf=n=>Df(n,!0,!1),Xf=(n,e)=>Bn(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let a=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let l=Ze(r.text,i-r.from,e)+r.from,c=r.text.slice(Math.min(i,l)-r.from,Math.max(i,l)-r.from),h=o(c);if(a!=null&&h!=a)break;(c!=" "||i!=t.head)&&(a=h),i=l}return i}),Bf=n=>Xf(n,!1),cy=n=>Xf(n,!0),hy=n=>Bn(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headBn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),fy=n=>Bn(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:se.of(["",""])},range:A.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},py=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:Ze(r.text,s-r.from,!1)+r.from,a=s==r.to?s+1:Ze(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:a,insert:n.doc.slice(s,a).append(n.doc.slice(o,s))},range:A.cursor(a)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function wr(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function If(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of wr(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),a=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let l of r.ranges)s.push(A.range(Math.min(n.doc.length,l.anchor+a),Math.min(n.doc.length,l.head+a)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let l of r.ranges)s.push(A.range(l.anchor-a,l.head-a))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:A.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const my=({state:n,dispatch:e})=>If(n,e,!1),gy=({state:n,dispatch:e})=>If(n,e,!0);function Wf(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of wr(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const Oy=({state:n,dispatch:e})=>Wf(n,e,!1),yy=({state:n,dispatch:e})=>Wf(n,e,!0),Ay=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(wr(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),a=n.coordsAtPos(s.head,s.assoc||1);a&&(r=o.bottom+n.documentTop-a.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function by(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Ce(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(G.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}const Kc=qf(!1),Sy=qf(!0);function qf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,a=e.doc.lineAt(r),l=!n&&r==o&&by(e,r);n&&(r=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Ar(e,{simulateBreak:r,simulateDoubleBreak:!!l}),h=Ma(c,r);for(h==null&&(h=_i(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));oa.from&&r{let s=[];for(let o=i.from;o<=i.to;){let a=n.doc.lineAt(o);a.number>t&&(i.empty||i.to>a.from)&&(e(a,s,i),t=a.number),o=a.to+1}let r=n.changes(s);return{changes:s,range:A.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}const xy=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Ar(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=Xa(n,(r,o,a)=>{let l=Ma(i,r.from);if(l==null)return;/\S/.test(r.text)||(l=0);let c=/^\s*/.exec(r.text)[0],h=Tn(n,l);(c!=h||a.fromn.readOnly?!1:(e(n.update(Xa(n,(t,i)=>{i.push({from:t.from,insert:n.facet(yr)})}),{userEvent:"input.indent"})),!0),Vf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Xa(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=_i(s,n.tabSize),o=0,a=Tn(n,Math.max(0,r-Is(n)));for(;o(n.setTabFocusMode(),!0),wy=[{key:"Ctrl-b",run:Sf,shift:Rf,preventDefault:!0},{key:"Ctrl-f",run:xf,shift:$f},{key:"Ctrl-p",run:kf,shift:Mf},{key:"Ctrl-n",run:Qf,shift:Ef},{key:"Ctrl-a",run:W0,shift:ty},{key:"Ctrl-e",run:q0,shift:iy},{key:"Ctrl-d",run:Lf},{key:"Ctrl-h",run:na},{key:"Ctrl-k",run:hy},{key:"Ctrl-Alt-h",run:Bf},{key:"Ctrl-o",run:dy},{key:"Ctrl-t",run:py},{key:"Ctrl-v",run:ia}],ky=[{key:"ArrowLeft",run:Sf,shift:Rf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:M0,shift:j0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:B0,shift:J0,preventDefault:!0},{key:"ArrowRight",run:xf,shift:$f,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:E0,shift:Y0,preventDefault:!0},{mac:"Cmd-ArrowRight",run:I0,shift:ey,preventDefault:!0},{key:"ArrowUp",run:kf,shift:Mf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Cc,shift:Rc},{mac:"Ctrl-ArrowUp",run:kc,shift:Qc},{key:"ArrowDown",run:Qf,shift:Ef,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Tc,shift:$c},{mac:"Ctrl-ArrowDown",run:ia,shift:Pc},{key:"PageUp",run:kc,shift:Qc},{key:"PageDown",run:ia,shift:Pc},{key:"Home",run:X0,shift:_0,preventDefault:!0},{key:"Mod-Home",run:Cc,shift:Rc},{key:"End",run:L0,shift:G0,preventDefault:!0},{key:"Mod-End",run:Tc,shift:$c},{key:"Enter",run:Kc,shift:Kc},{key:"Mod-a",run:ny},{key:"Backspace",run:na,shift:na,preventDefault:!0},{key:"Delete",run:Lf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Bf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:cy,preventDefault:!0},{mac:"Mod-Backspace",run:uy,preventDefault:!0},{mac:"Mod-Delete",run:fy,preventDefault:!0}].concat(wy.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),Qy=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:F0,shift:N0},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:D0,shift:H0},{key:"Alt-ArrowUp",run:my},{key:"Shift-Alt-ArrowUp",run:Oy},{key:"Alt-ArrowDown",run:gy},{key:"Shift-Alt-ArrowDown",run:yy},{key:"Mod-Alt-ArrowUp",run:oy},{key:"Mod-Alt-ArrowDown",run:ay},{key:"Escape",run:ly},{key:"Mod-Enter",run:Sy},{key:"Alt-l",mac:"Ctrl-l",run:sy},{key:"Mod-i",run:ry,preventDefault:!0},{key:"Mod-[",run:Vf},{key:"Mod-]",run:zf},{key:"Mod-Alt-\\",run:xy},{key:"Shift-Mod-k",run:Ay},{key:"Shift-Mod-\\",run:V0},{key:"Mod-/",run:g0},{key:"Alt-A",run:y0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:vy}].concat(ky),Py={key:"Tab",run:zf,shift:Vf};class jf{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=Ce(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(Nf(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}}function Zc(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Cy(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Cy(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function Ty(n,e){return t=>{for(let i=Ce(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}let Mc=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function yi(n){return n.selection.main.from}function Nf(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}const Ba=qt.define();function Ry(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(a=>{if(a!=s&&t!=i&&n.sliceDoc(a.from+r,a.from+o)!=n.sliceDoc(t,i))return{range:a};let l=n.toText(e);return{changes:{from:a.from+r,to:i==s.from?a.to:a.from+o,insert:l},range:A.cursor(a.from+r+l.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const Ec=new WeakMap;function $y(n){if(!Array.isArray(n))return n;let e=Ec.get(n);return e||Ec.set(n,e=Yf(n)),e}const js=z.define(),Rn=z.define();class Ky{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t=48&&k<=57||k>=97&&k<=122?2:k>=65&&k<=90?1:0:(S=fa(k))!=S.toLowerCase()?1:S!=S.toUpperCase()?2:0;(!b||w==1&&g||C==0&&w!=0)&&(t[u]==k||i[u]==k&&(f=!0)?o[u++]=b:o.length&&(y=!1)),C=w,b+=Qt(k)}return u==l&&o[0]==0&&y?this.result(-100+(f?-200:0),o,e):d==l&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):a>-1?this.ret(-700-e.length,[a,a+this.pattern.length]):d==l?this.ret(-900-e.length,[p,m]):u==l?this.result(-100+(f?-200:0)+-700+(y?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let a=o+(this.astral?Qt(Ne(i,o)):1);r&&s[r-1]==o?s[r-1]=a:(s[r++]=o,s[r++]=a)}return this.ret(e-i.length,s)}}class Zy{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:My,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>Uc(e(i),t(i)),optionClass:(e,t)=>i=>Uc(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function Uc(n,e){return n?e?n+" "+e:n:e}function My(n,e,t,i,s,r){let o=n.textDirection==fe.RTL,a=o,l=!1,c="top",h,u,f=e.left-s.left,d=s.right-e.right,p=i.right-i.left,m=i.bottom-i.top;if(a&&f=m||b>e.top?h=t.bottom-e.top:(c="bottom",h=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,y=(e.right-e.left)/r.offsetWidth;return{style:`${c}: ${h/g}px; max-width: ${u/y}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":a?"left":"right")}}const Ia=z.define();function Ey(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let a=t.displayLabel||t.label,l=0;for(let c=0;cl&&o.appendChild(document.createTextNode(a.slice(l,h)));let f=o.appendChild(document.createElement("span"));f.appendChild(document.createTextNode(a.slice(h,u))),f.className="cm-completionMatchedText",l=u}return lt.position-i.position).map(t=>t.render)}function eo(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.ceil((n-e)/t);return{from:n-i*t,to:n-(i-1)*t}}class Uy{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,a=e.state.facet(Ke);this.optionContent=Ey(a),this.optionClass=a.optionClass,this.tooltipClass=a.tooltipClass,this.range=eo(r.length,o,a.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=e.state.field(t).open;for(let h=l.target,u;h&&h!=this.dom;h=h.parentNode)if(h.nodeName=="LI"&&(u=/-(\d+)$/.exec(h.id))&&+u[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;h!=null&&(e.dispatch({effects:Ia.of(h)}),l.preventDefault())}}),this.dom.addEventListener("focusout",l=>{let c=e.state.field(this.stateField,!1);c&&c.tooltip&&e.state.facet(Ke).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:Rn.of(null)})}),this.showOptions(r,s.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:a}=i.open;(!s.open||s.open.options!=r)&&(this.range=eo(r.length,o,e.state.facet(Ke).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),a!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected=this.range.to)&&(this.range=eo(t.options.length,t.selected,this.view.state.facet(Ke).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(a=>{a&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(a,s)}).catch(a=>ze(this.view.state,a,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&Dy(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;oi.from||i.from==0))if(r=f,typeof c!="string"&&c.header)s.appendChild(c.header(c));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=f}}const h=s.appendChild(document.createElement("li"));h.id=t+"-"+o,h.setAttribute("role","option");let u=this.optionClass(a);u&&(h.className=u);for(let f of this.optionContent){let d=f(a,this.view.state,this.view,l);d&&h.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.tonew Uy(t,n,e)}function Dy(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.topt.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function Fc(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function Ly(n,e){let t=[],i=null,s=null,r=h=>{t.push(h);let{section:u}=h.completion;if(u){i||(i=[]);let f=typeof u=="string"?u:u.name;i.some(d=>d.name==f)||i.push(typeof u=="string"?{name:f}:u)}},o=e.facet(Ke);for(let h of n)if(h.hasResult()){let u=h.result.getMatch;if(h.result.filter===!1)for(let f of h.result.options)r(new Mc(f,h.source,u?u(f):[],1e9-t.length));else{let f=e.sliceDoc(h.from,h.to),d,p=o.filterStrict?new Zy(f):new Ky(f);for(let m of h.result.options)if(d=p.match(m.label)){let g=m.displayLabel?u?u(m,d.matched):[]:d.matched,y=d.score+(m.boost||0);if(r(new Mc(m,h.source,g,y)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:b}=m.section;s||(s=Object.create(null)),s[b]=Math.max(y,s[b]||-1e9)}}}}if(i){let h=Object.create(null),u=0,f=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.namef.score-u.score||c(u.completion,f.completion))){let u=h.completion;!l||l.label!=u.label||l.detail!=u.detail||l.type!=null&&u.type!=null&&l.type!=u.type||l.apply!=u.apply||l.boost!=u.boost?a.push(h):Fc(h.completion)>Fc(l)&&(a[a.length-1]=h),l=h.completion}return a}class Ki{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new Ki(this.options,Dc(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(c=>c.isPending))return s.setDisabled();let a=Ly(e,t);if(!a.length)return s&&e.some(c=>c.isPending)?s.setDisabled():null;let l=t.facet(Ke).selectOnOpen?0:-1;if(s&&s.selected!=l&&s.selected!=-1){let c=s.options[s.selected].completion;for(let h=0;hh.hasResult()?Math.min(c,h.from):c,1e8),create:zy,above:r.aboveCursor},s?s.timestamp:Date.now(),l,!1)}map(e){return new Ki(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Ki(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class Ys{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Ys(Wy,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(Ke),r=(i.override||t.languageDataAt("autocomplete",yi(t)).map($y)).map(l=>(this.active.find(h=>h.source==l)||new ut(l,this.active.some(h=>h.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((l,c)=>l==this.active[c])&&(r=this.active);let o=this.open,a=e.effects.some(l=>l.is(Wa));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!Xy(r,this.active)||a?o=Ki.build(r,t,this.id,o,i,a):o&&o.disabled&&!r.some(l=>l.isPending)&&(o=null),!o&&r.every(l=>!l.isPending)&&r.some(l=>l.hasResult())&&(r=r.map(l=>l.hasResult()?new ut(l.source,0):l));for(let l of e.effects)l.is(Ia)&&(o=o&&o.setSelected(l.value,this.id));return r==this.active&&o==this.open?this:new Ys(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?By:Iy}}function Xy(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}const Wy=[];function Hf(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(Ba);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}class ut{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=Hf(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new ut(s.source,0)),i&4&&s.state==0&&(s=new ut(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(js))s=new ut(s.source,1,r.value);else if(r.is(Rn))s=new ut(s.source,0);else if(r.is(Wa))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(yi(e.state))}}class Fi extends ut{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),a=yi(e.state);if(a>o||!s||t&2&&(yi(e.startState)==this.from||at.map(e))}}),He=Te.define({create(){return Ys.start()},update(n,e){return n.update(e)},provide:n=>[gr.from(n,e=>e.tooltip),$.contentAttributes.from(n,e=>e.attrs)]});function qa(n,e){const t=e.completion.apply||e.completion.label;let i=n.state.field(He).active.find(s=>s.source==e.source);return i instanceof Fi?(typeof t=="string"?n.dispatch({...Ry(n.state,t,i.from,i.to),annotations:Ba.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}const zy=Fy(He,qa);function us(n,e="option"){return t=>{let i=t.state.field(He,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+s*(n?1:-1):n?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:Ia.of(a)}),!0}}const Vy=n=>{let e=n.state.field(He,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampn.state.field(He,!1)?(n.dispatch({effects:js.of(!0)}),!0):!1,jy=n=>{let e=n.state.field(He,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Rn.of(null)}),!0)};class Yy{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const Ny=50,Hy=1e3,Gy=xe.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(He).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(He),t=n.state.facet(Ke);if(!n.selectionSet&&!n.docChanged&&n.startState.field(He)==e)return;let i=n.transactions.some(r=>{let o=Hf(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;rNy&&Date.now()-o.time>Hy){for(let a of o.context.abortListeners)try{a()}catch(l){ze(this.view.state,l)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(js)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(He);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=yi(e),i=new jf(e,t,n.explicit,this.view),s=new Yy(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:Rn.of(null)}),ze(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(Ke),i=this.view.state.field(He);for(let s=0;sa.source==r.active.source);if(o&&o.isPending)if(r.done==null){let a=new ut(r.active.source,0);for(let l of r.updates)a=a.update(l,t);a.isPending||e.push(a)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:Wa.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(He,!1);if(e&&e.tooltip&&this.view.state.facet(Ke).closeOnBlur){let t=e.open&&Uu(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Rn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:js.of(!1)}),20),this.composing=0}}}),_y=typeof navigator=="object"&&/Win/.test(navigator.platform),Jy=ri.highest($.domEventHandlers({keydown(n,e){let t=e.state.field(He,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(_y&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&qa(e,i),!1}})),Gf=$.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class eA{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}}class za{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,De.TrackDel),i=e.mapPos(this.to,1,De.TrackDel);return t==null||i==null?null:new za(this.field,t,i)}}class Va{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let l of this.lines){if(i.length){let c=o,h=/^\t*/.exec(l)[0].length;for(let u=0;unew za(l.field,s[l.line]+l.from,s[l.line]+l.to));return{text:i,ranges:a}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let a=r[1]?+r[1]:null,l=r[2]||r[3]||"",c=-1;a===0&&(a=1e9);let h=l.replace(/\\[{}]/g,u=>u[1]);for(let u=0;u=c&&f.field++}for(let u of s)if(u.line==i.length&&u.from>r.index){let f=r[2]?3+(r[1]||"").length:2;u.from-=f,u.to-=f}s.push(new eA(c,i.length,r.index,r.index+h.length)),o=o.slice(0,r.index)+l+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(a,l,c)=>{for(let h of s)h.line==i.length&&h.from>c&&(h.from--,h.to--);return l}),i.push(o)}return new Va(i,s)}}let tA=B.widget({widget:new class extends Ut{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),iA=B.mark({class:"cm-snippetField"});class en{constructor(e,t){this.ranges=e,this.active=t,this.deco=B.set(e.map(i=>(i.from==i.to?tA:iA).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new en(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const In=z.define({map(n,e){return n&&n.map(e)}}),nA=z.define(),$n=Te.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(In))return t.value;if(t.is(nA)&&n)return new en(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>$.decorations.from(n,e=>e?e.deco:B.none)});function ja(n,e){return A.create(n.filter(t=>t.field==e).map(t=>A.range(t.from,t.to)))}function sA(n){let e=Va.parse(n);return(t,i,s,r)=>{let{text:o,ranges:a}=e.instantiate(t.state,s),{main:l}=t.state.selection,c={changes:{from:s,to:r==l.from?l.to:r,insert:se.of(o)},scrollIntoView:!0,annotations:i?[Ba.of(i),Pe.userEvent.of("input.complete")]:void 0};if(a.length&&(c.selection=ja(a,0)),a.some(h=>h.field>0)){let h=new en(a,0),u=c.effects=[In.of(h)];t.state.field($n,!1)===void 0&&u.push(z.appendConfig.of([$n,cA,hA,Gf]))}t.dispatch(t.state.update(c))}}function _f(n){return({state:e,dispatch:t})=>{let i=e.field($n,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:ja(i.ranges,s),effects:In.of(r?null:new en(i.ranges,s)),scrollIntoView:!0})),!0}}const rA=({state:n,dispatch:e})=>n.field($n,!1)?(e(n.update({effects:In.of(null)})),!0):!1,oA=_f(1),aA=_f(-1),lA=[{key:"Tab",run:oA,shift:aA},{key:"Escape",run:rA}],Lc=K.define({combine(n){return n.length?n[0]:lA}}),cA=ri.highest(mr.compute([Lc],n=>n.facet(Lc)));function Ye(n,e){return{...e,apply:sA(n)}}const hA=$.domEventHandlers({mousedown(n,e){let t=e.state.field($n,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:ja(t.ranges,s.field),effects:In.of(t.ranges.some(r=>r.field>s.field)?new en(t.ranges,s.field):null),scrollIntoView:!0}),!0)}}),Kn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},mi=z.define({map(n,e){let t=e.mapPos(n,-1,De.TrackAfter);return t??void 0}}),Ya=new class extends Jt{};Ya.startSide=1;Ya.endSide=-1;const Jf=Te.define({create(){return N.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(mi)&&(n=n.update({add:[Ya.range(t.value,t.value+1)]}));return n}});function uA(){return[dA,Jf]}const io="()[]{}<>«»»«[]{}";function ed(n){for(let e=0;e{if((fA?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Qt(Ne(i,0))==1||e!=s.from||t!=s.to)return!1;let r=gA(n.state,i);return r?(n.dispatch(r),!0):!1}),pA=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=td(n,n.selection.main.head).brackets||Kn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let a=OA(n.doc,o.head);for(let l of i)if(l==a&&kr(n.doc,o.head)==ed(Ne(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:A.cursor(o.head-l.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},mA=[{key:"Backspace",run:pA}];function gA(n,e){let t=td(n,n.selection.main.head),i=t.brackets||Kn.brackets;for(let s of i){let r=ed(Ne(s,0));if(e==s)return r==s?bA(n,s,i.indexOf(s+s+s)>-1,t):yA(n,s,r,t.before||Kn.before);if(e==r&&id(n,n.selection.main.from))return AA(n,s,r)}return null}function id(n,e){let t=!1;return n.field(Jf).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function kr(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Qt(Ne(t,0)))}function OA(n,e){let t=n.sliceString(e-2,e);return Qt(Ne(t,0))==t.length?t:t.slice(1)}function yA(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:mi.of(o.to+e.length),range:A.range(o.anchor+e.length,o.head+e.length)};let a=kr(n.doc,o.head);return!a||/\s/.test(a)||i.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:mi.of(o.head+e.length),range:A.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function AA(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&kr(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:A.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function bA(n,e,t,i){let s=i.stringPrefixes||Kn.stringPrefixes,r=null,o=n.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:mi.of(a.to+e.length),range:A.range(a.anchor+e.length,a.head+e.length)};let l=a.head,c=kr(n.doc,l),h;if(c==e){if(Xc(n,l))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(id(n,l)){let f=t&&n.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+f.length,insert:f},range:A.cursor(l+f.length)}}}else{if(t&&n.sliceDoc(l-2*e.length,l)==e+e&&(h=Bc(n,l-2*e.length,s))>-1&&Xc(n,h))return{changes:{insert:e+e+e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(n.charCategorizer(l)(c)!=ye.Word&&Bc(n,l,s)>-1&&!SA(n,l,e,s))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)}}return{range:r=a}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function Xc(n,e){let t=Ce(n).resolveInner(e+1);return t.parent&&t.from==e}function SA(n,e,t,i){let s=Ce(n).resolveInner(e,-1),r=i.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),l=a.indexOf(t);if(!l||l>-1&&i.indexOf(a.slice(0,l))>-1){let h=s.firstChild;for(;h&&h.from==s.from&&h.to-h.from>t.length+l;){if(n.sliceDoc(h.to-t.length,h.to)==t)return!1;h=h.firstChild}return!0}let c=s.to==e&&s.parent;if(!c)break;s=c}return!1}function Bc(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=ye.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=ye.Word)return r}return-1}function xA(n={}){return[Jy,He,Ke.of(n),Gy,vA,Gf]}const nd=[{key:"Ctrl-Space",run:to},{mac:"Alt-`",run:to},{mac:"Alt-i",run:to},{key:"Escape",run:jy},{key:"ArrowDown",run:us(!0)},{key:"ArrowUp",run:us(!1)},{key:"PageDown",run:us(!0,"page")},{key:"PageUp",run:us(!1,"page")},{key:"Enter",run:Vy}],vA=ri.highest(mr.computeN([Ke],n=>n.facet(Ke).defaultKeymap?[nd]:[]));var Ic={};class Ns{constructor(e,t,i,s,r,o,a,l,c,h=0,u){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=a,this.bufferBase=l,this.curContext=c,this.lookAhead=h,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new Ns(e,[],t,i,i,0,[],0,s?new Wc(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(c==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=h):this.p.lastBigReductionSizel;)this.stack.pop();this.reduceContext(s,c)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let a=!1;for(let l=o;l>0&&this.buffer[l-2]>i;l-=4)if(this.buffer[l-1]>=0){a=!0;break}if(a)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let a=o.stateFlag(r,1);!a&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,a?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new Ns(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new wA(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;rl&1&&a==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let a=(o>>19)-r;if(a>1){let l=o&65535,c=this.stack.length-a*3;if(c>=0&&e.getGoto(this.stack[c],l,!1)>=0)return a<<19|65536|l}}else{let a=i(o,r+1);if(a!=null)return a}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}}class Wc{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class wA{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}}class Hs{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new Hs(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new Hs(this.stack,this.pos,this.index)}}function dn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),r+=l,a)break;r*=46}t?t[s++]=r:t=new e(r)}return t}class ks{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const qc=new ks;class kA{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=qc,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&ia.to&&(this.chunk2=this.chunk2.slice(0,a.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=qc,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}}class Di{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;sd(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}Di.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class sa{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?dn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(sd(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}}sa.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class Wn{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function sd(n,e,t,i,s,r){let o=0,a=1<0){let p=n[d];if(l.allows(p)&&(e.token.value==-1||e.token.value==p||QA(p,e.token.value,s,r))){e.acceptToken(p);break}}let h=e.next,u=0,f=n[o+2];if(e.next<0&&f>u&&n[c+f*3-3]==65535){o=n[c+f*3-1];continue e}for(;u>1,p=c+d+(d<<1),m=n[p],g=n[p+1]||65536;if(h=g)u=d+1;else{o=n[p+2],e.advance();continue e}}break}}function zc(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function QA(n,e,t,i){let s=zc(t,i,e);return s<0||zc(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class PA{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Vc(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Vc(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof ke){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}}class CA{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new ks)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let c=0;cu.end+25&&(l=Math.max(u.lookAhead,l)),u.value!=0)){let f=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!h.extend&&(i=u,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!i&&e.pos==this.stream.end&&(i=new ks,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new ks,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(a>>1)){(a&1)==0?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new PA(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(a);else{if(this.advanceStack(a,i,e))continue;{s||(s=[],r=[]),s.push(a);let l=this.tokens.getMainToken(a);r.push(l.value,l.end)}}break}}if(!i.length){let o=s&&KA(s);if(o)return nt&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw nt&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return nt&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((a,l)=>l.score-a.score);i.length>o;)i.pop();i.some(a=>a.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&c.buffer.length>500)if((a.score-c.score||a.buffer.length-c.buffer.length)>0)i.splice(l--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,a)=>a.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let c=e.curContext&&e.curContext.tracker.strict,h=c?e.curContext.hash:0;for(let u=this.fragments.nodeAt(s);u;){let f=this.parser.nodeSet.types[u.type.id]==u.type?r.getGoto(e.state,u.type.id):-1;if(f>-1&&u.length&&(!c||(u.prop(G.contextHash)||0)==h))return e.useNode(u,f),nt&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(u.type.id)})`),!0;if(!(u instanceof ke)||u.children.length==0||u.positions[0]>0)break;let d=u.children[0];if(d instanceof ke&&u.positions[0]==0)u=d;else break}}let a=r.stateSlot(e.state,4);if(a>0)return e.reduce(a),nt&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(a&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let c=0;cs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return jc(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(a.deadEnd&&(r||(r=!0,a.restart(),nt&&console.log(h+this.stackID(a)+" (restarted)"),this.advanceFully(a,i))))continue;let u=a.split(),f=h;for(let d=0;d<10&&u.forceReduce()&&(nt&&console.log(f+this.stackID(u)+" (via force-reduce)"),!this.advanceFully(u,i));d++)nt&&(f=this.stackID(u)+" -> ");for(let d of a.recoverByInsert(l))nt&&console.log(h+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>a.pos?(c==a.pos&&(c++,l=0),a.recoverByDelete(l,c),nt&&console.log(h+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),jc(a,i)):(!s||s.scoren;class $A{constructor(e){this.start=e.start,this.shift=e.shift||so,this.reduce=e.reduce||so,this.reuse=e.reuse||so,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Gs extends Yu{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;ae.topRules[a][1]),s=[];for(let a=0;a=0)r(h,l,a[c++]);else{let u=a[c+-h];for(let f=-h;f>0;f--)r(a[c++],l,u);c++}}}this.nodeSet=new Ta(t.map((a,l)=>et.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:s[l],top:i.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=qu;let o=dn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;atypeof a=="number"?new Di(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new TA(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],a=o&1,l=s[r++];if(a&&i)return l;for(let c=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Ft(this.data,r+2);else break;s=t(Ft(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Ft(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(Gs.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(a=>a.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=Yc(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}const ZA=316,MA=317,Nc=1,EA=2,UA=3,FA=4,DA=318,LA=320,XA=321,BA=5,IA=6,WA=0,ra=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],rd=125,qA=59,oa=47,zA=42,VA=43,jA=45,YA=60,NA=44,HA=63,GA=46,_A=91,JA=new $A({start:!1,shift(n,e){return e==BA||e==IA||e==LA?n:e==XA},strict:!1}),eb=new Wn((n,e)=>{let{next:t}=n;(t==rd||t==-1||e.context)&&n.acceptToken(DA)},{contextual:!0,fallback:!0}),tb=new Wn((n,e)=>{let{next:t}=n,i;ra.indexOf(t)>-1||t==oa&&((i=n.peek(1))==oa||i==zA)||t!=rd&&t!=qA&&t!=-1&&!e.context&&n.acceptToken(ZA)},{contextual:!0}),ib=new Wn((n,e)=>{n.next==_A&&!e.context&&n.acceptToken(MA)},{contextual:!0}),nb=new Wn((n,e)=>{let{next:t}=n;if(t==VA||t==jA){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(Nc);n.acceptToken(i?Nc:EA)}}else t==HA&&n.peek(1)==GA&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(UA))},{contextual:!0});function ro(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}const sb=new Wn((n,e)=>{if(n.next!=YA||!e.dialectEnabled(WA)||(n.advance(),n.next==oa))return;let t=0;for(;ra.indexOf(n.next)>-1;)n.advance(),t++;if(ro(n.next,!0)){for(n.advance(),t++;ro(n.next,!1);)n.advance(),t++;for(;ra.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==NA)return;for(let i=0;;i++){if(i==7){if(!ro(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(FA,-t)}),rb=Nu({"get set async static":O.modifier,"for while do if else switch try catch finally return throw break continue default case defer":O.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":O.operatorKeyword,"let var const using function class extends":O.definitionKeyword,"import export from":O.moduleKeyword,"with debugger new":O.keyword,TemplateString:O.special(O.string),super:O.atom,BooleanLiteral:O.bool,this:O.self,null:O.null,Star:O.modifier,VariableName:O.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":O.function(O.variableName),VariableDefinition:O.definition(O.variableName),Label:O.labelName,PropertyName:O.propertyName,PrivatePropertyName:O.special(O.propertyName),"CallExpression/MemberExpression/PropertyName":O.function(O.propertyName),"FunctionDeclaration/VariableDefinition":O.function(O.definition(O.variableName)),"ClassDeclaration/VariableDefinition":O.definition(O.className),"NewExpression/VariableName":O.className,PropertyDefinition:O.definition(O.propertyName),PrivatePropertyDefinition:O.definition(O.special(O.propertyName)),UpdateOp:O.updateOperator,"LineComment Hashbang":O.lineComment,BlockComment:O.blockComment,Number:O.number,String:O.string,Escape:O.escape,ArithOp:O.arithmeticOperator,LogicOp:O.logicOperator,BitOp:O.bitwiseOperator,CompareOp:O.compareOperator,RegExp:O.regexp,Equals:O.definitionOperator,Arrow:O.function(O.punctuation),": Spread":O.punctuation,"( )":O.paren,"[ ]":O.squareBracket,"{ }":O.brace,"InterpolationStart InterpolationEnd":O.special(O.brace),".":O.derefOperator,", ;":O.separator,"@":O.meta,TypeName:O.typeName,TypeDefinition:O.definition(O.typeName),"type enum interface implements namespace module declare":O.definitionKeyword,"abstract global Privacy readonly override":O.modifier,"is keyof unique infer asserts":O.operatorKeyword,JSXAttributeValue:O.attributeValue,JSXText:O.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":O.angleBracket,"JSXIdentifier JSXNameSpacedName":O.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":O.attributeName,"JSXBuiltin/JSXIdentifier":O.standard(O.tagName)}),ob={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,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)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.lPQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.nSR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:JA,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[rb],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$*T!b!c$,r!c!}Er!}#O$-|#O#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_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new sa("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>ob[n]||-1},{term:343,get:n=>ab[n]||-1},{term:95,get:n=>lb[n]||-1}],tokenPrec:15201}),od=[Ye("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ye("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ye("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ye("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ye("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ye(`try { +`){[e,t]=Bi(this,e,t);let s="";for(let r=0,o=0;re&&r&&(s+=i),eo&&(s+=a.sliceString(e-o,t-o,i)),o=l+1}return s}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof kt))return 0;let i=0,[s,r,o,a]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;s+=t,r+=t){if(s==o||r==a)return i;let l=this.children[s],c=e.children[r];if(l!=c)return i+l.scanIdentical(c,t);i+=l.length+1}}static from(e,t=e.reduce((i,s)=>i+s.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new we(d,t)}let s=Math.max(32,i>>5),r=s<<1,o=s>>1,a=[],l=0,c=-1,h=[];function u(d){let p;if(d.lines>r&&d instanceof kt)for(let m of d.children)u(m);else d.lines>o&&(l>o||!l)?(f(),a.push(d)):d instanceof we&&l&&(p=h[h.length-1])instanceof we&&d.lines+p.lines<=32?(l+=d.lines,c+=d.length+1,h[h.length-1]=new we(p.text.concat(d.text),p.length+1+d.length)):(l+d.lines>s&&f(),l+=d.lines,c+=d.length+1,h.push(d))}function f(){l!=0&&(a.push(h.length==1?h[0]:kt.from(h,c)),c=-1,l=h.length=0)}for(let d of e)u(d);return f(),a.length==1?a[0]:new kt(a,t)}}se.empty=new we([""],0);function sp(n){let e=-1;for(let t of n)e+=t.length+1;return e}function ys(n,e,t=0,i=1e9){for(let s=0,r=0,o=!0;r=t&&(l>i&&(a=a.slice(0,i-s)),s0?1:(e instanceof we?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,s=this.nodes[i],r=this.offsets[i],o=r>>1,a=s instanceof we?s.text.length:s.children.length;if(o==(t>0?a:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(s instanceof we){let l=s.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=s.children[o+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof we?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class vh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new pn(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:s}=this.cursor.next(e);return this.pos+=(s.length+e)*t,this.value=s.length<=i?s:t<0?s.slice(s.length-i):s.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class wh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:s}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=s,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(se.prototype[Symbol.iterator]=function(){return this.iter()},pn.prototype[Symbol.iterator]=vh.prototype[Symbol.iterator]=wh.prototype[Symbol.iterator]=function(){return this});class rp{constructor(e,t,i,s){this.from=e,this.to=t,this.number=i,this.text=s}get length(){return this.to-this.from}}function Bi(n,e,t){return e=Math.max(0,Math.min(n.length,e)),[e,Math.max(e,Math.min(n.length,t))]}function Ze(n,e,t=!0,i=!0){return ip(n,e,t,i)}function op(n){return n>=56320&&n<57344}function ap(n){return n>=55296&&n<56320}function Ne(n,e){let t=n.charCodeAt(e);if(!ap(t)||e+1==n.length)return t;let i=n.charCodeAt(e+1);return op(i)?(t-55296<<10)+(i-56320)+65536:t}function ma(n){return n<=65535?String.fromCharCode(n):(n-=65536,String.fromCharCode((n>>10)+55296,(n&1023)+56320))}function Qt(n){return n<65536?1:2}const Oo=/\r\n?|\n/;var De=(function(n){return n[n.Simple=0]="Simple",n[n.TrackDel=1]="TrackDel",n[n.TrackBefore=2]="TrackBefore",n[n.TrackAfter=3]="TrackAfter",n})(De||(De={}));class Zt{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-s);r+=a}else{if(i!=De.Simple&&c>=e&&(i==De.TrackDel&&se||i==De.TrackBefore&&se))return null;if(c>e||c==e&&t<0&&!a)return e==s||t<0?r:r+l;r+=l}s=c}if(e>s)throw new RangeError(`Position ${e} is out of range for changeset of length ${s}`);return r}touchesRange(e,t=e){for(let i=0,s=0;i=0&&s<=t&&a>=e)return st?"cover":!0;s=a}return!1}toString(){let e="";for(let t=0;t=0?":"+s:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Zt(e)}static create(e){return new Zt(e)}}class Re extends Zt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return yo(this,(t,i,s,r,o)=>e=e.replace(s,s+(i-t),o),!1),e}mapDesc(e,t=!1){return Ao(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let s=0,r=0;s=0){t[s]=a,t[s+1]=o;let l=s>>1;for(;i.length0&&Gt(i,t,r.text),r.forward(h),a+=h}let c=e[o++];for(;a>1].toJSON()))}return e}static of(e,t,i){let s=[],r=[],o=0,a=null;function l(h=!1){if(!h&&!s.length)return;of||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let p=d?typeof d=="string"?se.of(d.split(i||Oo)):d:se.empty,m=p.length;if(u==f&&m==0)return;uo&&Xe(s,u-o,-1),Xe(s,f-u,m),Gt(r,s,p),o=f}}return c(e),l(!a),a}static empty(e){return new Re(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let s=0;sa&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==n[s+1]?n[s]+=e:s>=0&&e==0&&n[s]==0?n[s+1]+=t:i?(n[s]+=e,n[s+1]+=t):n.push(e,t)}function Gt(n,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==n.sections.length||n.sections[o+1]<0);)a=n.sections[o++],l=n.sections[o++];e(s,c,r,h,u),s=c,r=h}}}function Ao(n,e,t,i=!1){let s=[],r=i?[]:null,o=new Sn(n),a=new Sn(e);for(let l=-1;;){if(o.done&&a.len||a.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&a.ins==-1){let c=Math.min(o.len,a.len);Xe(s,c,-1),o.forward(c),a.forward(c)}else if(a.ins>=0&&(o.ins<0||l==o.i||o.off==0&&(a.len=0&&l=0){let c=0,h=o.len;for(;h;)if(a.ins==-1){let u=Math.min(h,a.len);c+=u,h-=u,a.forward(u)}else if(a.ins==0&&a.lenl||o.ins>=0&&o.len>l)&&(a||i.length>c),r.forward2(l),o.forward(l)}}}}class Sn{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?se.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?se.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Nt{constructor(e,t,i,s){this.from=e,this.to=t,this.flags=i,this.goalColumn=s}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let i,s;return this.empty?i=s=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),s=e.mapPos(this.to,-1)),i==this.from&&s==this.to?this:new Nt(i,s,this.flags,this.goalColumn)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return A.range(e,t,void 0,void 0,i);let s=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return A.range(this.anchor,s,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return A.range(e.anchor,e.head)}static create(e,t,i,s){return new Nt(e,t,i,s)}}class A{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:A.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new A(e.ranges.map(t=>Nt.fromJSON(t)),e.main)}static single(e,t=e){return new A([A.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,s=0;ss.from-r.from),t=e.indexOf(i);for(let s=1;sr.head?A.range(l,a):A.range(a,l))}}return new A(e,t)}}function Qh(n,e){for(let t of n.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let ga=0;class Z{constructor(e,t,i,s,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=s,this.id=ga++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new Z(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Oa),!!e.static,e.enables)}of(e){return new As([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new As(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new As(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Oa(n,e){return n==e||n.length==e.length&&n.every((t,i)=>t===e[i])}class As{constructor(e,t,i,s){this.dependencies=e,this.facet=t,this.type=i,this.value=s,this.id=ga++}dynamicSlot(e){var t;let i=this.value,s=this.facet.compareInput,r=this.id,o=e[r]>>1,a=this.type==2,l=!1,c=!1,h=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?c=!0:(((t=e[u.id])!==null&&t!==void 0?t:1)&1)==0&&h.push(e[u.id]);return{create(u){return u.values[o]=i(u),1},update(u,f){if(l&&f.docChanged||c&&(f.docChanged||f.selection)||bo(u,h)){let d=i(u);if(a?!ml(d,u.values[o],s):!s(d,u.values[o]))return u.values[o]=d,1}return 0},reconfigure:(u,f)=>{let d,p=f.config.address[r];if(p!=null){let m=Rs(f,p);if(this.dependencies.every(g=>g instanceof Z?f.facet(g)===u.facet(g):g instanceof Te?f.field(g,!1)==u.field(g,!1):!0)||(a?ml(d=i(u),m,s):s(d=i(u),m)))return u.values[o]=m,0}else d=i(u);return u.values[o]=d,1}}}get extension(){return this}}function ml(n,e,t){if(n.length!=e.length)return!1;for(let i=0;in[l.id]),s=t.map(l=>l.type),r=i.filter(l=>!(l&1)),o=n[e.id]>>1;function a(l){let c=[];for(let h=0;hi===s),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(jn).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,s)=>{let r=i.values[t],o=this.updateF(r,s);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,s)=>{let r=i.facet(jn),o=s.facet(jn),a;return(a=r.find(l=>l.field==this))&&a!=o.find(l=>l.field==this)?(i.values[t]=a.create(i),1):s.config.address[this.id]!=null?(i.values[t]=s.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,jn.of({field:this,create:e})]}get extension(){return this}}const fi={lowest:4,low:3,default:2,high:1,highest:0};function sn(n){return e=>new Ph(e,n)}const oi={highest:sn(fi.highest),high:sn(fi.high),default:sn(fi.default),low:sn(fi.low),lowest:sn(fi.lowest)};class Ph{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class Gi{of(e){return new So(this,e)}reconfigure(e){return Gi.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class So{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class Ts{constructor(e,t,i,s,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=s,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let s=[],r=Object.create(null),o=new Map;for(let f of cp(e,t,o))f instanceof Te?s.push(f):(r[f.facet.id]||(r[f.facet.id]=[])).push(f);let a=Object.create(null),l=[],c=[];for(let f of s)a[f.id]=c.length<<1,c.push(d=>f.slot(d));let h=i?.config.facets;for(let f in r){let d=r[f],p=d[0].facet,m=h&&h[f]||[];if(d.every(g=>g.type==0))if(a[p.id]=l.length<<1|1,Oa(m,d))l.push(i.facet(p));else{let g=p.combine(d.map(y=>y.value));l.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(a[g.id]=l.length<<1|1,l.push(g.value)):(a[g.id]=c.length<<1,c.push(y=>g.dynamicSlot(y)));a[p.id]=c.length<<1,c.push(g=>lp(g,p,d))}}let u=c.map(f=>f(a));return new Ts(e,o,u,a,l,r)}}function cp(n,e,t){let i=[[],[],[],[],[]],s=new Map;function r(o,a){let l=s.get(o);if(l!=null){if(l<=a)return;let c=i[l].indexOf(o);c>-1&&i[l].splice(c,1),o instanceof So&&t.delete(o.compartment)}if(s.set(o,a),Array.isArray(o))for(let c of o)r(c,a);else if(o instanceof So){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let c=e.get(o.compartment)||o.inner;t.set(o.compartment,c),r(c,a)}else if(o instanceof Ph)r(o.inner,o.prec);else if(o instanceof Te)i[a].push(o),o.provides&&r(o.provides,a);else if(o instanceof As)i[a].push(o),o.facet.extensions&&r(o.facet.extensions,fi.default);else{let c=o.extension;if(!c)throw new Error(`Unrecognized extension value in extension set (${o}).`);if(c==o)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(c,a)}}return r(n,fi.default),i.reduce((o,a)=>o.concat(a))}function mn(n,e){if(e&1)return 2;let t=e>>1,i=n.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;n.status[t]=4;let s=n.computeSlot(n,n.config.dynamicSlots[t]);return n.status[t]=2|s}function Rs(n,e){return e&1?n.config.staticValues[e>>1]:n.values[e>>1]}const Ch=Z.define(),xo=Z.define({combine:n=>n.some(e=>e),static:!0}),Th=Z.define({combine:n=>n.length?n[0]:void 0,static:!0}),Rh=Z.define(),$h=Z.define(),Kh=Z.define(),Zh=Z.define({combine:n=>n.length?n[0]:!1});class zt{constructor(e,t){this.type=e,this.value=t}static define(){return new hp}}class hp{of(e){return new zt(this,e)}}class up{constructor(e){this.map=e}of(e){return new Y(this,e)}}class Y{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new Y(this.type,t)}is(e){return this.type==e}static define(e={}){return new up(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let s of e){let r=s.map(t);r&&i.push(r)}return i}}Y.reconfigure=Y.define();Y.appendConfig=Y.define();class Pe{constructor(e,t,i,s,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=s,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Qh(i,t.newLength),r.some(a=>a.type==Pe.time)||(this.annotations=r.concat(Pe.time.of(Date.now())))}static create(e,t,i,s,r,o){return new Pe(e,t,i,s,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(Pe.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}Pe.time=zt.define();Pe.userEvent=zt.define();Pe.addToHistory=zt.define();Pe.remote=zt.define();function fp(n,e){let t=[];for(let i=0,s=0;;){let r,o;if(i=n[i]))r=n[i++],o=n[i++];else if(s=0;s--){let r=i[s](n);r instanceof Pe?n=r:Array.isArray(r)&&r.length==1&&r[0]instanceof Pe?n=r[0]:n=Eh(e,Zi(r),!1)}return n}function pp(n){let e=n.startState,t=e.facet(Kh),i=n;for(let s=t.length-1;s>=0;s--){let r=t[s](n);r&&Object.keys(r).length&&(i=Mh(i,vo(e,r,n.changes.newLength),!0))}return i==n?n:Pe.create(e,n.changes,n.selection,i.effects,i.annotations,i.scrollIntoView)}const mp=[];function Zi(n){return n==null?mp:Array.isArray(n)?n:[n]}var ye=(function(n){return n[n.Word=0]="Word",n[n.Space=1]="Space",n[n.Other=2]="Other",n})(ye||(ye={}));const gp=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let wo;try{wo=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function Op(n){if(wo)return wo.test(n);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||gp.test(t)))return!0}return!1}function yp(n){return e=>{if(!/\S/.test(e))return ye.Space;if(Op(e))return ye.Word;for(let t=0;t-1)return ye.Word;return ye.Other}}class J{constructor(e,t,i,s,r,o){this.config=e,this.doc=t,this.selection=i,this.values=s,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let a=0;as.set(c,l)),t=null),s.set(a.value.compartment,a.value.extension)):a.is(Y.reconfigure)?(t=null,i=a.value):a.is(Y.appendConfig)&&(t=null,i=Zi(i).concat(a.value));let r;t?r=e.startState.values.slice():(t=Ts.resolve(i,s,this),r=new J(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,c)=>c.reconfigure(l,this),null).values);let o=e.startState.facet(xo)?e.newSelection:e.newSelection.asSingle();new J(t,e.newDoc,o,r,(a,l)=>l.update(a,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:A.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),s=this.changes(i.changes),r=[i.range],o=Zi(i.effects);for(let a=1;ao.spec.fromJSON(a,l)))}}return J.create({doc:e.doc,selection:A.fromJSON(e.selection),extensions:t.extensions?s.concat([t.extensions]):s})}static create(e={}){let t=Ts.resolve(e.extensions||[],new Map),i=e.doc instanceof se?e.doc:se.of((e.doc||"").split(t.staticFacet(J.lineSeparator)||Oo)),s=e.selection?e.selection instanceof A?e.selection:A.single(e.selection.anchor,e.selection.head):A.single(0);return Qh(s,i.length),t.staticFacet(xo)||(s=s.asSingle()),new J(t,i,s,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(J.tabSize)}get lineBreak(){return this.facet(J.lineSeparator)||` +`}get readOnly(){return this.facet(Zh)}phrase(e,...t){for(let i of this.facet(J.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,s)=>{if(s=="$")return"$";let r=+(s||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let s=[];for(let r of this.facet(Ch))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&s.push(o[e]);return s}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return yp(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:s}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,a=e-i;for(;o>0;){let l=Ze(t,o,!1);if(r(t.slice(l,o))!=ye.Word)break;o=l}for(;an.length?n[0]:4});J.lineSeparator=Th;J.readOnly=Zh;J.phrases=Z.define({compare(n,e){let t=Object.keys(n),i=Object.keys(e);return t.length==i.length&&t.every(s=>n[s]==e[s])}});J.languageData=Ch;J.changeFilter=Rh;J.transactionFilter=$h;J.transactionExtender=Kh;Gi.reconfigure=Y.define();function yt(n,e,t={}){let i={};for(let s of n)for(let r of Object.keys(s)){let o=s[r],a=i[r];if(a===void 0)i[r]=o;else if(!(a===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](a,o);else throw new Error("Config merge conflict for field "+r)}for(let s in e)i[s]===void 0&&(i[s]=e[s]);return i}class ei{eq(e){return this==e}range(e,t=e){return ko.create(e,t,this)}}ei.prototype.startSide=ei.prototype.endSide=0;ei.prototype.point=!1;ei.prototype.mapMode=De.TrackDel;function ya(n,e){return n==e||n.constructor==e.constructor&&n.eq(e)}let ko=class Uh{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new Uh(e,t,i)}};function Qo(n,e){return n.from-e.from||n.value.startSide-e.value.startSide}class Aa{constructor(e,t,i,s){this.from=e,this.to=t,this.value=i,this.maxPoint=s}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,s=0){let r=i?this.to:this.from;for(let o=s,a=r.length;;){if(o==a)return o;let l=o+a>>1,c=r[l]-e||(i?this.value[l].endSide:this.value[l].startSide)-t;if(l==o)return c>=0?o:a;c>=0?a=l:o=l+1}}between(e,t,i,s){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||f==d&&c.startSide>0&&c.endSide<=0)continue;(d-f||c.endSide-c.startSide)<0||(o<0&&(o=f),c.point&&(a=Math.max(a,d-f)),i.push(c),s.push(f-o),r.push(d-o))}return{mapped:i.length?new Aa(s,r,i,a):null,pos:o}}}class H{constructor(e,t,i,s){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=s}static create(e,t,i,s){return new H(e,t,i,s)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:s=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Qo)),this.isEmpty)return t.length?H.of(t):this;let a=new Fh(this,null,-1).goto(0),l=0,c=[],h=new It;for(;a.value||l=0){let u=t[l++];h.addInner(u.from,u.to,u.value)||c.push(u)}else a.rangeIndex==1&&a.chunkIndexthis.chunkEnd(a.chunkIndex)||ra.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return xn.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return xn.from(e).goto(t)}static compare(e,t,i,s,r=-1){let o=e.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),a=t.filter(u=>u.maxPoint>0||!u.isEmpty&&u.maxPoint>=r),l=gl(o,a,i),c=new rn(o,l,r),h=new rn(a,l,r);i.iterGaps((u,f,d)=>Ol(c,u,h,f,d,s)),i.empty&&i.length==0&&Ol(c,0,h,0,0,s)}static eq(e,t,i=0,s){s==null&&(s=999999999);let r=e.filter(h=>!h.isEmpty&&t.indexOf(h)<0),o=t.filter(h=>!h.isEmpty&&e.indexOf(h)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let a=gl(r,o),l=new rn(r,a,0).goto(i),c=new rn(o,a,0).goto(i);for(;;){if(l.to!=c.to||!Po(l.active,c.active)||l.point&&(!c.point||!ya(l.point,c.point)))return!1;if(l.to>s)return!0;l.next(),c.next()}}static spans(e,t,i,s,r=-1){let o=new rn(e,null,r).goto(t),a=t,l=o.openStart;for(;;){let c=Math.min(o.to,i);if(o.point){let h=o.activeForPoint(o.to),u=o.pointFroma&&(s.span(a,c,o.active,l),l=o.openEnd(c));if(o.to>i)return l+(o.point&&o.to>i?1:0);a=o.to,o.next()}}static of(e,t=!1){let i=new It;for(let s of e instanceof ko?[e]:t?Ap(e):e)i.add(s.from,s.to,s.value);return i.finish()}static join(e){if(!e.length)return H.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let s=e[i];s!=H.empty;s=s.nextLayer)t=new H(s.chunkPos,s.chunk,t,Math.max(s.maxPoint,t.maxPoint));return t}}H.empty=new H([],[],null,-1);function Ap(n){if(n.length>1)for(let e=n[0],t=1;t0)return n.slice().sort(Qo);e=i}return n}H.empty.nextLayer=H.empty;class It{finishChunk(e){this.chunks.push(new Aa(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new It)).add(e,t,i)}addInner(e,t,i){let s=e-this.lastTo||i.startSide-this.last.endSide;if(s<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return s<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(H.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=H.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function gl(n,e,t){let i=new Map;for(let r of n)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&s.push(new Fh(o,t,i,r));return s.length==1?s[0]:new xn(s)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Kr(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Kr(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Kr(this.heap,0)}}}function Kr(n,e){for(let t=n[e];;){let i=(e<<1)+1;if(i>=n.length)break;let s=n[i];if(i+1=0&&(s=n[i+1],i++),t.compare(s)<0)break;n[i]=t,n[e]=s,e=i}}class rn{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=xn.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){Yn(this.active,e),Yn(this.activeTo,e),Yn(this.activeRank,e),this.minActive=yl(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:s,rank:r}=this.cursor;for(;t0;)t++;Nn(this.active,t,i),Nn(this.activeTo,t,s),Nn(this.activeRank,t,r),e&&Nn(e,t,this.cursor.from),this.minActive=yl(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let s=this.minActive;if(s>-1&&(this.activeTo[s]-this.cursor.from||this.active[s].endSide-this.cursor.startSide)<0){if(this.activeTo[s]>e){this.to=this.activeTo[s],this.endSide=this.active[s].endSide;break}this.removeActive(s),i&&Yn(i,s)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[s]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function Ol(n,e,t,i,s,r){n.goto(e),t.goto(i);let o=i+s,a=i,l=i-e,c=!!r.boundChange;for(let h=!1;;){let u=n.to+l-t.to,f=u||n.endSide-t.endSide,d=f<0?n.to+l:t.to,p=Math.min(d,o);if(n.point||t.point?(n.point&&t.point&&ya(n.point,t.point)&&Po(n.activeForPoint(n.to),t.activeForPoint(t.to))||r.comparePoint(a,p,n.point,t.point),h=!1):(h&&r.boundChange(a),p>a&&!Po(n.active,t.active)&&r.compareRange(a,p,n.active,t.active),c&&po)break;a=d,f<=0&&n.next(),f>=0&&t.next()}}function Po(n,e){if(n.length!=e.length)return!1;for(let t=0;t=e;i--)n[i+1]=n[i];n[e]=t}function yl(n,e){let t=-1,i=1e9;for(let s=0;s=e)return s;if(s==n.length)break;r+=n.charCodeAt(s)==9?t-r%t:1,s=Ze(n,s)}return i===!0?-1:n.length}const To="ͼ",Al=typeof Symbol>"u"?"__"+To:Symbol.for(To),Ro=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),bl=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class ti{constructor(e,t){this.rules=[];let{finish:i}=t||{};function s(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,a,l,c){let h=[],u=/^@(\w+)\b/.exec(o[0]),f=u&&u[1]=="keyframes";if(u&&a==null)return l.push(o[0]+";");for(let d in a){let p=a[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,l);else if(p&&typeof p=="object"){if(!u)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(s(d),p,h,f)}else p!=null&&h.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(h.length||f)&&l.push((i&&!u&&!c?o.map(i):o).join(", ")+" {"+h.join(" ")+"}")}for(let o in e)r(s(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=bl[Al]||1;return bl[Al]=e+1,To+e.toString(36)}static mount(e,t,i){let s=e[Ro],r=i&&i.nonce;s?r&&s.setNonce(r):s=new bp(e,r),s.mount(Array.isArray(t)?t:[t],e)}}let Sl=new Map;class bp{constructor(e,t){let i=e.ownerDocument||e,s=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&s.CSSStyleSheet){let r=Sl.get(i);if(r)return e[Ro]=r;this.sheet=new s.CSSStyleSheet,Sl.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[Ro]=this}mount(e,t){let i=this.sheet,s=0,r=0;for(let o=0;o-1&&(this.modules.splice(l,1),r--,l=-1),l==-1){if(this.modules.splice(r++,0,a),i)for(let c=0;c",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"',229:"Q"},xl=typeof navigator<"u"&&/Chrome\/(\d+)/.exec(navigator.userAgent),Sp=typeof navigator<"u"&&/Apple Computer/.test(navigator.vendor),xp=typeof navigator<"u"&&/Gecko\/\d+/.test(navigator.userAgent),vl=typeof navigator<"u"&&/Mac/.test(navigator.platform),vp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),wp=xl&&(vl||+xl[1]<57)||xp&&vl;for(var Fe=0;Fe<10;Fe++)ii[48+Fe]=ii[96+Fe]=String(Fe);for(var Fe=1;Fe<=24;Fe++)ii[Fe+111]="F"+Fe;for(var Fe=65;Fe<=90;Fe++)ii[Fe]=String.fromCharCode(Fe+32),vn[Fe]=String.fromCharCode(Fe);for(var Zr in ii)vn.hasOwnProperty(Zr)||(vn[Zr]=ii[Zr]);function kp(n){var e=wp&&(n.ctrlKey||n.altKey||n.metaKey)||(Sp||vp)&&n.shiftKey&&n.key&&n.key.length==1,t=!e&&n.key||(n.shiftKey?vn:ii)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function he(){var n=arguments[0];typeof n=="string"&&(n=document.createElement(n));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=t[i];typeof s=="string"?n.setAttribute(i,s):s!=null&&(n[i]=s)}e++}for(;e2);var $={mac:Ql||/Mac/.test(qe.platform),windows:/Win/.test(qe.platform),linux:/Linux|X11/.test(qe.platform),ie:fr,ie_version:Lh?$o.documentMode||6:Zo?+Zo[1]:Ko?+Ko[1]:0,gecko:wl,gecko_version:wl?+(/Firefox\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,chrome:!!Mr,chrome_version:Mr?+Mr[1]:0,ios:Ql,android:/Android\b/.test(qe.userAgent),webkit:kl,webkit_version:kl?+(/\bAppleWebKit\/(\d+)/.exec(qe.userAgent)||[0,0])[1]:0,safari:Mo,safari_version:Mo?+(/\bVersion\/(\d+(\.\d+)?)/.exec(qe.userAgent)||[0,0])[1]:0,tabSize:$o.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function ba(n,e){for(let t in n)t=="class"&&e.class?e.class+=" "+n.class:t=="style"&&e.style?e.style+=";"+n.style:e[t]=n[t];return e}const $s=Object.create(null);function Sa(n,e,t){if(n==e)return!0;n||(n=$s),e||(e=$s);let i=Object.keys(n),s=Object.keys(e);if(i.length-0!=s.length-0)return!1;for(let r of i)if(r!=t&&(s.indexOf(r)==-1||n[r]!==e[r]))return!1;return!0}function Qp(n,e){for(let t=n.attributes.length-1;t>=0;t--){let i=n.attributes[t].name;e[i]==null&&n.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?n.style.cssText=i:n.getAttribute(t)!=i&&n.setAttribute(t,i)}}function Pl(n,e,t){let i=!1;if(e)for(let s in e)t&&s in t||(i=!0,s=="style"?n.style.cssText="":n.removeAttribute(s));if(t)for(let s in t)e&&e[s]==t[s]||(i=!0,s=="style"?n.style.cssText=t[s]:n.setAttribute(s,t[s]));return i}function Pp(n){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Ai(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,s;if(e.isBlockGap)i=-5e8,s=4e8;else{let{start:r,end:o}=Xh(e,t);i=(r?t?-3e8:-1:5e8)-1,s=(o?t?2e8:1:-6e8)+1}return new Ai(e,i,s,t,e.widget||null,!0)}static line(e){return new Dn(e)}static set(e,t=!1){return H.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}I.none=H.empty;class Fn extends I{constructor(e){let{start:t,end:i}=Xh(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?ba(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||$s}eq(e){return this==e||e instanceof Fn&&this.tagName==e.tagName&&Sa(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}Fn.prototype.point=!1;class Dn extends I{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof Dn&&this.spec.class==e.spec.class&&Sa(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}Dn.prototype.mapMode=De.TrackBefore;Dn.prototype.point=!0;class Ai extends I{constructor(e,t,i,s,r,o){super(t,i,r,e),this.block=s,this.isReplace=o,this.mapMode=s?t<=0?De.TrackBefore:De.TrackAfter:De.TrackDel}get type(){return this.startSide!=this.endSide?Le.WidgetRange:this.startSide<=0?Le.WidgetBefore:Le.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof Ai&&Cp(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Ai.prototype.point=!0;function Xh(n,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=n;return t==null&&(t=n.inclusive),i==null&&(i=n.inclusive),{start:t??e,end:i??e}}function Cp(n,e){return n==e||!!(n&&e&&n.compare(e))}function Mi(n,e,t,i=0){let s=t.length-1;s>=0&&t[s]+i>=n?t[s]=Math.max(t[s],e):t.push(n,e)}class wn extends ei{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof wn&&this.tagName==e.tagName&&Sa(this.attributes,e.attributes)}static create(e){return new wn(e.tagName,e.attributes||$s,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return H.of(e,t)}}wn.prototype.startSide=wn.prototype.endSide=-1;function kn(n){let e;return n.nodeType==11?e=n.getSelection?n:n.ownerDocument:e=n,e.getSelection()}function Eo(n,e){return e?n==e||n.contains(e.nodeType!=1?e.parentNode:e):!1}function gn(n,e){if(!e.anchorNode)return!1;try{return Eo(n,e.anchorNode)}catch{return!1}}function bs(n){return n.nodeType==3?Qn(n,0,n.nodeValue.length).getClientRects():n.nodeType==1?n.getClientRects():[]}function On(n,e,t,i){return t?Cl(n,e,t,i,-1)||Cl(n,e,t,i,1):!1}function ni(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e}function Ks(n){return n.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(n.nodeName)}function Cl(n,e,t,i,s){for(;;){if(n==t&&e==i)return!0;if(e==(s<0?0:Wt(n))){if(n.nodeName=="DIV")return!1;let r=n.parentNode;if(!r||r.nodeType!=1)return!1;e=ni(n)+(s<0?0:1),n=r}else if(n.nodeType==1){if(n=n.childNodes[e+(s<0?-1:0)],n.nodeType==1&&n.contentEditable=="false")return!1;e=s<0?Wt(n):0}else return!1}}function Wt(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function Zs(n,e){let{left:t,right:i}=n;if(t==i)return n;let s=e?t:i;return{left:s,right:s,top:n.top,bottom:n.bottom}}function Tp(n){let e=n.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.innerWidth,top:0,bottom:n.innerHeight}}function Bh(n,e){let t=e.width/n.offsetWidth,i=e.height/n.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-n.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-n.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Rp(n,e,t,i,s,r,o,a){let l=n.ownerDocument,c=l.defaultView||window;for(let h=n,u=!1;h&&!u;)if(h.nodeType==1){let f,d=h==l.body,p=1,m=1;if(d)f=Tp(c);else{if(/^(fixed|sticky)$/.test(getComputedStyle(h).position)&&(u=!0),h.scrollHeight<=h.clientHeight&&h.scrollWidth<=h.clientWidth){h=h.assignedSlot||h.parentNode;continue}let x=h.getBoundingClientRect();({scaleX:p,scaleY:m}=Bh(h,x)),f={left:x.left,right:x.left+h.clientWidth*p,top:x.top,bottom:x.top+h.clientHeight*m}}let g=0,y=0;if(s=="nearest")e.top0&&e.bottom>f.bottom+y&&(y=e.bottom-f.bottom+o)):e.bottom>f.bottom-o&&(y=e.bottom-f.bottom+o,t<0&&e.top-y0&&e.right>f.right+g&&(g=e.right-f.right+r)):e.right>f.right-r&&(g=e.right-f.right+r,t<0&&e.leftf.bottom||e.leftf.right)&&(e={left:Math.max(e.left,f.left),right:Math.min(e.right,f.right),top:Math.max(e.top,f.top),bottom:Math.min(e.bottom,f.bottom)}),h=h.assignedSlot||h.parentNode}else if(h.nodeType==11)h=h.host;else break}function Ih(n,e=!0){let t=n.ownerDocument,i=null,s=null;for(let r=n.parentNode;r&&!(r==t.body||(!e||i)&&s);)if(r.nodeType==1)!s&&r.scrollHeight>r.clientHeight&&(s=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:s}}class $p{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?Wt(t):0),i,Math.min(e.focusOffset,i?Wt(i):0))}set(e,t,i,s){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=s}}function Wh(n){let e=[];for(let t=n;t;t=t.nodeType==11?t.host:t.parentNode)t.nodeType==1&&e.push({node:t,left:t.scrollLeft,top:t.scrollTop});return e}function qh(n,e=!0){for(let{node:t,left:i,top:s}of n)e&&t.scrollTop!=s&&(t.scrollTop=s),t.scrollLeft!=i&&(t.scrollLeft=i)}let ui=null;$.safari&&$.safari_version>=26&&(ui=!1);function zh(n){if(n.setActive)return n.setActive();if(ui)return n.focus(ui);let e=Wh(n);n.focus(ui==null?{get preventScroll(){return ui={preventScroll:!0},!0}}:void 0),ui||(ui=!1,qh(e))}let Tl;function Qn(n,e,t=e){let i=Tl||(Tl=document.createRange());return i.setEnd(n,t),i.setStart(n,e),i}function Ei(n,e,t,i){let s={key:e,code:e,keyCode:t,which:t,cancelable:!0};i&&({altKey:s.altKey,ctrlKey:s.ctrlKey,shiftKey:s.shiftKey,metaKey:s.metaKey}=i);let r=new KeyboardEvent("keydown",s);r.synthetic=!0,n.dispatchEvent(r);let o=new KeyboardEvent("keyup",s);return o.synthetic=!0,n.dispatchEvent(o),r.defaultPrevented||o.defaultPrevented}function Kp(n){for(;n;){if(n&&(n.nodeType==9||n.nodeType==11&&n.host))return n;n=n.assignedSlot||n.parentNode}return null}function Zp(n,e){let t=e.focusNode,i=e.focusOffset;if(!t||e.anchorNode!=t||e.anchorOffset!=i)return!1;for(i=Math.min(i,Wt(t));;)if(i){if(t.nodeType!=1)return!1;let s=t.childNodes[i-1];s.contentEditable=="false"?i--:(t=s,i=Wt(t))}else{if(t==n)return!0;i=ni(t),t=t.parentNode}}function Vh(n){return n instanceof Window?n.pageYOffset>Math.max(0,n.document.documentElement.scrollHeight-n.innerHeight-4):n.scrollTop>Math.max(1,n.scrollHeight-n.clientHeight-4)}function jh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=Wt(t)}else if(t.parentNode&&!Ks(t))i=ni(t),t=t.parentNode;else return null}}function Yh(n,e){for(let t=n,i=e;;){if(t.nodeType==3&&i=t){if(a.level==i)return o;(r<0||(s!=0?s<0?a.fromt:e[r].level>a.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}function Gh(n,e){if(n.length!=e.length)return!1;for(let t=0;t=0;m-=3)if(St[m+1]==-d){let g=St[m+2],y=g&2?s:g&4?g&1?r:s:0;y&&(ue[u]=ue[St[m]]=y),a=m;break}}else{if(St.length==189)break;St[a++]=u,St[a++]=f,St[a++]=l}else if((p=ue[u])==2||p==1){let m=p==s;l=m?0:1;for(let g=a-3;g>=0;g-=3){let y=St[g+2];if(y&2)break;if(m)St[g+2]|=2;else{if(y&4)break;St[g+2]|=4}}}}}function Lp(n,e,t,i){for(let s=0,r=i;s<=t.length;s++){let o=s?t[s-1].to:n,a=sl;)p==g&&(p=t[--m].from,g=m?t[m-1].to:n),ue[--p]=d;l=h}else r=c,l++}}}function Fo(n,e,t,i,s,r,o){let a=i%2?2:1;if(i%2==s%2)for(let l=e,c=0;ll&&o.push(new Ct(l,m.from,d));let g=m.direction==bi!=!(d%2);Do(n,g?i+1:i,s,m.inner,m.from,m.to,o),l=m.to}p=m.to}else{if(p==t||(h?ue[p]!=a:ue[p]==a))break;p++}f?Fo(n,l,p,i+1,s,f,o):le;){let h=!0,u=!1;if(!c||l>r[c-1].to){let m=ue[l-1];m!=a&&(h=!1,u=m==16)}let f=!h&&a==1?[]:null,d=h?i:i+1,p=l;e:for(;;)if(c&&p==r[c-1].to){if(u)break e;let m=r[--c];if(!h)for(let g=m.from,y=c;;){if(g==e)break e;if(y&&r[y-1].to==g)g=r[--y].from;else{if(ue[g-1]==a)break e;break}}if(f)f.push(m);else{m.toue.length;)ue[ue.length]=256;let i=[],s=e==bi?0:1;return Do(n,s,s,t,0,n.length,i),i}function _h(n){return[new Ct(0,n,0)]}let Jh="";function Bp(n,e,t,i,s){var r;let o=i.head-n.from,a=Ct.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),l=e[a],c=l.side(s,t);if(o==c){let f=a+=s?1:-1;if(f<0||f>=e.length)return null;l=e[a=f],o=l.side(!s,t),c=l.side(s,t)}let h=Ze(n.text,o,l.forward(s,t));(hl.to)&&(h=c),Jh=n.text.slice(Math.min(o,h),Math.max(o,h));let u=a==(s?e.length-1:0)?null:e[a+(s?1:-1)];return u&&h==c&&u.level+(s?0:1)n.some(e=>e)}),au=Z.define({combine:n=>n.some(e=>e)}),lu=Z.define();class Ui{constructor(e,t,i,s,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=s,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new Ui(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new Ui(A.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Hn=Y.define({map:(n,e)=>n.map(e)}),cu=Y.define();function ze(n,e,t){let i=n.facet(nu);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const Lt=Z.define({combine:n=>n.length?n[0]:!0});let Wp=0;const Ti=Z.define({combine(n){return n.filter((e,t)=>{for(let i=0;i{let l=[];return o&&l.push(dr.of(c=>{let h=c.plugin(a);return h?o(h):I.none})),r&&l.push(r(a)),l})}static fromClass(e,t){return xe.define((i,s)=>new e(i,s),t)}}class Er{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(ze(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){ze(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){ze(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const hu=Z.define(),ka=Z.define(),dr=Z.define(),uu=Z.define(),Qa=Z.define(),Ln=Z.define(),fu=Z.define();function Rl(n,e){let t=n.state.facet(fu);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(n):r),s=[];return H.spans(i,e.from,e.to,{point(){},span(r,o,a,l){let c=r-e.from,h=o-e.from,u=s;for(let f=a.length-1;f>=0;f--,l--){let d=a[f].spec.bidiIsolate,p;if(d==null&&(d=Ip(e.text,c,h)),l>0&&u.length&&(p=u[u.length-1]).to==c&&p.direction==d)p.to=h,u=p.inner;else{let m={from:c,to:h,direction:d,inner:[]};u.push(m),u=m.inner}}}}),s}const du=Z.define();function Pa(n){let e=0,t=0,i=0,s=0;for(let r of n.state.facet(du)){let o=r(n);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(s=Math.max(s,o.bottom)))}return{left:e,right:t,top:i,bottom:s}}const hn=Z.define();class ct{constructor(e,t,i,s){this.fromA=e,this.toA=t,this.fromB=i,this.toB=s}join(e){return new ct(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let s=e[t-1];if(!(s.fromA>i.toA)){if(s.toAs.push(new ct(r,o,a,l))),this.changedRanges=s}static create(e,t,i){return new Ms(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const qp=[];class Se{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return qp}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Qp(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let s of this.children){if(s==e)return i;i+=s.length+s.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t,i){return null}domPosFor(e,t){let i=ni(this.dom),s=this.length?e>0:t>0;return new pt(this.parent.dom,i+(s?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof mr)return e;return null}static get(e){return e.cmTile}}class pr extends Se{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,s,r=e?.node==t?e:null,o=0;for(let a of this.children){if(a.sync(e),o+=a.length+a.breakAfter,s=i?i.nextSibling:t.firstChild,r&&s!=a.dom&&(r.written=!0),a.dom.parentNode==t)for(;s&&s!=a.dom;)s=$l(s);else t.insertBefore(a.dom,s);i=a.dom}for(s=i?i.nextSibling:t.firstChild,r&&s&&(r.written=!0);s;)s=$l(s);this.length=o}}function $l(n){let e=n.nextSibling;return n.parentNode.removeChild(n),e}class mr extends pr{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=Se.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,s=0,r=0;;)if(s==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,s=t.pop()}else{let o=i.children[s++];if(o instanceof Xt)t.push(s),i=o,s=0;else{let a=r+o.length,l=e(o,r);if(l!==void 0)return l;r=a+o.breakAfter}}}resolveBlock(e,t){let i,s=-1,r,o=-1;if(this.blockTiles((a,l)=>{let c=l+a.length;if(e>=l&&e<=c){if(a.isWidget()&&t>=-1&&t<=1){if(a.flags&32)return!0;a.flags&16&&(i=void 0)}(le||e==l&&(t>1?a.length:a.covers(-1)))&&(!r||!a.isWidget()&&r.isWidget())&&(r=a,o=e-l)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:s}:{tile:r,offset:o}}}class Xt extends pr{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new Xt(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class Ii extends pr{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let s=new Ii(t||document.createElement("div"),e);return(!t||!i)&&(s.flags|=4),s}get domAttrs(){return this.attrs}resolveInline(e,t,i){let s=null,r=-1,o=null,a=-1;function l(h,u){for(let f=0,d=0;f=u&&(p.isComposite()?l(p,u-d):(!o||o.isHidden&&(t>0&&!(o.flags&32)||i&&Vp(o,p)))&&(m>u||p.flags&32&&t<=1)?(o=p,a=u-d):(d=-1)&&(s=p,r=u-d)),d=m}}l(this,e);let c=(t<0?s:o)||s||o;return c?{tile:c,offset:c==s?r:a}:null}coordsIn(e,t,i){let s=this.resolveInline(e,t,!0);return s?s.tile.coordsIn(Math.max(0,s.offset),t,i):zp(this)}domIn(e,t){let i=this.resolveInline(e,t);if(i){let{tile:s,offset:r}=i;if(this.dom.contains(s.dom))return s.isText()?new pt(s.dom,Math.min(s.dom.nodeValue.length,r)):s.domPosFor(r,s.flags&16?1:s.flags&32?-1:t);let o=i.tile.parent,a=!1;for(let l of o.children){if(a)return new pt(l.dom,0);l==i.tile&&(a=!0)}}return new pt(this.dom,0)}}function zp(n){let e=n.dom.lastChild;if(!e)return n.dom.getBoundingClientRect();let t=bs(e);return t[t.length-1]||null}function Vp(n,e){let t=n.coordsIn(0,1),i=e.coordsIn(0,1);return t&&i&&i.tops&&(e=s);let r=e,o=e,a=0;e==0&&t<0||e==s&&t>=0?$.chrome||$.gecko||(e?(r--,a=1):o=0)?0:l.length-1];return $.safari&&!a&&c.width==0&&(c=Array.prototype.find.call(l,h=>h.width)||c),i==null?c:Zs(c,(a?a>0:t<0)==i)}static of(e,t){let i=new pi(t||document.createTextNode(e),e);return t||(i.flags|=2),i}}class Si extends Se{constructor(e,t,i,s){super(e,t,s),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let s=this.widget.coordsAt(this.dom,e,t);if(s)return s;if(i)return Zs(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let a=this.flags&16?!0:this.flags&32?!1:e>0;for(let l=a?r.length-1:0;o=r[l],!(e>0?l==0:l==r.length-1||o.top0==i)}}class jp{constructor(e){this.index=0,this.beforeBreak=!1,this.parents=[],this.tile=e}advance(e,t,i){let{tile:s,index:r,beforeBreak:o,parents:a}=this;for(;e||t>0;)if(s.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==s.children.length){if(!e&&!a.length)break;i&&i.leave(s),o=!!s.breakAfter,{tile:s,index:r}=a.pop(),r++}else{let l=s.children[r],c=l.breakAfter;(t>0?l.length<=e:l.length=0;a--){let l=t.marks[a],c=s.lastChild;if(c instanceof Ge&&c.mark.eq(l.mark))c.dom!=l.dom&&c.setDOM(Ur(l.dom)),s=c;else{if(this.cache.reused.get(l)){let u=Se.get(l.dom);u&&u.setDOM(Ur(l.dom))}let h=Ge.of(l.mark,l.dom);s.append(h),s=h}this.cache.reused.set(l,2)}let r=Se.get(e.text);r&&this.cache.reused.set(r,2);let o=new pi(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,s.append(o)}addInlineWidget(e,t,i){let s=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);s||this.flushBuffer();let r=this.ensureMarks(t,i);!s&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=pu);let s=Ii.start(e,t||((i=this.cache.find(Ii))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=s)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let s=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],a;if(t>0&&(a=s.lastChild)&&a instanceof Ge&&a.mark.eq(o))s=a,t--;else{let l=Ge.of(o,(i=this.cache.find(Ge,c=>c.mark.eq(o)))===null||i===void 0?void 0:i.dom);s.append(l),s=l,t=0}}return s}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!Kl(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!($.ios&&Kl(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(Fr,0,32)||new Si(Fr.toDOM(),0,Fr,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new Yp(e.from,e.to,e.value,t),s=this.wrappers.length;for(;s>0&&(this.wrappers[s-1].rank-i.rank||this.wrappers[s-1].to-i.to)<0;)s--;this.wrappers.splice(s,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let s=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(Es,void 0,1);return i&&(i.flags=t),i||new Es(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class Hp{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:s,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=s;let a=this.textOff=Math.min(e,s.length);return r?null:s.slice(0,a)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}}const Us=[Si,Ii,pi,Ge,Es,Xt,mr];for(let n=0;n[]),this.index=Us.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let s=e.bucket,r=this.buckets[s],o=this.index[s];for(let a=0;a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let s=0,r=0,o=0;;){let a=os){let c=l-s;this.preserve(c,!o,!a),s=l,r+=c}if(!a)break;t&&a.fromA<=t.range.fromA&&a.toA>=t.range.toA?(this.forward(a.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(l-a);else{let c=l>0||a{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Ge&&s.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?s.length&&(s.length=r=0):o instanceof Ge&&(s.shift(),r=Math.min(r,s.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,s=this.builder,r=-1,o=H.spans(this.decorations,e,t,{point:(a,l,c,h,u,f)=>{if(c instanceof Ai){if(this.disallowBlockEffectsFor[f]){if(c.block)throw new RangeError("Block decorations may not be specified via plugins");if(l>this.view.state.doc.lineAt(a).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=h.length,u>h.length)s.continueWidget(l-a);else{let d=c.widget||(c.block?Wi.block:Wi.inline),p=Jp(c),m=this.cache.findWidget(d,l-a,p)||Si.of(d,this.view,l-a,p);c.block?(c.startSide>0&&s.addLineStartIfNotCovered(i),s.addBlockWidget(m)):(s.ensureLine(i),s.addInlineWidget(m,h,u))}i=null}else i=em(i,c);l>a&&this.text.skip(l-a)},span:(a,l,c,h)=>{for(let u=a;u-1&&(this.openWidget=o>r),this.openWidget||s.addLineStartIfNotCovered(i),this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let s=e.parentNode;;s=s.parentNode){let r=Se.get(s);if(s==this.view.contentDOM)break;r instanceof Ge?t.push(r):r?.isLine()?i=r:r instanceof Xt||(s.nodeName=="DIV"&&!i&&s!=this.view.contentDOM?i=new Ii(s,pu):i||t.push(Ge.of(new Fn({tagName:s.nodeName.toLowerCase(),attributes:Pp(s)}),s)))}return{line:i,marks:t}}}function Kl(n,e){let t=i=>{for(let s of i.children)if((e?s.isText():s.length)||t(s))return!0;return!1};return t(n)}function Jp(n){let e=n.isReplace?(n.startSide<0?64:0)|(n.endSide>0?128:0):n.startSide>0?32:16;return n.block&&(e|=256),e}const pu={class:"cm-line"};function em(n,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(n||(n={class:"cm-line"}),t&&ba(t,n),i&&(n.class+=" "+i)),n}function tm(n){let e=[];for(let t=n.parents.length;t>1;t--){let i=t==n.parents.length?n.tile:n.parents[t].tile;i instanceof Ge&&e.push(i.mark)}return e}function Ur(n){let e=Se.get(n);return e&&e.setDOM(n.cloneNode()),n}class Wi extends Ut{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}Wi.inline=new Wi("span");Wi.block=new Wi("div");const Fr=new class extends Ut{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class Zl{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=I.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new mr(e,e.contentDOM),this.updateInner([new ct(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:h,toA:u})=>uthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let s=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?s=this.domChanged.newSel.head:!hm(e.changes,this.hasComposition)&&!e.selectionSet&&(s=e.state.selection.main.head));let r=s>-1?nm(this.view,e.changes,s):null;if(this.domChanged=null,this.hasComposition){let{from:h,to:u}=this.hasComposition;i=new ct(h,u,e.changes.mapPos(h,-1),e.changes.mapPos(u,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,($.ie||$.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,a=this.blockWrappers;this.updateDeco();let l=om(o,this.decorations,e.changes);l.length&&(i=ct.extendWithRanges(i,l));let c=lm(a,this.blockWrappers,e.changes);return c.length&&(i=ct.extendWithRanges(i,c)),r&&!i.some(h=>h.fromA<=r.range.fromA&&h.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,a=new _p(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&Se.get(t.text)&&a.cache.reused.set(Se.get(t.text),2),this.tile=a.run(e,t),Xo(o,a.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=$.chrome||$.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let s=[];if(this.view.viewport.from||this.view.viewport.to-1)&&gn(i,this.view.observer.selectionRange)&&!(s&&i.contains(s));if(!(r||t||o))return;let a=this.forceSelection;this.forceSelection=!1;let l=this.view.state.selection.main,c,h;if(l.empty?h=c=this.inlineDOMNearPos(l.anchor,l.assoc||1):(h=this.inlineDOMNearPos(l.head,l.head==l.from?1:-1),c=this.inlineDOMNearPos(l.anchor,l.anchor==l.from?1:-1)),$.gecko&&l.empty&&!this.hasComposition&&im(c)){let f=document.createTextNode("");this.view.observer.ignore(()=>c.node.insertBefore(f,c.node.childNodes[c.offset]||null)),c=h=new pt(f,0),a=!0}let u=this.view.observer.selectionRange;(a||!u.focusNode||(!On(c.node,c.offset,u.anchorNode,u.anchorOffset)||!On(h.node,h.offset,u.focusNode,u.focusOffset))&&!this.suppressWidgetCursorChange(u,l))&&(this.view.observer.ignore(()=>{$.android&&$.chrome&&i.contains(u.focusNode)&&cm(u.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let f=kn(this.view.root);if(f)if(l.empty){if($.gecko){let d=sm(c.node,c.offset);if(d&&d!=3){let p=(d==1?jh:Yh)(c.node,c.offset);p&&(c=new pt(p.node,p.offset))}}f.collapse(c.node,c.offset),l.bidiLevel!=null&&f.caretBidiLevel!==void 0&&(f.caretBidiLevel=l.bidiLevel)}else if(f.extend){f.collapse(c.node,c.offset);try{f.extend(h.node,h.offset)}catch{}}else{let d=document.createRange();l.anchor>l.head&&([c,h]=[h,c]),d.setEnd(h.node,h.offset),d.setStart(c.node,c.offset),f.removeAllRanges(),f.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),s&&s.focus())}),this.view.observer.setSelectionRange(c,h)),this.impreciseAnchor=c.precise?null:new pt(u.anchorNode,u.anchorOffset),this.impreciseHead=h.precise?null:new pt(u.focusNode,u.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&On(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=kn(e.root),{anchorNode:s,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let a=o.posAtStart;if(t.head==a||t.head==a+o.length)return;let l=this.coordsAt(t.head,-1),c=this.coordsAt(t.head,1);if(!l||!c||l.bottom>c.top)return;let h=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(h.node,h.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let u=e.observer.selectionRange;e.docView.posFromDOM(u.anchorNode,u.anchorOffset)!=t.from&&i.collapse(s,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let s=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=Wt(e)==0?0:t==0?-1:1;for(;;){let a=e.parentNode;if(a==i.dom)break;o==0&&a.firstChild!=a.lastChild&&(e==a.firstChild?o=-1:o=1),e=a}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return s;for(;r&&!Se.get(r);)r=r.nextSibling;if(!r)return s+i.length;for(let o=0,a=s;;o++){let l=i.children[o];if(l.dom==r)return a;a+=l.length+l.breakAfter}}else return i.isText()?e==i.dom?s+t:s+(t?i.length:0):s}domAtPos(e,t){let{tile:i,offset:s}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(s,t):i.domIn(s,t)}inlineDOMNearPos(e,t){let i,s=-1,r=!1,o,a=-1,l=!1;return this.tile.blockTiles((c,h)=>{if(c.isWidget()){if(c.flags&32&&h>=e)return!0;c.flags&16&&(r=!0)}else{let u=h+c.length;if(h<=e&&(i=c,s=e-h,r=u=e&&!o&&(o=c,a=e-h,l=h>e),h>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:l&&i&&(o=null),i&&t<0||!o?i.domIn(s,t):o.domIn(a,t))}coordsAt(e,t,i){let{tile:s,offset:r}=this.tile.resolveBlock(e,t);return s.isWidget()?s.widget instanceof Dr?null:s.coordsInWidget(r,t,!0):s.coordsIn(r,t,i)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function s(r,o){if(r.isComposite())for(let a of r.children){if(a.length>=o){let l=s(a,o);if(l)return l}if(o-=a.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,a=-1,l=this.view.textDirection==fe.LTR,c=0,h=(u,f,d)=>{for(let p=0;ps);p++){let m=u.children[p],g=f+m.length,y=m.dom.getBoundingClientRect(),{height:x}=y;if(d&&!p&&(c+=y.top-d.top),m instanceof Xt)g>i&&h(m,f,y);else if(f>=i&&(c>0&&t.push(-c),t.push(x+c),c=0,o)){let b=m.dom.lastChild,C=b?bs(b):[];if(C.length){let Q=C[C.length-1],P=l?Q.right-y.left:y.right-Q.left;P>a&&(a=P,this.minWidth=r,this.minWidthFrom=f,this.minWidthTo=g)}}d&&p==u.children.length-1&&(c+=d.bottom-y.bottom),f=g+m.breakAfter}};return h(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?fe.RTL:fe.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let a=0,l;for(let c of o.children){if(!c.isText()||/[^ -~]/.test(c.text))return;let h=bs(c.dom);if(h.length!=1)return;a+=h[0].width,l=h[0].height}if(a)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:a/o.length,textHeight:l}}});if(e)return e;let t=document.createElement("div"),i,s,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=bs(t.firstChild)[0];i=t.getBoundingClientRect().height,s=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:s,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,s=0;;s++){let r=s==t.viewports.length?null:t.viewports[s],o=r?r.from-1:this.view.state.doc.length;if(o>i){let a=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(I.replace({widget:new Dr(a),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return I.set(e)}updateDeco(){let e=1,t=this.view.state.facet(dr).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,s=this.view.state.facet(Qa).map((r,o)=>{let a=typeof r=="function";return a&&(i=!0),a?r(this.view):r});for(s.length&&(this.dynamicDecorationMap[e++]=i,t.push(H.join(s))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(lu))try{if(c(this.view,e.range,e))return!0}catch(h){ze(this.view.state,h,"scroll handler")}let{range:t}=e,i=this.coordsAt(t.head,t.assoc||(t.head>t.anchor?-1:1)),s;if(!i)return;!t.empty&&(s=this.coordsAt(t.anchor,t.anchor>t.head?-1:1))&&(i={left:Math.min(i.left,s.left),top:Math.min(i.top,s.top),right:Math.max(i.right,s.right),bottom:Math.max(i.bottom,s.bottom)});let r=Pa(this.view),o={left:i.left-r.left,top:i.top-r.top,right:i.right+r.right,bottom:i.bottom+r.bottom},{offsetWidth:a,offsetHeight:l}=this.view.scrollDOM;if(Rp(this.view.scrollDOM,o,t.head1&&(i.top>window.visualViewport.offsetTop+window.visualViewport.height||i.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){Xo(this.tile)}}function Xo(n,e){let t=e?.get(n);if(t!=1){t==null&&n.destroy();for(let i of n.children)Xo(i,e)}}function im(n){return n.node.nodeType==1&&n.node.firstChild&&(n.offset==0||n.node.childNodes[n.offset-1].contentEditable=="false")&&(n.offset==n.node.childNodes.length||n.node.childNodes[n.offset].contentEditable=="false")}function mu(n,e){let t=n.observer.selectionRange;if(!t.focusNode)return null;let i=jh(t.focusNode,t.focusOffset),s=Yh(t.focusNode,t.focusOffset),r=i||s;if(s&&i&&s.node!=i.node){let a=Se.get(s.node);if(!a||a.isText()&&a.text!=s.node.nodeValue)r=s;else if(n.docView.lastCompositionAfterCursor){let l=Se.get(i.node);!l||l.isText()&&l.text!=i.node.nodeValue||(r=s)}}if(n.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function nm(n,e,t){let i=mu(n,t);if(!i)return null;let{node:s,from:r,to:o}=i,a=s.nodeValue;if(/[\n\r]/.test(a)||n.state.doc.sliceString(i.from,i.to)!=a)return null;let l=e.invertedDesc;return{range:new ct(l.mapPos(r),l.mapPos(o),r,o),text:s}}function sm(n,e){return n.nodeType!=1?0:(e&&n.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}class Dr extends Ut{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function um(n,e,t=1){let i=n.charCategorizer(e),s=n.doc.lineAt(e),r=e-s.from;if(s.length==0)return A.cursor(e);r==0?t=1:r==s.length&&(t=-1);let o=r,a=r;t<0?o=Ze(s.text,r,!1):a=Ze(s.text,r);let l=i(s.text.slice(o,a));for(;o>0;){let c=Ze(s.text,o,!1);if(i(s.text.slice(c,o))!=l)break;o=c}for(;an.defaultLineHeight*1.5){let a=n.viewState.heightOracle.textHeight,l=Math.floor((s-t.top-(n.defaultLineHeight-a)*.5)/a);r+=l*n.viewState.heightOracle.lineLength}let o=n.state.sliceDoc(t.from,t.to);return t.from+Co(o,r,n.state.tabSize)}function Bo(n,e,t){let i=n.lineBlockAt(e);if(Array.isArray(i.type)){let s;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!s||r.type==Le.Text&&(s.type!=r.type||(t<0?r.frome)))&&(s=r)}}return s||i}return i}function dm(n,e,t,i){let s=Bo(n,e.head,e.assoc||-1),r=!i||s.type!=Le.Text||!(n.lineWrapping||s.widgetLineBreaks)?null:n.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head);if(r){let o=n.dom.getBoundingClientRect(),a=n.textDirectionAt(s.from),l=n.posAtCoords({x:t==(a==fe.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(l!=null)return A.cursor(l,t?-1:1)}return A.cursor(t?s.to:s.from,t?-1:1)}function Ml(n,e,t,i){let s=n.state.doc.lineAt(e.head),r=n.bidiSpans(s),o=n.textDirectionAt(s.from);for(let a=e,l=null;;){let c=Bp(s,r,o,a,t),h=Jh;if(!c){if(s.number==(t?n.state.doc.lines:1))return a;h=` +`,s=n.state.doc.line(s.number+(t?1:-1)),r=n.bidiSpans(s),c=n.visualLineSide(s,!t)}if(l){if(!l(h))return a}else{if(!i)return c;l=i(h)}a=c}}function pm(n,e,t){let i=n.state.charCategorizer(e),s=i(t);return r=>{let o=i(r);return s==ye.Space&&(s=o),s==o}}function mm(n,e,t,i){let s=e.head,r=t?1:-1;if(s==(t?n.state.doc.length:0))return A.cursor(s,e.assoc);let o=e.goalColumn,a,l=n.contentDOM.getBoundingClientRect(),c=n.coordsAtPos(s,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),h=n.documentTop;if(c)o==null&&(o=c.left-l.left),a=r<0?c.top:c.bottom;else{let p=n.viewState.lineBlockAt(s);o==null&&(o=Math.min(l.right-l.left,n.defaultCharacterWidth*(s-p.from))),a=(r<0?p.top:p.bottom)+h}let u=l.left+o,f=n.viewState.heightOracle.textHeight>>1,d=i??f;for(let p=0;;p+=f){let m=a+(d+p)*r,g=Io(n,{x:u,y:m},!1,r);if(t?m>l.bottom:ma:x{if(e>r&&es(n)),t.from,e.head>t.from?-1:1);return i==t.from?t:A.cursor(i,in.viewState.docHeight)return new Pt(n.state.doc.length,-1);if(c=n.elementAtHeight(l),i==null)break;if(c.type==Le.Text){if(i<0?c.ton.viewport.to)break;let f=n.docView.coordsAt(i<0?c.from:c.to,i>0?-1:1);if(f&&(i<0?f.top<=l+r:f.bottom>=l+r))break}let u=n.viewState.heightOracle.textHeight/2;l=i>0?c.bottom+u:c.top-u}if(n.viewport.from>=c.to||n.viewport.to<=c.from){if(t)return null;if(c.type==Le.Text){let u=fm(n,s,c,o,a);return new Pt(u,u==c.from?1:-1)}}if(c.type!=Le.Text)return l<(c.top+c.bottom)/2?new Pt(c.from,1):new Pt(c.to,-1);let h=n.docView.lineAt(c.from,2);return(!h||h.length!=c.length)&&(h=n.docView.lineAt(c.from,-2)),new gm(n,o,a,n.textDirectionAt(c.from)).scanTile(h,c.from)}class gm{constructor(e,t,i,s){this.view=e,this.x=t,this.y=i,this.baseDir=s,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+s.from>1;t:if(o.has(m)){for(let x=1;x=r&&(b-=p),!o.has(b)){m=b;break t}}break e}o.add(m);let g=t(m),y=0;if(g)for(let x=0;x1))if(b.bottomthis.y)(!c||c.top>b.top)&&(c=b),y=-1;else{let C=b.left>this.x?this.x-b.left:b.right(p+p+m)/3)return this.y=l.bottom-1,this.scan(e,t,!0);if(c&&c.top<(p+m+m)/3)return this.y=c.top+1,this.scan(e,t,!0)}let d=(a?this.dirAt(e[h],1):this.baseDir)==fe.LTR;return{i:h,after:this.x>(f.left+f.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,a=i[r+1]-t;return Qn(e.dom,o,a).getClientRects()});return s.after?new Pt(i[s.i+1],-1):new Pt(i[s.i],1)}scanTile(e,t){if(!e.length)return new Pt(t,1);if(e.children.length==1){let a=e.children[0];if(a.isText())return this.scanText(a,t);if(a.isComposite())return this.scanTile(a,t)}let i=[t];for(let a=0,l=t;a{let l=e.children[a];return l.flags&48?null:(l.dom.nodeType==1?l.dom:Qn(l.dom,0,l.length)).getClientRects()}),r=e.children[s.i],o=i[s.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):s.after?new Pt(i[s.i+1],-1):new Pt(o,1)}}const ki="￿";class Om{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(J.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=ki}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let s=e;;){this.findPointBefore(i,s);let r=this.text.length;this.readNode(s);let o=Se.get(s),a=s.nextSibling;if(a==t){o?.breakAfter&&!a&&i!=this.view.contentDOM&&this.lineBreak();break}let l=Se.get(a);(o&&l?o.breakAfter:(o?o.breakAfter:Ks(s))||Ks(a)&&(s.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!Am(a,t)&&this.lineBreak(),s=a}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,s=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,a;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(a=s.exec(t))&&(r=a.index,o=a[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let l of this.points)l.node==e&&l.pos>this.text.length&&(l.pos-=o-1);i=r+o}}readNode(e){let t=Se.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let s=i.iter();!s.next().done;)s.lineBreak?this.lineBreak():this.append(s.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(ym(e,i.node,i.offset)?t:0))}}function ym(n,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,a=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Ou(e.docView.tile,t,i,0))){let l=r||o?[]:xm(e),c=new Om(l,e);c.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=c.text,this.newSel=vm(l,this.bounds.from)}else{let l=e.observer.selectionRange,c=r&&r.node==l.focusNode&&r.offset==l.focusOffset||!Eo(e.contentDOM,l.focusNode)?a.main.head:e.docView.posFromDOM(l.focusNode,l.focusOffset),h=o&&o.node==l.anchorNode&&o.offset==l.anchorOffset||!Eo(e.contentDOM,l.anchorNode)?a.main.anchor:e.docView.posFromDOM(l.anchorNode,l.anchorOffset),u=e.viewport;if(($.ios||$.chrome)&&c!=h&&Math.min(c,h)<=a.main.from&&Math.max(c,h)>=a.main.to&&(u.from>0||u.to-1&&a.ranges.length>1)this.newSel=a.replaceRange(A.range(h,c));else if(e.lineWrapping&&h==c&&!(a.main.empty&&a.main.head==c)&&e.inputState.lastTouchTime>Date.now()-100){let f=e.coordsAtPos(c,-1),d=0;f&&(d=e.inputState.lastTouchY<=f.bottom?-1:1),this.newSel=A.create([A.cursor(c,d)])}else this.newSel=A.single(h,c)}}}function Ou(n,e,t,i){if(n.isComposite()){let s=-1,r=-1,o=-1,a=-1;for(let l=0,c=i,h=i;lt)return Ou(u,e,t,c);if(f>=e&&s==-1&&(s=l,r=c),c>t&&u.dom.parentNode==n.dom){o=l,a=h;break}h=f,c=f+u.breakAfter}return{from:r,to:a<0?i+n.length:a,startDOM:(s?n.children[s-1].dom.nextSibling:null)||n.dom.firstChild,endDOM:o=0?n.children[o].dom:null}}else return n.isText()?{from:i,to:i+n.length,startDOM:n.dom,endDOM:n.dom.nextSibling}:null}function yu(n,e){let t,{newSel:i}=e,{state:s}=n,r=s.selection.main,o=n.inputState.lastKeyTime>Date.now()-100?n.inputState.lastKeyCode:-1;if(e.bounds){let{from:a,to:l}=e.bounds,c=r.from,h=null;(o===8||$.android&&e.text.length=a&&r.to<=l&&(e.typeOver||u!=e.text)&&u.slice(0,r.from-a)==e.text.slice(0,r.from-a)&&u.slice(r.to-a)==e.text.slice(f=e.text.length-(u.length-(r.to-a)))?t={from:r.from,to:r.to,insert:se.of(e.text.slice(r.from-a,f).split(ki))}:(d=Au(u,e.text,c-a,h))&&($.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==ki+ki&&d.toB--,t={from:a+d.from,to:a+d.toA,insert:se.of(e.text.slice(d.from,d.toB).split(ki))})}else i&&(!n.hasFocus&&s.facet(Lt)||Fs(i,r))&&(i=null);if(!t&&!i)return!1;if(($.mac||$.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&n.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:se.of([t.insert.toString().replace("."," ")])}):s.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:s.toText(n.inputState.insertingText)}:$.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&n.lineWrapping&&(i&&(i=A.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:se.of([" "])}),t)return Ca(n,t,i,o);if(i&&!Fs(i,r)){let a=!1,l="select";return n.inputState.lastSelectionTime>Date.now()-50&&(n.inputState.lastSelectionOrigin=="select"&&(a=!0),l=n.inputState.lastSelectionOrigin,l=="select.pointer"&&(i=gu(s.facet(Ln).map(c=>c(n)),i))),n.dispatch({selection:i,scrollIntoView:a,userEvent:l}),!0}else return!1}function Ca(n,e,t,i=-1){if($.ios&&n.inputState.flushIOSKey(e))return!0;let s=n.state.selection.main;if($.android&&(e.to==s.to&&(e.from==s.from||e.from==s.from-1&&n.state.sliceDoc(e.from,s.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&Ei(n.contentDOM,"Enter",13)||(e.from==s.from-1&&e.to==s.to&&e.insert.length==0||i==8&&e.insert.lengths.head)&&Ei(n.contentDOM,"Backspace",8)||e.from==s.from&&e.to==s.to+1&&e.insert.length==0&&Ei(n.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();n.inputState.composing>=0&&n.inputState.composing++;let o,a=()=>o||(o=Sm(n,e,t));return n.state.facet(su).some(l=>l(n,e.from,e.to,r,a))||n.dispatch(a()),!0}function Sm(n,e,t){let i,s=n.state,r=s.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let l=e.fromu(n)),c,l);e.from==h&&(o=h)}if(o>-1)i={changes:e,selection:A.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&n.inputState.composing<0){let l=r.frome.to?s.sliceDoc(e.to,r.to):"";i=s.replaceSelection(n.state.toText(l+e.insert.sliceString(0,void 0,n.state.lineBreak)+c))}else{let l=s.changes(e),c=t&&t.main.to<=l.newLength?t.main:void 0;if(s.selection.ranges.length>1&&(n.inputState.composing>=0||n.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let h=n.state.sliceDoc(e.from,e.to),u,f=t&&mu(n,t.main.head);if(f){let p=e.insert.length-(e.to-e.from);u={from:f.from,to:f.to-p}}else u=n.state.doc.lineAt(r.head);let d=r.to-e.to;i=s.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:l,range:c||p.map(l)};let m=p.to-d,g=m-h.length;if(n.state.sliceDoc(g,m)!=h||m>=u.from&&g<=u.to)return{range:p};let y=s.changes({from:g,to:m,insert:e.insert}),x=p.to-r.to;return{changes:y,range:c?A.range(Math.max(0,c.anchor+x),Math.max(0,c.head+x)):p.map(y)}})}else i={changes:l,selection:c&&s.selection.replaceRange(c)}}let a="input.type";return(n.composing||n.inputState.compositionPendingChange&&n.inputState.compositionEndedAt>Date.now()-50)&&(n.inputState.compositionPendingChange=!1,a+=".compose",n.inputState.compositionFirstChange&&(a+=".start",n.inputState.compositionFirstChange=!1)),s.update(i,{userEvent:a,scrollIntoView:!0})}function Au(n,e,t,i){let s=Math.min(n.length,e.length),r=0;for(;r0&&a>0&&n.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if(i=="end"){let l=Math.max(0,r-Math.min(o,a));t-=o+l-r}if(o=o?r-t:0;r-=l,a=r+(a-o),o=r}else if(a=a?r-t:0;r-=l,o=r+(o-a),a=r}return{from:r,toA:o,toB:a}}function xm(n){let e=[];if(n.root.activeElement!=n.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}=n.observer.selectionRange;return t&&(e.push(new El(t,i)),(s!=t||r!=i)&&e.push(new El(s,r))),e}function vm(n,e){if(n.length==0)return null;let t=n[0].pos,i=n.length==2?n[1].pos:t;return t>-1&&i>-1?A.single(t+e,i+e):null}function Fs(n,e){return e.head==n.main.head&&e.anchor==n.main.anchor}class wm{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.touchActive=!1,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.lastIOSMomentumScroll=0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,$.safari&&e.contentDOM.addEventListener("input",()=>null),$.gecko&&Xm(e.contentDOM.ownerDocument)}handleEvent(e){!Zm(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let s of i.observers)s(this.view,t);for(let s of i.handlers){if(t.defaultPrevented)break;if(s(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Qm(e),i=this.handlers,s=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,a=i[r];a&&o!=!a.handlers.length&&(s.removeEventListener(r,this.handleEvent),a=null),a||s.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&s.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Su.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),$.android&&$.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;if($.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&(bu.some(t=>t.keyCode==e.keyCode)&&!e.ctrlKey||Pm.indexOf(e.key)>-1&&e.ctrlKey)){let t={ctrlKey:e.ctrlKey,altKey:e.altKey,metaKey:e.metaKey,shiftKey:e.shiftKey};return t.shiftKey&&$.ios&&!/^(off|none)$/.test(this.view.contentDOM.autocapitalize)&&km(this.view.win)&&(t.shiftKey=!1),this.pendingIOSKey={key:e.key,keyCode:e.keyCode,mods:t},setTimeout(()=>this.flushIOSKey(),250),!0}return e.keyCode!=229&&this.view.observer.forceFlush(),!1}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from0?!0:$.safari&&!$.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function km(n){return n.visualViewport?n.visualViewport.height*n.visualViewport.scale/n.document.documentElement.clientHeight<.85:!1}function Ul(n,e){return(t,i)=>{try{return e.call(n,i,t)}catch(s){ze(t.state,s)}}}function Qm(n){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of n){let s=i.spec,r=s&&s.plugin.domEventHandlers,o=s&&s.plugin.domEventObservers;if(r)for(let a in r){let l=r[a];l&&t(a).handlers.push(Ul(i.value,l))}if(o)for(let a in o){let l=o[a];l&&t(a).observers.push(Ul(i.value,l))}}for(let i in Ot)t(i).handlers.push(Ot[i]);for(let i in je)t(i).observers.push(je[i]);return e}const bu=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Pm="dthko",Su=[16,17,18,20,91,92,224,225],Gn=6;function _n(n){return Math.max(0,n)*.7+8}function Cm(n,e){return Math.max(Math.abs(n.clientX-e.clientX),Math.abs(n.clientY-e.clientY))}class Tm{constructor(e,t,i,s){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=s,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Ih(e.contentDOM),this.atoms=e.state.facet(Ln).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(J.allowMultipleSelections)&&Rm(e,t),this.dragging=Km(e,t)&&wu(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Cm(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,s=0,r=0,o=this.view.win.innerWidth,a=this.view.win.innerHeight;this.scrollParents.x&&({left:s,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:a}=this.scrollParents.y.getBoundingClientRect());let l=Pa(this.view);e.clientX-l.left<=s+Gn?t=-_n(s-e.clientX):e.clientX+l.right>=o-Gn&&(t=_n(e.clientX-o)),e.clientY-l.top<=r+Gn?i=-_n(r-e.clientY):e.clientY+l.bottom>=a-Gn&&(i=_n(e.clientY-a)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=gu(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function Rm(n,e){let t=n.state.facet(eu);return t.length?t[0](e):$.mac?e.metaKey:e.ctrlKey}function $m(n,e){let t=n.state.facet(tu);return t.length?t[0](e):$.mac?!e.altKey:!e.ctrlKey}function Km(n,e){let{main:t}=n.state.selection;if(t.empty)return!1;let i=kn(n.root);if(!i||i.rangeCount==0)return!0;let s=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Zm(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=n.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=Se.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}const Ot=Object.create(null),je=Object.create(null),xu=$.ie&&$.ie_version<15||$.ios&&$.webkit_version<604;function Mm(n){let e=n.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{n.focus(),t.remove(),vu(n,t.value)},50)}function gr(n,e,t){for(let i of n.facet(e))t=i(t,n);return t}function vu(n,e){e=gr(n.state,va,e);let{state:t}=n,i,s=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(Wo!=null&&t.selection.ranges.every(l=>l.empty)&&Wo==r.toString()){let l=-1;i=t.changeByRange(c=>{let h=t.doc.lineAt(c.from);if(h.from==l)return{range:c};l=h.from;let u=t.toText((o?r.line(s++).text:e)+t.lineBreak);return{changes:{from:h.from,insert:u},range:A.cursor(c.from+u.length)}})}else o?i=t.changeByRange(l=>{let c=r.line(s++);return{changes:{from:l.from,to:l.to,insert:c.text},range:A.cursor(l.from+c.length)}}):i=t.replaceSelection(r);n.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}je.scroll=n=>{let e=n.inputState;e.lastScrollTop=n.scrollDOM.scrollTop,e.lastScrollLeft=n.scrollDOM.scrollLeft,$.ios&&!e.touchActive&&(e.lastIOSMomentumScroll=Date.now())};je.wheel=je.mousewheel=n=>{n.inputState.lastWheelEvent=Date.now()};Ot.keydown=(n,e)=>(n.inputState.setSelectionOrigin("select"),e.keyCode==27&&n.inputState.tabFocusMode!=0&&(n.inputState.tabFocusMode=Date.now()+2e3),!1);je.touchstart=(n,e)=>{let t=n.inputState,i=e.targetTouches[0];t.touchActive=!0,t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};je.touchmove=n=>{n.inputState.setSelectionOrigin("select.pointer")};je.touchend=(n,e)=>{n.inputState.touchActive=!1};Ot.mousedown=(n,e)=>{if(n.observer.flush(),n.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of n.state.facet(iu))if(t=i(n,e),t)break;if(!t&&e.button==0&&(t=Um(n,e)),t){let i=!n.hasFocus;n.inputState.startMouseSelection(new Tm(n,e,t,i)),i&&n.observer.ignore(()=>{zh(n.contentDOM);let r=n.root.activeElement;r&&!r.contains(n.contentDOM)&&r.blur()});let s=n.inputState.mouseSelection;if(s)return s.start(e),s.dragging===!1}else n.inputState.setSelectionOrigin("select.pointer");return!1};function Fl(n,e,t,i){if(i==1)return A.cursor(e,t);if(i==2)return um(n.state,e,t);{let s=n.docView.lineAt(e,t),r=n.state.doc.lineAt(s?s.posAtEnd:e),o=s?s.posAtStart:r.from,a=s?s.posAtEnd:r.to;return aDate.now()-400&&Math.abs(e.clientX-n.clientX)<2&&Math.abs(e.clientY-n.clientY)<2?(Ll+1)%3:1}function Um(n,e){let t=n.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=wu(e),s=n.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),s=s.map(r.changes))},get(r,o,a){let l=n.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),c,h=Fl(n,l.pos,l.assoc,i);if(t.pos!=l.pos&&!o){let u=Fl(n,t.pos,t.assoc,i),f=Math.min(u.from,h.from),d=Math.max(u.to,h.to);h=f1&&(c=Fm(s,l.pos))?c:a?s.addRange(h):A.create([h])}}}function Fm(n,e){for(let t=0;t=e)return A.create(n.ranges.slice(0,t).concat(n.ranges.slice(t+1)),n.mainIndex==t?0:n.mainIndex-(n.mainIndex>t?1:0))}return null}Ot.dragstart=(n,e)=>{let{selection:{main:t}}=n.state;if(e.target.draggable){let s=n.docView.tile.nearest(e.target);if(s&&s.isWidget()){let r=s.posAtStart,o=r+s.length;(r>=t.to||o<=t.from)&&(t=A.undirectionalRange(r,o))}}let{inputState:i}=n;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",gr(n.state,wa,n.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Ot.dragend=n=>(n.inputState.draggedContent=null,!1);function Bl(n,e,t,i){if(t=gr(n.state,va,t),!t)return;let s=n.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=n.inputState,o=i&&r&&$m(n,e)?{from:r.from,to:r.to}:null,a={from:s,insert:t},l=n.state.changes(o?[o,a]:a);n.focus(),n.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),n.inputState.draggedContent=null}Ot.drop=(n,e)=>{if(!e.dataTransfer)return!1;if(n.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),s=0,r=()=>{++s==t.length&&Bl(n,e,i.filter(o=>o!=null).join(n.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(a.result)||(i[o]=a.result),r()},a.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Bl(n,e,i,!0),!0}return!1};Ot.paste=(n,e)=>{if(n.state.readOnly)return!0;n.observer.flush();let t=xu?null:e.clipboardData;return t?(vu(n,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Mm(n),!1)};function Dm(n,e){let t=n.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),n.focus()},50)}function Lm(n){let e=[],t=[],i=!1;for(let s of n.selection.ranges)s.empty||(e.push(n.sliceDoc(s.from,s.to)),t.push(s));if(!e.length){let s=-1;for(let{from:r}of n.selection.ranges){let o=n.doc.lineAt(r);o.number>s&&(e.push(o.text),t.push({from:o.from,to:Math.min(n.doc.length,o.to+1)})),s=o.number}i=!0}return{text:gr(n,wa,e.join(n.lineBreak)),ranges:t,linewise:i}}let Wo=null;Ot.copy=Ot.cut=(n,e)=>{if(!gn(n.contentDOM,n.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:s}=Lm(n.state);if(!t&&!s)return!1;Wo=s?t:null,e.type=="cut"&&!n.state.readOnly&&n.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=xu?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(Dm(n,t),!1)};const ku=zt.define();function Qu(n,e){let t=[];for(let i of n.facet(ru)){let s=i(n,e);s&&t.push(s)}return t.length?n.update({effects:t,annotations:ku.of(!0)}):null}function Pu(n){setTimeout(()=>{let e=n.hasFocus;if(e!=n.inputState.notifiedFocused){let t=Qu(n.state,e);t?n.dispatch(t):n.update([])}},10)}je.focus=n=>{n.inputState.lastFocusTime=Date.now(),!n.scrollDOM.scrollTop&&(n.inputState.lastScrollTop||n.inputState.lastScrollLeft)&&(n.scrollDOM.scrollTop=n.inputState.lastScrollTop,n.scrollDOM.scrollLeft=n.inputState.lastScrollLeft),Pu(n)};je.blur=n=>{n.observer.clearSelectionRange(),Pu(n)};je.compositionstart=je.compositionupdate=n=>{n.observer.editContext||(n.inputState.compositionFirstChange==null&&(n.inputState.compositionFirstChange=!0),n.inputState.composing<0&&(n.inputState.composing=0))};je.compositionend=n=>{n.observer.editContext||(n.inputState.composing=-1,n.inputState.compositionEndedAt=Date.now(),n.inputState.compositionPendingKey=!0,n.inputState.compositionPendingChange=n.observer.pendingRecords().length>0,n.inputState.compositionFirstChange=null,$.chrome&&$.android?n.observer.flushSoon():n.inputState.compositionPendingChange?Promise.resolve().then(()=>n.observer.flush()):setTimeout(()=>{n.inputState.composing<0&&n.docView.hasComposition&&n.update([])},50))};je.contextmenu=n=>{n.inputState.lastContextMenu=Date.now()};Ot.beforeinput=(n,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(n.inputState.insertingText=e.data,n.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&n.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let a=o[0],l=n.posAtDOM(a.startContainer,a.startOffset),c=n.posAtDOM(a.endContainer,a.endOffset);return Ca(n,{from:l,to:c,insert:n.state.toText(r)},null),!0}}let s;if($.chrome&&$.android&&(s=bu.find(r=>r.inputType==e.inputType))&&(n.observer.delayAndroidKey(s.key,s.keyCode),s.key=="Backspace"||s.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&n.hasFocus&&(n.contentDOM.blur(),n.focus())},100)}return $.ios&&e.inputType=="deleteContentForward"&&n.observer.flushSoon(),$.safari&&e.inputType=="insertText"&&n.inputState.composing>=0&&setTimeout(()=>je.compositionend(n,e),20),!1};const Il=new Set;function Xm(n){Il.has(n)||(Il.add(n),n.addEventListener("copy",()=>{}),n.addEventListener("cut",()=>{}))}const Wl=["pre-wrap","normal","pre-line","break-spaces"];let qi=!1;function ql(){qi=!1}class Bm{constructor(e){this.lineWrapping=e,this.doc=se.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return Wl.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,l=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=a;if(this.lineWrapping=a,this.lineHeight=t,this.charWidth=i,this.textHeight=s,this.lineLength=r,l){this.heightSamples={};for(let c=0;c0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Ss&&(qi=!0),this.height=e)}replace(e,t,i){return Ve.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,s){let r=this,o=i.doc;for(let a=s.length-1;a>=0;a--){let{fromA:l,toA:c,fromB:h,toB:u}=s[a],f=r.lineAt(l,pe.ByPosNoHeight,i.setDoc(t),0,0),d=f.to>=c?f:r.lineAt(c,pe.ByPosNoHeight,i,0,0);for(u+=d.to-c,c=d.to;a>0&&f.from<=s[a-1].toA;)l=s[a-1].fromA,h=s[a-1].fromB,a--,lr*2){let a=e[t-1];a.break?e.splice(--t,1,a.left,null,a.right):e.splice(--t,1,a.left,a.right),i+=1+a.break,s-=a.size}else if(r>s*2){let a=e[i];a.break?e.splice(i,1,a.left,null,a.right):e.splice(i,1,a.left,a.right),i+=2+a.break,r-=a.size}else break;else if(s=r&&o(this.lineAt(0,pe.ByPos,i,s,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more&&this.setMeasuredHeight(s),this.outdated=!1,this}toString(){return`block(${this.length})`}}class ot extends Cu{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new dt(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let s=i[0];return i.length==1&&(s instanceof ot||s instanceof Ee&&s.flags&4)&&Math.abs(this.length-s.length)<10?(s instanceof Ee?s=new ot(s.length,this.height,this.spaceAbove):s.height=this.height,this.outdated||(s.outdated=!1),s):Ve.of(i)}updateHeight(e,t=0,i=!1,s){return s&&s.from<=t&&s.more?this.setMeasuredHeight(s):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class Ee extends Ve{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,s=e.doc.lineAt(t+this.length).number,r=s-i+1,o,a=0;if(e.lineWrapping){let l=Math.min(this.height,e.lineHeight*r);o=l/r,this.length>r+1&&(a=(this.height-l)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:s,perLine:o,perChar:a}}blockAt(e,t,i,s){let{firstLine:r,lastLine:o,perLine:a,perChar:l}=this.heightMetrics(t,s);if(t.lineWrapping){let c=s+(e0){let r=i[i.length-1];r instanceof Ee?i[i.length-1]=new Ee(r.length+s):i.push(null,new Ee(s-1))}if(e>0){let r=i[0];r instanceof Ee?i[0]=new Ee(e+r.length):i.unshift(new Ee(e-1),null)}return Ve.of(i)}decomposeLeft(e,t){t.push(new Ee(e-1),null)}decomposeRight(e,t){t.push(null,new Ee(this.length-e-1))}updateHeight(e,t=0,i=!1,s){let r=t+this.length;if(s&&s.from<=t+this.length&&s.more){let o=[],a=Math.max(t,s.from),l=-1;for(s.from>t&&o.push(new Ee(s.from-t-1).updateHeight(e,t));a<=r&&s.more;){let h=e.doc.lineAt(a).length;o.length&&o.push(null);let u=s.heights[s.index++],f=0;u<0&&(f=-u,u=s.heights[s.index++]),l==-1?l=u:Math.abs(u-l)>=Ss&&(l=-2);let d=new ot(h,u,f);d.outdated=!1,o.push(d),a+=h+1}a<=r&&o.push(null,new Ee(r-a).updateHeight(e,a));let c=Ve.of(o);return(l<0||Math.abs(c.height-this.height)>=Ss||Math.abs(l-this.heightMetrics(e,t).perLine)>=Ss)&&(qi=!0),Ds(this,c)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class qm extends Ve{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,s){let r=i+this.left.height;return ea))return c;let h=t==pe.ByPosNoHeight?pe.ByPosNoHeight:pe.ByPos;return l?c.join(this.right.lineAt(a,h,i,o,a)):this.left.lineAt(a,h,i,s,r).join(c)}forEachLine(e,t,i,s,r,o){let a=s+this.left.height,l=r+this.left.length+this.break;if(this.break)e=l&&this.right.forEachLine(e,t,i,a,l,o);else{let c=this.lineAt(l,pe.ByPos,i,s,r);e=e&&c.from<=t&&o(c),t>c.to&&this.right.forEachLine(c.to+1,t,i,a,l,o)}}replace(e,t,i){let s=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-s,t-s,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let a of i)r.push(a);if(e>0&&zl(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,s=i+this.break;if(e>=s)return this.right.decomposeRight(e-s,t);e2*t.size||t.size>2*e.size?Ve.of(this.break?[e,null,t]:[e,t]):(this.left=Ds(this.left,e),this.right=Ds(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,s){let{left:r,right:o}=this,a=t+r.length+this.break,l=null;return s&&s.from<=t+r.length&&s.more?l=r=r.updateHeight(e,t,i,s):r.updateHeight(e,t,i),s&&s.from<=a+o.length&&s.more?l=o=o.updateHeight(e,a,i,s):o.updateHeight(e,a,i),l?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function zl(n,e){let t,i;n[e]==null&&(t=n[e-1])instanceof Ee&&(i=n[e+1])instanceof Ee&&n.splice(e-1,3,new Ee(t.length+1+i.length))}const zm=5;class Ta{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),s=this.nodes[this.nodes.length-1];s instanceof ot?s.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new ot(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=zm)&&this.addLineDeco(s,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new ot(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new Ee(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof ot)return e;let t=new ot(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let s=this.ensureLine();s.length+=i,s.collapsed+=i,s.widgetHeight=Math.max(s.widgetHeight,e),s.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof ot)&&!this.isCovered?this.nodes.push(new ot(0,-1,0)):(this.writtenToh.clientHeight||h.scrollWidth>h.clientWidth)&&u.overflow!="visible"){let f=h.getBoundingClientRect();r=Math.max(r,f.left),o=Math.min(o,f.right),a=Math.max(a,f.top),l=Math.min(c==n.parentNode?s.innerHeight:l,f.bottom)}c=u.position=="absolute"||u.position=="fixed"?h.offsetParent:h.parentNode}else if(c.nodeType==11)c=c.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:a-(t.top+e),bottom:Math.max(a,l)-(t.top+e)}}function Nm(n){let e=n.getBoundingClientRect(),t=n.ownerDocument.defaultView||window;return e.left0&&e.top0}function Hm(n,e){let t=n.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class Xr{constructor(e,t,i,s){this.from=e,this.to=t,this.size=i,this.displaySize=s}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof s!="function"&&s.class=="cm-lineWrapping");this.heightOracle=new Bm(i),this.stateDeco=Yl(t),this.heightMap=Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle.setDoc(t.doc),[new ct(0,0,0,t.doc.length)]);for(let s=0;s<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());s++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=I.set(this.lineGaps.map(s=>s.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let s=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>s>=r&&s<=o)){let{from:r,to:o}=this.lineBlockAt(s);e.push(new Jn(r,o))}}return this.viewports=e.sort((i,s)=>i.from-s.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?jl:new Ra(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(un(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=Yl(this.state);let s=e.changedRanges,r=ct.extendWithRanges(s,Vm(i,this.stateDeco,e?e.changes:Re.empty(this.state.doc.length))),o=this.heightMap.height,a=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);ql(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||qi)&&(e.flags|=2),a?(this.scrollAnchorPos=e.changes.mapPos(a.from,-1),this.scrollAnchorHeight=a.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let l=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.headl.to)||!this.viewportIsAppropriate(l))&&(l=this.getViewport(0,t));let c=l.from!=this.viewport.from||l.to!=this.viewport.to;this.viewport=l,e.flags|=this.updateForViewport(),(c||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(au)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),s=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?fe.RTL:fe.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",a=t.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let c=0,h=0;if(a.width&&a.height){let{scaleX:Q,scaleY:P}=Bh(t,a);(Q>.005&&Math.abs(this.scaleX-Q)>.005||P>.005&&Math.abs(this.scaleY-P)>.005)&&(this.scaleX=Q,this.scaleY=P,c|=16,o=l=!0)}let u=(parseInt(i.paddingTop)||0)*this.scaleY,f=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=u||this.paddingBottom!=f)&&(this.paddingTop=u,this.paddingBottom=f,c|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=e.scrollDOM.clientWidth,c|=16);let d=Ih(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=Vh(this.scrollParent||e.win);let m=(this.printing?Hm:Ym)(t,this.paddingTop),g=m.top-this.pixelViewport.top,y=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let x=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(x!=this.inView&&(this.inView=x,x&&(l=!0)),!this.inView&&!this.scrollTarget&&!Nm(e.dom))return 0;let b=a.width;if((this.contentDOMWidth!=b||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=a.width,this.editorHeight=e.scrollDOM.clientHeight,c|=16),l){let Q=e.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(Q)&&(o=!0),o||s.lineWrapping&&Math.abs(b-this.contentDOMWidth)>s.charWidth){let{lineHeight:P,charWidth:w,textHeight:L}=e.docView.measureTextSize();o=P>0&&s.refresh(r,P,w,L,Math.max(5,b/w),Q),o&&(e.docView.minWidth=0,c|=16)}g>0&&y>0?h=Math.max(g,y):g<0&&y<0&&(h=Math.min(g,y)),ql();for(let P of this.viewports){let w=P.from==this.viewport.from?Q:e.docView.measureVisibleLineHeights(P);this.heightMap=(o?Ve.empty().applyChanges(this.stateDeco,se.empty,this.heightOracle,[new ct(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new Im(P.from,w))}qi&&(c|=2)}let C=!this.viewportIsAppropriate(this.viewport,h)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return C&&(c&2&&(c|=this.updateScaler()),this.viewport=this.getViewport(h,this.scrollTarget),c|=this.updateForViewport()),(c&2||C)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),c|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),c}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),s=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:a}=this,l=new Jn(s.lineAt(o-i*1e3,pe.ByHeight,r,0,0).from,s.lineAt(a+(1-i)*1e3,pe.ByHeight,r,0,0).to);if(t){let{head:c}=t.range;if(cl.to){let h=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),u=s.lineAt(c,pe.ByPos,r,0,0),f;t.y=="center"?f=(u.top+u.bottom)/2-h/2:t.y=="start"||t.y=="nearest"&&c=a+Math.max(10,Math.min(i,250)))&&s>o-2*1e3&&r>1,o=s<<1;if(this.defaultTextDirection!=fe.LTR&&!i)return[];let a=[],l=(h,u,f,d)=>{if(u-hh&&yy.from>=f.from&&y.to<=f.to&&Math.abs(y.from-h)y.fromx));if(!g){if(ub.from<=u&&b.to>=u)){let b=t.moveToLineBoundary(A.cursor(u),!1,!0).head;b>h&&(u=b)}let y=this.gapSize(f,h,u,d),x=i||y<2e6?y:2e6;g=new Xr(h,u,y,x)}a.push(g)},c=h=>{if(h.length2e6)for(let P of e)P.from>=h.from&&P.fromh.from&&l(h.from,d,h,u),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];H.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let s=0;if(i.length!=this.visibleRanges.length)s=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||un(this.heightMap.lineAt(e,pe.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||un(this.heightMap.lineAt(this.scaler.fromDOM(e),pe.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return un(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class Jn{constructor(e,t){this.from=e,this.to=t}}function _m(n,e,t){let i=[],s=n,r=0;return H.spans(t,n,e,{span(){},point(o,a){o>s&&(i.push({from:s,to:o}),r+=o-s),s=a}},20),s=1)return e[e.length-1].to;let i=Math.floor(n*t);for(let s=0;;s++){let{from:r,to:o}=e[s],a=o-r;if(i<=a)return r+i;i-=a}}function ts(n,e){let t=0;for(let{from:i,to:s}of n.ranges){if(e<=s){t+=e-i;break}t+=s-i}return t/n.total}function Jm(n,e){for(let t of n)if(e(t))return t}const jl={toDOM(n){return n},fromDOM(n){return n},scale:1,eq(n){return n==this}};function Yl(n){let e=n.facet(dr).filter(i=>typeof i!="function"),t=n.facet(Qa).filter(i=>typeof i!="function");return t.length&&e.push(H.join(t)),e}class Ra{constructor(e,t,i){let s=0,r=0,o=0;this.viewports=i.map(({from:a,to:l})=>{let c=t.lineAt(a,pe.ByPos,e,0,0).top,h=t.lineAt(l,pe.ByPos,e,0,0).bottom;return s+=h-c,{from:a,to:l,top:c,bottom:h,domTop:0,domBottom:0}}),this.scale=(7e6-s)/(t.height-s);for(let a of this.viewports)a.domTop=o+(a.top-r)*this.scale,o=a.domBottom=a.domTop+(a.bottom-a.top),r=a.bottom}toDOM(e){for(let t=0,i=0,s=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}}function un(n,e){if(e.scale==1)return n;let t=e.toDOM(n.top),i=e.toDOM(n.bottom);return new dt(n.from,n.length,t,i-t,Array.isArray(n._content)?n._content.map(s=>un(s,e)):n._content)}const is=Z.define({combine:n=>n.join(" ")}),qo=Z.define({combine:n=>n.indexOf(!0)>-1}),zo=ti.newName(),Tu=ti.newName(),Ru=ti.newName(),$u={"&light":"."+Tu,"&dark":"."+Ru};function Vo(n,e,t){return new ti(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,s=>{if(s=="&")return n;if(!t||!t[s])throw new RangeError(`Unsupported selector: ${s}`);return t[s]}):n+" "+i}})}const eg=Vo("."+zo,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},".cm-panels-top":{top:"0"},".cm-panels-bottom":{bottom:"0"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},$u),tg={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Br=$.ie&&$.ie_version<=11;class ig{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new $p,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);($.ie&&$.ie_version<=11||$.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&$.android&&e.constructor.EDIT_CONTEXT!==!1&&!($.chrome&&$.chrome_version<126)&&(this.editContext=new sg(e),e.state.facet(Lt)&&(e.contentDOM.editContext=this.editContext.editContext)),Br&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,s=this.selectionRange;if(i.state.facet(Lt)?i.root.activeElement!=this.dom:!gn(this.dom,s))return;let r=s.anchorNode&&i.docView.tile.nearest(s.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}($.ie&&$.ie_version<=11||$.android&&$.chrome)&&!i.state.selection.main.empty&&s.focusNode&&On(s.focusNode,s.focusOffset,s.anchorNode,s.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=kn(e.root);if(!t)return!1;let i=$.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&ng(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let s=gn(this.dom,i);return s&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&Ei(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(s)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,s=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(s=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:s}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),s=this.selectionChanged&&gn(this.dom,this.selectionRange);if(e<0&&!s)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new bm(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,s=yu(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!Fs(this.view.state.selection,t.newSel.main))&&this.view.update([]),s}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=Nl(t,e.previousSibling||e.target.previousSibling,-1),s=Nl(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:s?t.posBefore(s):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(Lt)!=e.state.facet(Lt)&&(e.view.contentDOM.editContext=e.state.facet(Lt)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let s of this.scrollTargets)s.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function Nl(n,e,t){for(;e;){let i=Se.get(e);if(i&&i.parent==n)return i;let s=e.parentNode;e=s!=n.dom?s:t>0?e.nextSibling:e.previousSibling}return null}function Hl(n,e){let t=e.startContainer,i=e.startOffset,s=e.endContainer,r=e.endOffset,o=n.docView.domAtPos(n.state.selection.main.anchor,1);return On(o.node,o.offset,s,r)&&([t,i,s,r]=[s,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:s,focusOffset:r}}function ng(n,e){if(e.getComposedRanges){let s=e.getComposedRanges(n.root)[0];if(s)return Hl(n,s)}let t=null;function i(s){s.preventDefault(),s.stopImmediatePropagation(),t=s.getTargetRanges()[0]}return n.contentDOM.addEventListener("beforeinput",i,!0),n.dom.ownerDocument.execCommand("indent"),n.contentDOM.removeEventListener("beforeinput",i,!0),t?Hl(n,t):null}class sg{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let s=e.state.selection.main,{anchor:r,head:o}=s,a=this.toEditorPos(i.updateRangeStart),l=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:a,drifted:!1});let c=l-a>i.text.length;a==this.from&&rthis.to&&(l=r);let h=Au(e.state.sliceDoc(a,l),i.text,(c?s.from:s.to)-a,c?"end":null);if(!h){let f=A.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));Fs(f,s)||e.dispatch({selection:f,userEvent:"select"});return}let u={from:h.from+a,to:h.toA+a,insert:se.of(i.text.slice(h.from,h.toB).split(` +`))};if(($.mac||$.android)&&u.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(u={from:a,to:l,insert:se.of([i.text.replace("."," ")])}),this.pendingContextChange=u,!e.state.readOnly){let f=this.to-this.from+(u.to-u.from+u.insert.length);Ca(e,u,A.single(this.toEditorPos(i.selectionStart,f),this.toEditorPos(i.selectionEnd,f)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),u.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let s=[],r=null;for(let o=this.toEditorPos(i.rangeStart),a=this.toEditorPos(i.rangeEnd);o{let s=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,a=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(a)){let l=this.toEditorPos(r.rangeStart),c=this.toEditorPos(r.rangeEnd);if(l{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{let s=kn(i.root);s&&s.rangeCount&&this.editContext.updateSelectionBounds(s.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,s=this.pendingContextChange;return e.changes.iterChanges((r,o,a,l,c)=>{if(i)return;let h=c.length-(o-r);if(s&&o>=s.to)if(s.from==r&&s.to==o&&s.insert.eq(c)){s=this.pendingContextChange=null,t+=h,this.to+=h;return}else s=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=h,this.to+=h;else if(rthis.to||this.to-this.from+c.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),c.toString()),this.to+=h}t+=h}),s&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(s=>!s.isUserEvent("input.type")&&s.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),s=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=s)&&this.editContext.updateSelection(i,s)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class K{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(s=>s.forEach(r=>i(r,this)))||(s=>this.update(s)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Kp(e.parent)||document,this.viewState=new Vl(this,e.state||J.create(e)),e.scrollTo&&e.scrollTo.is(Hn)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Ti).map(s=>new Er(s));for(let s of this.plugins)s.update(this);this.observer=new ig(this),this.inputState=new wm(this),this.inputState.ensureHandlers(this.plugins),this.docView=new Zl(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof Pe?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,s,r=this.state;for(let f of e){if(f.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=f.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,a=0,l=null;e.some(f=>f.annotation(ku))?(this.inputState.notifiedFocused=o,a=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,l=Qu(r,o),l||(a=1));let c=this.observer.delayedAndroidKey,h=null;if(c?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(h=null)):this.observer.clear(),r.facet(J.phrases)!=this.state.facet(J.phrases))return this.setState(r);s=Ms.create(this,r,e),s.flags|=a;let u=this.viewState.scrollTarget;try{this.updateState=2;for(let f of e){if(u&&(u=u.map(f.changes)),f.scrollIntoView){let{main:d}=f.state.selection,{x:p,y:m}=this.state.facet(K.cursorScrollMargin);u=new Ui(d.empty?d:A.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of f.effects)d.is(Hn)&&(u=d.value.clip(this.state))}this.viewState.update(s,u),this.bidiCache=Ls.update(this.bidiCache,s.changes),s.empty||(this.updatePlugins(s),this.inputState.update(s)),t=this.docView.update(s),this.state.facet(hn)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(f=>f.isUserEvent("select.pointer")))}finally{this.updateState=0}if(s.startState.facet(is)!=s.state.facet(is)&&(this.viewState.mustMeasureContent=!0),(t||i||u||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!s.empty)for(let f of this.state.facet(Lo))try{f(s)}catch(d){ze(this.state,d,"update listener")}(l||h)&&Promise.resolve().then(()=>{l&&this.state==l.startState&&this.dispatch(l),h&&!yu(this,h)&&c.force&&Ei(this.contentDOM,c.key,c.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new Vl(this,e),this.plugins=e.facet(Ti).map(i=>new Er(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new Zl(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(Ti),i=e.state.facet(Ti);if(t!=i){let s=[];for(let r of i){let o=t.indexOf(r);if(o<0)s.push(new Er(r));else{let a=this.plugins[o];a.mustUpdate=e,s.push(a)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=s,this.pluginMap.clear()}else for(let s of this.plugins)s.mustUpdate=e;for(let s=0;s-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,s=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(s-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let a=0;;a++){if(o<0)if(Vh(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(s);r=d.from,o=d.top}this.updateState=1;let l=this.viewState.measure();if(!l&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(a>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let c=[];l&4||([this.measureRequests,c]=[c,this.measureRequests]);let h=c.map(d=>{try{return d.read(this)}catch(p){return ze(this.state,p),Gl}}),u=Ms.create(this,this.state,[]),f=!1;u.flags|=l,t?t.flags|=l:t=u,this.updateState=2,u.empty||(this.updatePlugins(u),this.inputState.update(u),this.updateAttrs(),f=this.docView.update(u),f&&this.docViewUpdate());for(let d=0;d1||p<-1)&&!($.ios&&this.inputState.lastIOSMomentumScroll>Date.now()-100)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){s=s+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let a of this.state.facet(Lo))a(t)}get themeClasses(){return zo+" "+(this.state.facet(qo)?Ru:Tu)+" "+this.state.facet(is)}updateAttrs(){let e=_l(this,hu,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(Lt)?"true":"false",class:"cm-content",style:`${$.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),_l(this,ka,t);let i=this.observer.ignore(()=>{let s=Pl(this.contentDOM,this.contentAttrs,t),r=Pl(this.dom,this.editorAttrs,e);return s||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let s of i.effects)if(s.is(K.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=s.value}}mountStyles(){this.styleModules=this.state.facet(hn);let e=this.state.facet(K.cspNonce);ti.mount(this.root,this.styleModules.concat(eg).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return Lr(this,e,Ml(this,e,t,i))}moveByGroup(e,t){return Lr(this,e,Ml(this,e,t,i=>pm(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),s=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return A.cursor(r.side(t,s)+e.from,r.forward(!t,s)?1:-1)}moveToLineBoundary(e,t,i=!0){return dm(this,e,t,i)}moveVertically(e,t,i){return Lr(this,e,mm(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=Io(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),Io(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.state.doc.lineAt(e),s=this.bidiSpans(i),r=s[Ct.find(s,e-i.from,-1,t)];return this.docView.coordsAt(e,t,r.dir==fe.RTL)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(ou)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>rg)return _h(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||Gh(r.isolates,i=Rl(this,e))))return r.order;i||(i=Rl(this,e));let s=Xp(e.text,t,i);return this.bidiCache.push(new Ls(e.from,e.to,t,i,!0,s)),s}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||$.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{zh(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,s,r,o;return Hn.of(new Ui(typeof e=="number"?A.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(s=t.x)!==null&&s!==void 0?s:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Hn.of(new Ui(A.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return xe.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return xe.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=ti.newName(),s=[is.of(i),hn.of(Vo(`.${i}`,e))];return t&&t.dark&&s.push(qo.of(!0)),s}static baseTheme(e){return oi.lowest(hn.of(Vo("."+zo,e,$u)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),s=i&&Se.get(i)||Se.get(e);return((t=s?.root)===null||t===void 0?void 0:t.view)||null}}K.styleModule=hn;K.inputHandler=su;K.clipboardInputFilter=va;K.clipboardOutputFilter=wa;K.scrollHandler=lu;K.focusChangeEffect=ru;K.perLineTextDirection=ou;K.exceptionSink=nu;K.updateListener=Lo;K.editable=Lt;K.mouseSelectionStyle=iu;K.dragMovesSelection=tu;K.clickAddsSelectionRange=eu;K.decorations=dr;K.blockWrappers=uu;K.outerDecorations=Qa;K.atomicRanges=Ln;K.bidiIsolatedRanges=fu;K.cursorScrollMargin=Z.define({combine:n=>{let e=5,t=5;for(let i of n)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});K.scrollMargins=du;K.darkTheme=qo;K.cspNonce=Z.define({combine:n=>n.length?n[0]:""});K.contentAttributes=ka;K.editorAttributes=hu;K.lineWrapping=K.contentAttributes.of({class:"cm-lineWrapping"});K.announce=Y.define();const rg=4096,Gl={};class Ls{constructor(e,t,i,s,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=s,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],s=e.length?e[e.length-1].dir:fe.LTR;for(let r=Math.max(0,e.length-10);r=0;s--){let r=i[s],o=typeof r=="function"?r(n):r;o&&ba(o,t)}return t}const og=$.mac?"mac":$.windows?"win":$.linux?"linux":"key";function ag(n,e){const t=n.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let s,r,o,a;for(let l=0;li.concat(s),[]))),t}function cg(n,e,t){return Zu(Ku(n.state),e,n,t)}let Ht=null;const hg=4e3;function ug(n,e=og){let t=Object.create(null),i=Object.create(null),s=(o,a)=>{let l=i[o];if(l==null)i[o]=a;else if(l!=a)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,a,l,c,h)=>{var u,f;let d=t[o]||(t[o]=Object.create(null)),p=a.split(/ (?!$)/).map(y=>ag(y,e));for(let y=1;y{let C=Ht={view:b,prefix:x,scope:o};return setTimeout(()=>{Ht==C&&(Ht=null)},hg),!0}]})}let m=p.join(" ");s(m,!1);let g=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((f=(u=d._any)===null||u===void 0?void 0:u.run)===null||f===void 0?void 0:f.slice())||[]});l&&g.run.push(l),c&&(g.preventDefault=!0),h&&(g.stopPropagation=!0)};for(let o of n){let a=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let c of a){let h=t[c]||(t[c]=Object.create(null));h._any||(h._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:u}=o;for(let f in h)h[f].run.push(d=>u(d,jo))}let l=o[e]||o.key;if(l)for(let c of a)r(c,l,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(c,"Shift-"+l,o.shift,o.preventDefault,o.stopPropagation)}return t}let jo=null;function Zu(n,e,t,i){jo=e;let s=kp(e),r=Ne(s,0),o=Qt(r)==s.length&&s!=" ",a="",l=!1,c=!1,h=!1;Ht&&Ht.view==t&&Ht.scope==i&&(a=Ht.prefix+" ",Su.indexOf(e.keyCode)<0&&(c=!0,Ht=null));let u=new Set,f=g=>{if(g){for(let y of g.run)if(!u.has(y)&&(u.add(y),y(t)))return g.stopPropagation&&(h=!0),!0;g.preventDefault&&(g.stopPropagation&&(h=!0),c=!0)}return!1},d=n[i],p,m;return d&&(f(d[a+ns(s,e,!o)])?l=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!($.windows&&e.ctrlKey&&e.altKey)&&!($.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=ii[e.keyCode])&&p!=s?(f(d[a+ns(p,e,!0)])||e.shiftKey&&(m=vn[e.keyCode])!=s&&m!=p&&f(d[a+ns(m,e,!1)]))&&(l=!0):o&&e.shiftKey&&f(d[a+ns(s,e,!0)])&&(l=!0),!l&&f(d._any)&&(l=!0)),c&&(l=!0),l&&h&&e.stopPropagation(),jo=null,l}class gi{constructor(e,t,i,s,r){this.className=e,this.left=t,this.top=i,this.width=s,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let s=e.coordsAtPos(i.head,i.assoc||1);if(!s)return[];let r=Mu(e);return[new gi(t,s.left-r.left,s.top-r.top,null,s.bottom-s.top)]}else return fg(e,t,i)}}function Mu(n){let e=n.scrollDOM.getBoundingClientRect();return{left:(n.textDirection==fe.LTR?e.left:e.right-n.scrollDOM.clientWidth*n.scaleX)-n.scrollDOM.scrollLeft*n.scaleX,top:e.top-n.scrollDOM.scrollTop*n.scaleY}}function ec(n,e,t,i){let s=n.coordsAtPos(e,t*2);if(!s)return i;let r=n.dom.getBoundingClientRect(),o=(s.top+s.bottom)/2,a=n.posAtCoords({x:r.left+1,y:o}),l=n.posAtCoords({x:r.right-1,y:o});return a==null||l==null?i:{from:Math.max(i.from,Math.min(a,l)),to:Math.min(i.to,Math.max(a,l))}}function fg(n,e,t){if(t.to<=n.viewport.from||t.from>=n.viewport.to)return[];let i=Math.max(t.from,n.viewport.from),s=Math.min(t.to,n.viewport.to),r=n.textDirection==fe.LTR,o=n.contentDOM,a=o.getBoundingClientRect(),l=Mu(n),c=o.querySelector(".cm-line"),h=c&&window.getComputedStyle(c),u=a.left+(h?parseInt(h.paddingLeft)+Math.min(0,parseInt(h.textIndent)):0),f=a.right-(h?parseInt(h.paddingRight):0),d=Bo(n,i,1),p=Bo(n,s,-1),m=d.type==Le.Text?d:null,g=p.type==Le.Text?p:null;if(m&&(n.lineWrapping||d.widgetLineBreaks)&&(m=ec(n,i,1,m)),g&&(n.lineWrapping||p.widgetLineBreaks)&&(g=ec(n,s,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return x(b(t.from,t.to,m));{let Q=m?b(t.from,null,m):C(d,!1),P=g?b(null,t.to,g):C(p,!0),w=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&Q.bottom+n.defaultLineHeight/2U&&v.from=k)break;ee>M&&F(Math.max(N,M),Q==null&&N<=U,Math.min(ee,k),P==null&&ee>=T,re.dir)}if(M=z.to+1,M>=k)break}return W.length==0&&F(U,Q==null,T,P==null,n.textDirection),{top:L,bottom:D,horizontal:W}}function C(Q,P){let w=a.top+(P?Q.top:Q.bottom);return{top:w,bottom:w,horizontal:[]}}}function dg(n,e){return n.constructor==e.constructor&&n.eq(e)}class pg{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(xs)!=e.state.facet(xs)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(xs);for(;t!dg(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let s of e)s.update&&t&&s.constructor&&this.drawn[i].constructor&&s.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(s.draw(),t);for(;t;){let s=t.nextSibling;t.remove(),t=s}this.drawn=e,$.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const xs=Z.define();function Eu(n){return[xe.define(e=>new pg(e,n)),xs.of(n)]}const zi=Z.define({combine(n){return yt(n,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function mg(n={}){return[zi.of(n),gg,Og,Ag,au.of(!0)]}function Uu(n){return n.startState.facet(zi)!=n.state.facet(zi)}const gg=Eu({above:!0,markers(n){let{state:e}=n,t=e.facet(zi),i=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty||t.drawRangeCursor&&!(r&&$.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",a=s.empty?s:A.cursor(s.head,s.assoc);for(let l of gi.forRange(n,o,a))i.push(l)}}return i},update(n,e){n.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Uu(n);return t&&tc(n.state,e),n.docChanged||n.selectionSet||t},mount(n,e){tc(e.state,n)},class:"cm-cursorLayer"});function tc(n,e){e.style.animationDuration=n.facet(zi).cursorBlinkRate+"ms"}const Og=Eu({above:!1,markers(n){let e=[],{main:t,ranges:i}=n.state.selection;for(let s of i)if(!s.empty)for(let r of gi.forRange(n,"cm-selectionBackground",s))e.push(r);if($.ios&&!t.empty&&n.state.facet(zi).iosSelectionHandles){for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-start",A.cursor(t.from,1)))e.push(s);for(let s of gi.forRange(n,"cm-selectionHandle cm-selectionHandle-end",A.cursor(t.to,1)))e.push(s)}return e},update(n,e){return n.docChanged||n.selectionSet||n.viewportChanged||Uu(n)},class:"cm-selectionLayer"}),yg=$.gecko&&$.gecko_version==153?"#ffffff01":"transparent",Ag=oi.highest(K.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:`${yg} !important`},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),Fu=Y.define({map(n,e){return n==null?null:e.mapPos(n)}}),fn=Te.define({create(){return null},update(n,e){return n!=null&&(n=e.changes.mapPos(n)),e.effects.reduce((t,i)=>i.is(Fu)?i.value:t,n)}}),bg=xe.fromClass(class{constructor(n){this.view=n,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(n){var e;let t=n.state.field(fn);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(n.startState.field(fn)!=t||n.docChanged||n.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:n}=this,e=n.state.field(fn),t=e!=null&&n.coordsAtPos(e);if(!t)return null;let i=n.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+n.scrollDOM.scrollLeft*n.scaleX,top:t.top-i.top+n.scrollDOM.scrollTop*n.scaleY,height:t.bottom-t.top}}drawCursor(n){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;n?(this.cursor.style.left=n.left/e+"px",this.cursor.style.top=n.top/t+"px",this.cursor.style.height=n.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(n){this.view.state.field(fn)!=n&&this.view.dispatch({effects:Fu.of(n)})}},{eventObservers:{dragover(n){this.setDropPos(this.view.posAtCoords({x:n.clientX,y:n.clientY}))},dragleave(n){(n.target==this.view.contentDOM||!this.view.contentDOM.contains(n.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Sg(){return[fn,bg]}function ic(n,e,t,i,s){e.lastIndex=0;for(let r=n.iterRange(t,i),o=t,a;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;a=e.exec(r.value);)s(o+a.index,a)}function xg(n,e){let t=n.visibleRanges;if(t.length==1&&t[0].from==n.viewport.from&&t[0].to==n.viewport.to)return t;let i=[];for(let{from:s,to:r}of t)s=Math.max(n.state.doc.lineAt(s).from,s-e),r=Math.min(n.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=s?i[i.length-1].to=r:i.push({from:s,to:r});return i}class vg{constructor(e){const{regexp:t,decoration:i,decorate:s,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,s)this.addMatch=(a,l,c,h)=>s(h,c,c+a[0].length,a,l);else if(typeof i=="function")this.addMatch=(a,l,c,h)=>{let u=i(a,l,c);u&&h(c,c+a[0].length,u)};else if(i)this.addMatch=(a,l,c,h)=>h(c,c+a[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new It,i=t.add.bind(t);for(let{from:s,to:r}of xg(e,this.maxLength))ic(e.state.doc,this.regexp,s,r,(o,a)=>this.addMatch(a,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,s=-1;return e.docChanged&&e.changes.iterChanges((r,o,a,l)=>{l>=e.view.viewport.from&&a<=e.view.viewport.to&&(i=Math.min(a,i),s=Math.max(l,s))}),e.viewportMoved||s-i>1e3?this.createDeco(e.view):s>-1?this.updateRange(e.view,t.map(e.changes),i,s):t}updateRange(e,t,i,s){for(let r of e.visibleRanges){let o=Math.max(r.from,i),a=Math.min(r.to,s);if(a>=o){let l=e.state.doc.lineAt(o),c=l.tol.from;o--)if(this.boundary.test(l.text[o-1-l.from])){h=o;break}for(;af.push(y.range(m,g));if(l==c)for(this.regexp.lastIndex=h-l.from;(d=this.regexp.exec(l.text))&&d.indexthis.addMatch(g,e,m,p));t=t.update({filterFrom:h,filterTo:u,filter:(m,g)=>mu,add:f})}}return t}}const Yo=/x/.unicode!=null?"gu":"g",wg=new RegExp(`[\0-\b +--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,Yo),kg={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Ir=null;function Qg(){var n;if(Ir==null&&typeof document<"u"&&document.body){let e=document.body.style;Ir=((n=e.tabSize)!==null&&n!==void 0?n:e.MozTabSize)!=null}return Ir||!1}const vs=Z.define({combine(n){let e=yt(n,{render:null,specialChars:wg,addSpecialChars:null});return(e.replaceTabs=!Qg())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,Yo)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Yo)),e}});function Pg(n={}){return[vs.of(n),Cg()]}let nc=null;function Cg(){return nc||(nc=xe.fromClass(class{constructor(n){this.view=n,this.decorations=I.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(n.state.facet(vs)),this.decorations=this.decorator.createDeco(n)}makeDecorator(n){return new vg({regexp:n.specialChars,decoration:(e,t,i)=>{let{doc:s}=t.state,r=Ne(e[0],0);if(r==9){let o=s.lineAt(i),a=t.state.tabSize,l=_i(o.text,a,i-o.from);return I.replace({widget:new Kg((a-l%a)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=I.replace({widget:new $g(n,r)}))},boundary:n.replaceTabs?void 0:/[^]/})}update(n){let e=n.state.facet(vs);n.startState.facet(vs)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(n.view)):this.decorations=this.decorator.updateDeco(n,this.decorations)}},{decorations:n=>n.decorations}))}const Tg="•";function Rg(n){return n>=32?Tg:n==10?"␤":String.fromCharCode(9216+n)}class $g extends Ut{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=Rg(this.code),i=e.state.phrase("Control character")+" "+(kg[this.code]||"0x"+this.code.toString(16)),s=this.options.render&&this.options.render(this.code,i,t);if(s)return s;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}}class Kg extends Ut{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Zg(){return Eg}const Mg=I.line({class:"cm-activeLine"}),Eg=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.docChanged||n.selectionSet)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=-1,t=[];for(let i of n.state.selection.ranges){let s=n.lineBlockAt(i.head);s.from>e&&(t.push(Mg.range(s.from)),e=s.from)}return I.set(t)}},{decorations:n=>n.decorations}),No=2e3;function Ug(n,e,t){let i=Math.min(e.line,t.line),s=Math.max(e.line,t.line),r=[];if(e.off>No||t.off>No||e.col<0||t.col<0){let o=Math.min(e.off,t.off),a=Math.max(e.off,t.off);for(let l=i;l<=s;l++){let c=n.doc.line(l);c.length<=a&&r.push(A.range(c.from+o,c.to+a))}}else{let o=Math.min(e.col,t.col),a=Math.max(e.col,t.col);for(let l=i;l<=s;l++){let c=n.doc.line(l),h=Co(c.text,o,n.tabSize,!0);if(h<0)r.push(A.cursor(c.to));else{let u=Co(c.text,a,n.tabSize);r.push(A.range(c.from+h,c.from+u))}}}return r}function Fg(n,e){let t=n.coordsAtPos(n.viewport.from);return t?Math.round(Math.abs((t.left-e)/n.defaultCharacterWidth)):-1}function sc(n,e){let t=n.posAtCoords({x:e.clientX,y:e.clientY},!1),i=n.state.doc.lineAt(t),s=t-i.from,r=s>No?-1:s==i.length?Fg(n,e.clientX):_i(i.text,n.state.tabSize,t-i.from);return{line:i.number,col:r,off:s}}function Dg(n,e){let t=sc(n,e),i=n.state.selection;return t?{update(s){if(s.docChanged){let r=s.changes.mapPos(s.startState.doc.line(t.line).from),o=s.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(s.changes)}},get(s,r,o){let a=sc(n,s);if(!a)return i;let l=Ug(n.state,t,a);return l.length?o?A.create(l.concat(i.ranges)):A.create(l):i}}:null}function Lg(n){let e=(t=>t.altKey&&t.button==0);return K.mouseSelectionStyle.of((t,i)=>e(i)?Dg(t,i):null)}const Xg={Alt:[18,n=>!!n.altKey],Control:[17,n=>!!n.ctrlKey],Shift:[16,n=>!!n.shiftKey],Meta:[91,n=>!!n.metaKey]},Bg={style:"cursor: crosshair"};function Ig(n={}){let[e,t]=Xg[n.key||"Alt"],i=xe.fromClass(class{constructor(s){this.view=s,this.isDown=!1}set(s){this.isDown!=s&&(this.isDown=s,this.view.update([]))}},{eventObservers:{keydown(s){this.set(s.keyCode==e||t(s))},keyup(s){(s.keyCode==e||!t(s))&&this.set(!1)},mousemove(s){this.set(t(s))}}});return[i,K.contentAttributes.of(s=>{var r;return!((r=s.plugin(i))===null||r===void 0)&&r.isDown?Bg:null})]}const ss="-10000px";class Du{constructor(e,t,i,s){this.facet=t,this.createTooltipView=i,this.removeTooltipView=s,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let s=e.state.facet(this.facet),r=s.filter(l=>l);if(s===this.input){for(let l of this.tooltipViews)l.update&&l.update(e);return!1}let o=[],a=t?[]:null;for(let l=0;lt[c]=l),t.length=a.length),this.input=s,this.tooltips=r,this.tooltipViews=o,!0}}function Wg(n){let e=n.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const Wr=Z.define({combine:n=>{var e,t,i;return{position:$.ios?"absolute":((e=n.find(s=>s.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=n.find(s=>s.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=n.find(s=>s.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||Wg}}}),rc=new WeakMap,$a=xe.fromClass(class{constructor(n){this.view=n,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=n.state.facet(Wr);this.position=e.position,this.parent=e.parent,this.classes=n.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new Du(n,yr,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),n.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let n of this.manager.tooltipViews)this.intersectionObserver.observe(n.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(n){n.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(n,this.above);e&&this.observeIntersection();let t=e||n.geometryChanged,i=n.state.facet(Wr);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let s of this.manager.tooltipViews)s.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let s of this.manager.tooltipViews)this.container.appendChild(s.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(n,e){let t=n.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),n.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let s=document.createElement("div");s.className="cm-tooltip-arrow",t.dom.appendChild(s)}return t.dom.style.position=this.position,t.dom.style.top=ss,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var n,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(n=i.destroy)===null||n===void 0||n.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let n=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if($.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(n=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:n,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),s=Pa(this.view);return{visible:{left:i.left+s.left,top:i.top+s.top,right:i.right-s.right,bottom:i.bottom-s.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let a=this.manager.tooltipViews[o];return a.getCoords?a.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(Wr).tooltipSpace(this.view),scaleX:n,scaleY:e,makeAbsolute:t}}writeMeasure(n){var e;if(n.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let a of this.manager.tooltipViews)a.dom.style.position="absolute"}let{visible:t,space:i,scaleX:s,scaleY:r}=n,o=[];for(let a=0;a=Math.min(t.bottom,i.bottom)||u.rightMath.min(t.right,i.right)+.1)){h.style.top=ss;continue}let d=l.arrow?c.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=f.right-f.left,g=(e=rc.get(c))!==null&&e!==void 0?e:f.bottom-f.top,y=c.offset||zg,x=this.view.textDirection==fe.LTR,b=f.width>i.right-i.left?x?i.left:i.right-f.width:x?Math.max(i.left,Math.min(u.left-(d?14:0)+y.x,i.right-m)):Math.min(Math.max(i.left,u.left-m+(d?14:0)-y.x),i.right-m),C=this.above[a];!l.strictSide&&(C?u.top-g-p-y.yi.bottom)&&C==i.bottom-u.bottom>u.top-i.top&&(C=this.above[a]=!C);let Q=(C?u.top-i.top:i.bottom-u.bottom)-p;if(Qb&&L.topP&&(P=C?L.top-g-2-p:L.bottom+p+2);if(this.position=="absolute"?(h.style.top=(P-n.parent.top)/r+"px",oc(h,(b-n.parent.left)/s)):(h.style.top=P/r+"px",oc(h,b/s)),d){let L=u.left+(x?y.x:-y.x)-(b+14-7);d.style.left=L/s+"px"}c.overlap!==!0&&o.push({left:b,top:P,right:w,bottom:P+g}),h.classList.toggle("cm-tooltip-above",C),h.classList.toggle("cm-tooltip-below",!C),c.positioned&&c.positioned(n.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let n of this.manager.tooltipViews)n.dom.style.top=ss}},{eventObservers:{scroll(){this.maybeMeasure()}}});function oc(n,e){let t=parseInt(n.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(n.style.left=e+"px")}const qg=K.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),zg={x:0,y:0},yr=Z.define({enables:[$a,qg]}),Xs=Z.define({combine:n=>n.reduce((e,t)=>e.concat(t),[])});class Ar{static create(e){return new Ar(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Du(e,Xs,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let s=i[e];if(s!==void 0){if(t===void 0)t=s;else if(t!==s)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Vg=yr.compute([Xs],n=>{let e=n.facet(Xs);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:Ar.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),jg=Z.define();class Yg{constructor(e,t,i,s,r,o){this.view=e,this.source=t,this.field=i,this.locked=s,this.setHover=r,this.hoverTime=o,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;eo.bottom||t.xo.right+e.defaultCharacterWidth)return;let a=e.bidiSpans(e.state.doc.lineAt(s)).find(c=>c.from<=s&&c.to>=s),l=a&&a.dir==fe.RTL?-1:1;r=t.x{if(a&&!(Array.isArray(a)&&!a.length)){let l=Array.isArray(a)?a:[a];s&&this.locked.set(l,s),e.dispatch({effects:this.setHover.of(l)})}};if(r&&"then"in r){let a=this.pending={pos:t};r.then(l=>{this.pending==a&&(this.pending=null,o(l))},l=>ze(e.state,l,"hover tooltip"))}else o(r)}get tooltip(){let e=this.view.plugin($a),t=e?e.manager.tooltips.findIndex(i=>i.create==Ar.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:s,tooltip:r}=this;if(s.length&&!this.locked.has(s)&&r&&!Ng(r.dom,e)||this.pending){let{pos:o}=s[0]||this.pending,a=(i=(t=s[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==a?this.view.posAtCoords(this.lastMove)!=o:!Hg(this.view,o,a,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t);let{active:s}=this;s.length&&!this.locked.has(s)&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const rs=4;function Ng(n,e){let{left:t,right:i,top:s,bottom:r}=n.getBoundingClientRect(),o;if(o=n.querySelector(".cm-tooltip-arrow")){let a=o.getBoundingClientRect();s=Math.min(a.top,s),r=Math.max(a.bottom,r)}return e.clientX>=t-rs&&e.clientX<=i+rs&&e.clientY>=s-rs&&e.clientY<=r+rs}function Hg(n,e,t,i,s,r){let o=n.scrollDOM.getBoundingClientRect(),a=n.documentTop+n.documentPadding.top+n.contentHeight;if(o.left>i||o.rights||Math.min(o.bottom,a)=e&&l<=t}function Lu(n,e={}){let t=Y.define(),i=new WeakMap,s=Te.define({create(){return[]},update(o,a){let l=i.get(o);if(o.length&&(e.hideOnChange&&(a.docChanged||a.selection)?o=[]:l&&l(a)?o=[]:e.hideOn&&(o=o.filter(c=>!e.hideOn(a,c)))),a.docChanged&&o.length){let c=[];for(let h of o){let u=a.changes.mapPos(h.pos,-1,De.TrackDel);if(u!=null){let f=Object.assign(Object.create(null),h);f.pos=u,f.end!=null&&(f.end=a.changes.mapPos(f.end)),c.push(f)}}o=c}for(let c of a.effects)c.is(t)&&(o=c.value,l=void 0),(c.is(Gg)&&!c.value||c.value==s)&&(o=[]);return o.length&&l&&i.set(o,l),o},provide:o=>Xs.from(o)});const r=xe.define(o=>new Yg(o,n,s,i,t,e.hoverTime||300));return{active:s,extension:[s,r,jg.of(r),Vg]}}function Xu(n,e){let t=n.plugin($a);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const Gg=Y.define(),ac=Z.define({combine(n){let e,t;for(let i of n)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function Bu(n,e){let t=n.plugin(Iu),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Iu=xe.fromClass(class{constructor(n){this.input=n.state.facet(Vi),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(n));let e=n.state.facet(ac);this.top=new os(n,!0,e.topContainer),this.bottom=new os(n,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(n){let e=n.state.facet(ac);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new os(n.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new os(n.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=n.state.facet(Vi);if(t!=this.input){let i=t.filter(l=>l),s=[],r=[],o=[],a=[];for(let l of i){let c=this.specs.indexOf(l),h;c<0?(h=l(n.view),a.push(h)):(h=this.panels[c],h.update&&h.update(n)),s.push(h),(h.top?r:o).push(h)}this.specs=i,this.panels=s,this.top.sync(r),this.bottom.sync(o);for(let l of a)l.dom.classList.add("cm-panel"),l.mount&&l.mount()}else for(let i of this.panels)i.update&&i.update(n)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:n=>K.scrollMargins.of(e=>{let t=e.plugin(n);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class os{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=lc(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=lc(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function lc(n){let e=n.nextSibling;return n.remove(),e}const Vi=Z.define({enables:Iu});function _g(n,e){let t,i=new Promise(o=>t=o),s=o=>Jg(o,e,t);n.state.field(qr,!1)?n.dispatch({effects:Wu.of(s)}):n.dispatch({effects:Y.appendConfig.of(qr.init(()=>[s]))});let r=qu.of(s);return{close:r,result:i.then(o=>((n.win.queueMicrotask||(l=>n.win.setTimeout(l,10)))(()=>{n.state.field(qr).indexOf(s)>-1&&n.dispatch({effects:r})}),o))}}const qr=Te.define({create(){return[]},update(n,e){for(let t of e.effects)t.is(Wu)?n=[t.value].concat(n):t.is(qu)&&(n=n.filter(i=>i!=t.value));return n},provide:n=>Vi.computeN([n],e=>e.field(n))}),Wu=Y.define(),qu=Y.define();function Jg(n,e,t){let i=e.content?e.content(n,()=>o(null)):null;if(!i){if(i=he("form"),e.input){let a=he("input",e.input);/^(text|password|number|email|tel|url)$/.test(a.type)&&a.classList.add("cm-textfield"),a.name||(a.name="input"),i.appendChild(he("label",(e.label||"")+": ",a))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(he("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let s=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let a=0;a{c.keyCode==27?(c.preventDefault(),o(null)):c.keyCode==13&&(c.preventDefault(),o(l))}),l.addEventListener("submit",c=>{c.preventDefault(),o(l)})}let r=he("div",i,he("button",{onclick:()=>o(null),"aria-label":n.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(a){r.contains(r.ownerDocument.activeElement)&&n.focus(),t(a)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let a;typeof e.focus=="string"?a=i.querySelector(e.focus):a=i.querySelector("input")||i.querySelector("button"),a&&"select"in a?a.select():a&&"focus"in a&&a.focus()}}}}class Mt extends ei{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}Mt.prototype.elementClass="";Mt.prototype.toDOM=void 0;Mt.prototype.mapMode=De.TrackBefore;Mt.prototype.startSide=Mt.prototype.endSide=-1;Mt.prototype.point=!0;const ws=Z.define(),eO=Z.define(),tO={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>H.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},An=Z.define();function zu(n){return[Vu(),An.of({...tO,...n})]}const cc=Z.define({combine:n=>n.some(e=>e)});function Vu(n){return[iO]}const iO=xe.fromClass(class{constructor(n){this.view=n,this.domAfter=null,this.prevViewport=n.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=n.state.facet(An).map(e=>new uc(n,e)),this.fixed=!n.state.facet(cc);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),n.scrollDOM.insertBefore(this.dom,n.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(n){if(this.updateGutters(n)){let e=this.prevViewport,t=n.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(n.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(cc)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=n.view.viewport}syncGutters(n){let e=this.dom.nextSibling;n&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=H.iter(this.view.state.facet(ws),this.view.viewport.from),i=[],s=this.gutters.map(r=>new nO(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let a of r.type)if(a.type==Le.Text&&o){Ho(t,i,a.from);for(let l of s)l.line(this.view,a,i);o=!1}else if(a.widget)for(let l of s)l.widget(this.view,a)}else if(r.type==Le.Text){Ho(t,i,r.from);for(let o of s)o.line(this.view,r,i)}else if(r.widget)for(let o of s)o.widget(this.view,r);for(let r of s)r.finish();n&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(n){let e=n.startState.facet(An),t=n.state.facet(An),i=n.docChanged||n.heightChanged||n.viewportChanged||!H.eq(n.startState.facet(ws),n.state.facet(ws),n.view.viewport.from,n.view.viewport.to);if(e==t)for(let s of this.gutters)s.update(n)&&(i=!0);else{i=!0;let s=[];for(let r of t){let o=e.indexOf(r);o<0?s.push(new uc(this.view,r)):(this.gutters[o].update(n),s.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),s.indexOf(r)<0&&r.destroy();for(let r of s)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=s}return i}destroy(){for(let n of this.gutters)n.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:n=>K.scrollMargins.of(e=>{let t=e.plugin(n);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,s=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==fe.LTR?{left:i,right:s}:{right:i,left:s}})});function hc(n){return Array.isArray(n)?n:[n]}function Ho(n,e,t){for(;n.value&&n.from<=t;)n.from==t&&e.push(n.value),n.next()}class nO{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=H.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:s}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==s.elements.length){let a=new ju(e,o,r,i);s.elements.push(a),s.dom.appendChild(a.dom)}else s.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let s=[];Ho(this.cursor,s,t.from),i.length&&(s=s.concat(i));let r=this.gutter.config.lineMarker(e,t,s);r&&s.unshift(r);let o=this.gutter;s.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,s)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),s=i?[i]:null;for(let r of e.state.facet(eO)){let o=r(e,t.widget,t);o&&(s||(s=[])).push(o)}s&&this.addElement(e,t,s)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class uc{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,s=>{let r=s.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let l=r.getBoundingClientRect();o=(l.top+l.bottom)/2}else o=s.clientY;let a=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,a,s)&&s.preventDefault()});this.markers=hc(t.markers(e)),t.initialSpacer&&(this.spacer=new ju(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=hc(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let s=this.config.updateSpacer(this.spacer.markers[0],e);s!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[s])}let i=e.view.viewport;return!H.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class ju{constructor(e,t,i,s){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,s)}update(e,t,i,s){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),sO(this.markers,s)||this.setMarkers(e,s)}setMarkers(e,t){let i="cm-gutterElement",s=this.dom.firstChild;for(let r=0,o=0;;){let a=o,l=rr(a,l,c)||o(a,l,c):o}return i}})}});class zr extends Mt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function Vr(n,e){return n.state.facet(Ri).formatNumber(e,n.state)}const aO=An.compute([Ri],n=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(rO)},lineMarker(e,t,i){return i.some(s=>s.toDOM)?null:new zr(Vr(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let s of e.state.facet(oO)){let r=s(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(Ri)!=e.state.facet(Ri),initialSpacer(e){return new zr(Vr(e,fc(e.state.doc.lines)))},updateSpacer(e,t){let i=Vr(t.view,fc(t.view.state.doc.lines));return i==e.number?e:new zr(i)},domEventHandlers:n.facet(Ri).domEventHandlers,side:"before"}));function lO(n={}){return[Ri.of(n),Vu(),aO]}function fc(n){let e=9;for(;e{let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.head).from;s>t&&(t=s,e.push(cO.range(s)))}return H.of(e)});function uO(){return hO}const Yu=1024;let fO=0;class jr{constructor(e,t){this.from=e,this.to=t}}class _{constructor(e={}){this.id=fO++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=et.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}_.closedBy=new _({deserialize:n=>n.split(" ")});_.openedBy=new _({deserialize:n=>n.split(" ")});_.group=new _({deserialize:n=>n.split(" ")});_.isolate=new _({deserialize:n=>{if(n&&n!="rtl"&&n!="ltr"&&n!="auto")throw new RangeError("Invalid value for isolate: "+n);return n||"auto"}});_.contextHash=new _({perNode:!0});_.lookAhead=new _({perNode:!0});_.mounted=new _({perNode:!0});class bn{constructor(e,t,i,s=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=s}static get(e){return e&&e.props&&e.props[_.mounted.id]}}const dO=Object.create(null);class et{constructor(e,t,i,s=0){this.name=e,this.props=t,this.id=i,this.flags=s}static define(e){let t=e.props&&e.props.length?Object.create(null):dO,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),s=new et(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(s)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return s}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(_.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let s of i.split(" "))t[s]=e[i];return i=>{for(let s=i.prop(_.group),r=-1;r<(s?s.length:0);r++){let o=t[r<0?i.name:s[r]];if(o)return o}}}}et.none=new et("",Object.create(null),0,8);class Ka{constructor(e){this.types=e;for(let t=0;t0;for(let l=this.cursor(o|be.IncludeAnonymous);;){let c=!1;if(l.from<=r&&l.to>=s&&(!a&&l.type.isAnonymous||t(l)!==!1)){if(l.firstChild())continue;c=!0}for(;c&&i&&(a||!l.type.isAnonymous)&&i(l),!l.nextSibling();){if(!l.parent())return;c=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Ea(et.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,s)=>new ke(this.type,t,i,s,this.propValues),e.makeTree||((t,i,s)=>new ke(et.none,t,i,s)))}static build(e){return OO(e)}}ke.empty=new ke(et.none,[],[],0);class Za{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Za(this.buffer,this.index)}}class si{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return et.none}toString(){let e=[];for(let t=0;t0));l=o[l+3]);return a}slice(e,t,i){let s=this.buffer,r=new Uint16Array(t-e),o=0;for(let a=e,l=0;a=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function Pn(n,e,t,i){for(var s;n.from==n.to||(t<1?n.from>=e:n.from>e)||(t>-1?n.to<=e:n.to0?a.length:-1;e!=c;e+=t){let h=a[e],u=l[e]+o.from,f;if(!(!(r&be.EnterBracketed&&h instanceof ke&&(f=bn.get(h))&&!f.overlay&&f.bracketed&&i>=u&&i<=u+h.length)&&!Nu(s,i,u,u+h.length))){if(h instanceof si){if(r&be.ExcludeBuffers)continue;let d=h.findChild(0,h.buffer.length,t,i-u,s);if(d>-1)return new Tt(new pO(o,h,e,u),null,d)}else if(r&be.IncludeAnonymous||!h.type.isAnonymous||Ma(h)){let d;if(!(r&be.IgnoreMounts)&&(d=bn.get(h))&&!d.overlay)return new Je(d.tree,u,e,o);let p=new Je(h,u,e,o);return r&be.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?h.children.length-1:0,t,i,s,r)}}}if(r&be.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let s;if(!(i&be.IgnoreOverlays)&&(s=bn.get(this._tree))&&s.overlay){let r=e-this.from,o=i&be.EnterBracketed&&s.bracketed;for(let{from:a,to:l}of s.overlay)if((t>0||o?a<=r:a=r:l>r))return new Je(s.tree,s.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function pc(n,e,t,i){let s=n.cursor(),r=[];if(!s.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=s.type.is(t),!s.nextSibling())return r}for(;;){if(i!=null&&s.type.is(i))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return i==null?r:[]}}function Go(n,e,t=e.length-1){for(let i=n;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class pO{constructor(e,t,i,s){this.parent=e,this.buffer=t,this.index=i,this.start=s}}class Tt extends Hu{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new Tt(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&be.ExcludeBuffers)return null;let{buffer:s}=this.context,r=s.findChild(this.index+4,s.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new Tt(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Tt(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new Tt(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,s=this.index+4,r=i.buffer[this.index+3];if(r>s){let o=i.buffer[this.index+1];e.push(i.slice(s,r,o)),t.push(0)}return new ke(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function Gu(n){if(!n.length)return null;let e=0,t=n[0];for(let r=1;rt.from||o.to=e){let a=new Je(o.tree,o.overlay[0].from+r.from,-1,r);(s||(s=[i])).push(Pn(a,e,t,!1))}}return s?Gu(s):i}class _o{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~be.EnterBracketed,e instanceof Je)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:s}=this.buffer;return this.type=t||s.set.types[s.buffer[e]],this.from=i+s.buffer[e+1],this.to=i+s.buffer[e+2],!0}yield(e){return e?e instanceof Je?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:s}=this.buffer,r=s.findChild(this.index+4,s.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&be.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&be.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&be.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let s=i<0?0:this.stack[i]+4;if(this.index!=s)return this.yieldBuf(t.findChild(s,this.index,-1,0,4))}else{let s=t.buffer[this.index+3];if(s<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(s)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:s}=this;if(s){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let a=i._tree.children[r];if(this.mode&be.IncludeAnonymous||a instanceof si||!a.type.isAnonymous||Ma(a))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==s){if(s==this.index)return o;t=o,i=r+1;break e}s=this.stack[--r]}for(let s=i;s=0;r--){if(r<0)return Go(this._tree,e,s);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[s]&&e[s]!=o.name)return!1;s--}}return!0}}function Ma(n){return n.children.some(e=>e instanceof si||!e.type.isAnonymous||Ma(e))}function OO(n){var e;let{buffer:t,nodeSet:i,maxBufferLength:s=Yu,reused:r=[],minRepeatType:o=i.types.length}=n,a=Array.isArray(t)?new Za(t,t.length):t,l=i.types,c=0,h=0;function u(Q,P,w,L,D,W){let{id:F,start:U,end:T,size:v}=a,M=h,k=c;if(v<0)if(a.next(),v==-1){let q=r[F];w.push(q),L.push(U-Q);return}else if(v==-3){c=F;return}else if(v==-4){h=F;return}else throw new RangeError(`Unrecognized record size: ${v}`);let z=l[F],re,N,ee=U-Q;if(T-U<=s&&(N=g(a.pos-P,D))){let q=new Uint16Array(N.size-N.skip),G=a.pos-N.size,ce=q.length;for(;a.pos>G;)ce=y(N.start,q,ce);re=new si(q,T-N.start,i),ee=N.start-Q}else{let q=a.pos-v;a.next();let G=[],ce=[],V=F>=o?F:-1,te=0,oe=T;for(;a.pos>q;)V>=0&&a.id==V&&a.size>=0?(a.end<=oe-s&&(p(G,ce,U,te,a.end,oe,V,M,k),te=G.length,oe=a.end),a.next()):W>2500?f(U,q,G,ce):u(U,q,G,ce,V,W+1);if(V>=0&&te>0&&te-1&&te>0){let Me=d(z,k);re=Ea(z,G,ce,0,G.length,0,T-U,Me,Me)}else re=m(z,G,ce,T-U,M-T,k)}w.push(re),L.push(ee)}function f(Q,P,w,L){let D=[],W=0,F=-1;for(;a.pos>P;){let{id:U,start:T,end:v,size:M}=a;if(M>4)a.next();else{if(F>-1&&T=0;v-=3)U[M++]=D[v],U[M++]=D[v+1]-T,U[M++]=D[v+2]-T,U[M++]=M;w.push(new si(U,D[2]-T,i)),L.push(T-Q)}}function d(Q,P){return(w,L,D)=>{let W=0,F=w.length-1,U,T;if(F>=0&&(U=w[F])instanceof ke){if(!F&&U.type==Q&&U.length==D)return U;(T=U.prop(_.lookAhead))&&(W=L[F]+U.length+T)}return m(Q,w,L,D,W,P)}}function p(Q,P,w,L,D,W,F,U,T){let v=[],M=[];for(;Q.length>L;)v.push(Q.pop()),M.push(P.pop()+w-D);Q.push(m(i.types[F],v,M,W-D,U-W,T)),P.push(D-w)}function m(Q,P,w,L,D,W,F){if(W){let U=[_.contextHash,W];F=F?[U].concat(F):[U]}if(D>25){let U=[_.lookAhead,D];F=F?[U].concat(F):[U]}return new ke(Q,P,w,L,F)}function g(Q,P){let w=a.fork(),L=0,D=0,W=0,F=w.end-s,U={size:0,start:0,skip:0};e:for(let T=w.pos-Q;w.pos>T;){let v=w.size;if(w.id==P&&v>=0){U.size=L,U.start=D,U.skip=W,W+=4,L+=4,w.next();continue}let M=w.pos-v;if(v<0||M=o?4:0,z=w.start;for(w.next();w.pos>M;){if(w.size<0)if(w.size==-3||w.size==-4)k+=4;else break e;else w.id>=o&&(k+=4);w.next()}D=z,L+=v,W+=k}return(P<0||L==Q)&&(U.size=L,U.start=D,U.skip=W),U.size>4?U:void 0}function y(Q,P,w){let{id:L,start:D,end:W,size:F}=a;if(a.next(),F>=0&&L4){let T=a.pos-(F-4);for(;a.pos>T;)w=y(Q,P,w)}P[--w]=U,P[--w]=W-Q,P[--w]=D-Q,P[--w]=L}else F==-3?c=L:F==-4&&(h=L);return w}let x=[],b=[];for(;a.pos>0;)u(n.start||0,n.bufferStart||0,x,b,-1,0);let C=(e=n.length)!==null&&e!==void 0?e:x.length?b[0]+x[0].length:0;return new ke(l[n.topID],x.reverse(),b.reverse(),C)}const mc=new WeakMap;function ks(n,e){if(!n.isAnonymous||e instanceof si||e.type!=n)return 1;let t=mc.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=n||!(i instanceof ke)){t=1;break}t+=ks(n,i)}mc.set(e,t)}return t}function Ea(n,e,t,i,s,r,o,a,l){let c=0;for(let p=i;p=h)break;P+=w}if(b==C+1){if(P>h){let w=p[C];d(w.children,w.positions,0,w.children.length,m[C]+x);continue}u.push(p[C])}else{let w=m[b-1]+p[b-1].length-Q;u.push(Ea(n,p,m,C,b,Q,w,null,l))}f.push(Q+x-r)}}return d(e,t,i,s,0),(a||l)(u,f,o)}class yO{constructor(){this.map=new WeakMap}setBuffer(e,t,i){let s=this.map.get(e);s||this.map.set(e,s=new Map),s.set(t,i)}getBuffer(e,t){let i=this.map.get(e);return i&&i.get(t)}set(e,t){e instanceof Tt?this.setBuffer(e.context.buffer,e.index,t):e instanceof Je&&this.map.set(e.tree,t)}get(e){return e instanceof Tt?this.getBuffer(e.context.buffer,e.index):e instanceof Je?this.map.get(e.tree):void 0}cursorSet(e,t){e.buffer?this.setBuffer(e.buffer.buffer,e.index,t):this.map.set(e.tree,t)}cursorGet(e){return e.buffer?this.getBuffer(e.buffer.buffer,e.index):this.map.get(e.tree)}}class Oi{constructor(e,t,i,s,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=s,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let s=[new Oi(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&s.push(r);return s}static applyChanges(e,t,i=128){if(!t.length)return e;let s=[],r=1,o=e.length?e[0]:null;for(let a=0,l=0,c=0;;a++){let h=a=i)for(;o&&o.from=f.from||u<=f.to||c){let d=Math.max(f.from,l)-c,p=Math.min(f.to,u)-c;f=d>=p?null:new Oi(d,p,f.tree,f.offset+c,a>0,!!h)}if(f&&s.push(f),o.to>u)break;o=rnew jr(s.from,s.to)):[new jr(0,0)]:[new jr(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let s=this.startParse(e,t,i);for(;;){let r=s.advance();if(r)return r}}}class AO{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new _({perNode:!0});let bO=0;class lt{constructor(e,t,i,s){this.name=e,this.set=t,this.base=i,this.modified=s,this.id=bO++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof lt&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let s=new lt(i,[],null,[]);if(s.set.push(s),t)for(let r of t.set)s.set.push(r);return s}static defineModifier(e){let t=new Bs(e);return i=>i.modified.indexOf(t)>-1?i:Bs.get(i.base||i,i.modified.concat(t).sort((s,r)=>s.id-r.id))}}let SO=0;class Bs{constructor(e){this.name=e,this.instances=[],this.id=SO++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(a=>a.base==e&&xO(t,a.modified));if(i)return i;let s=[],r=new lt(e.name,s,e,t);for(let a of t)a.instances.push(r);let o=vO(t);for(let a of e.set)if(!a.modified.length)for(let l of o)s.push(Bs.get(a,l));return r}}function xO(n,e){return n.length==e.length&&n.every((t,i)=>t==e[i])}function vO(n){let e=[[]];for(let t=0;ti.length-t.length)}function Ju(n){let e=Object.create(null);for(let t in n){let i=n[t];Array.isArray(i)||(i=[i]);for(let s of t.split(" "))if(s){let r=[],o=2,a=s;for(let u=0;;){if(a=="..."&&u>0&&u+3==s.length){o=1;break}let f=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(a);if(!f)throw new RangeError("Invalid path: "+s);if(r.push(f[0]=="*"?"":f[0][0]=='"'?JSON.parse(f[0]):f[0]),u+=f[0].length,u==s.length)break;let d=s[u++];if(u==s.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+s);a=s.slice(u)}let l=r.length-1,c=r[l];if(!c)throw new RangeError("Invalid path: "+s);let h=new Cn(i,o,l>0?r.slice(0,l):null);e[c]=h.sort(e[c])}}return ef.add(e)}const ef=new _({combine(n,e){let t,i,s;for(;n||e;){if(!n||e&&n.depth>=e.depth?(s=e,e=e.next):(s=n,n=n.next),t&&t.mode==s.mode&&!s.context&&!t.context)continue;let r=new Cn(s.tags,s.mode,s.context);t?t.next=r:i=r,t=r}return i}});class Cn{constructor(e,t,i,s){this.tags=e,this.mode=t,this.context=i,this.next=s}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=s;for(let a of r)for(let l of a.set){let c=t[l.id];if(c){o=o?o+" "+c:c;break}}return o},scope:i}}function wO(n,e){let t=null;for(let i of n){let s=i.style(e);s&&(t=t?t+" "+s:s)}return t}function kO(n,e,t,i=0,s=n.length){let r=new QO(i,Array.isArray(e)?e:[e],t);r.highlightRange(n.cursor(),i,s,"",r.highlighters),r.flush(s)}class QO{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,s,r){let{type:o,from:a,to:l}=e;if(a>=i||l<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let c=s,h=PO(e)||Cn.empty,u=wO(r,h.tags);if(u&&(c&&(c+=" "),c+=u,h.mode==1&&(s+=(s?" ":"")+u)),this.startSpan(Math.max(t,a),c),h.opaque)return;let f=e.tree&&e.tree.prop(_.mounted);if(f&&f.overlay){let d=e.node.enter(f.overlay[0].from+a,1),p=this.highlighters.filter(g=>!g.scope||g.scope(f.tree.type)),m=e.firstChild();for(let g=0,y=a;;g++){let x=g=b||!e.nextSibling())););if(!x||b>i)break;y=x.to+a,y>t&&(this.highlightRange(d.cursor(),Math.max(t,x.from+a),Math.min(i,y),"",p),this.startSpan(Math.min(i,y),c))}m&&e.parent()}else if(e.firstChild()){f&&(s="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,s,r),this.startSpan(Math.min(i,e.to),c)}while(e.nextSibling());e.parent()}}}function PO(n){let e=n.type.prop(ef);for(;e&&e.context&&!n.matchContext(e.context);)e=e.next;return e||null}const R=lt.define,ls=R(),jt=R(),gc=R(jt),Oc=R(jt),Yt=R(),cs=R(Yt),Yr=R(Yt),wt=R(),ci=R(wt),xt=R(),vt=R(),Jo=R(),on=R(Jo),hs=R(),O={comment:ls,lineComment:R(ls),blockComment:R(ls),docComment:R(ls),name:jt,variableName:R(jt),typeName:gc,tagName:R(gc),propertyName:Oc,attributeName:R(Oc),className:R(jt),labelName:R(jt),namespace:R(jt),macroName:R(jt),literal:Yt,string:cs,docString:R(cs),character:R(cs),attributeValue:R(cs),number:Yr,integer:R(Yr),float:R(Yr),bool:R(Yt),regexp:R(Yt),escape:R(Yt),color:R(Yt),url:R(Yt),keyword:xt,self:R(xt),null:R(xt),atom:R(xt),unit:R(xt),modifier:R(xt),operatorKeyword:R(xt),controlKeyword:R(xt),definitionKeyword:R(xt),moduleKeyword:R(xt),operator:vt,derefOperator:R(vt),arithmeticOperator:R(vt),logicOperator:R(vt),bitwiseOperator:R(vt),compareOperator:R(vt),updateOperator:R(vt),definitionOperator:R(vt),typeOperator:R(vt),controlOperator:R(vt),punctuation:Jo,separator:R(Jo),bracket:on,angleBracket:R(on),squareBracket:R(on),paren:R(on),brace:R(on),content:wt,heading:ci,heading1:R(ci),heading2:R(ci),heading3:R(ci),heading4:R(ci),heading5:R(ci),heading6:R(ci),contentSeparator:R(wt),list:R(wt),quote:R(wt),emphasis:R(wt),strong:R(wt),link:R(wt),monospace:R(wt),strikethrough:R(wt),inserted:R(),deleted:R(),changed:R(),invalid:R(),meta:hs,documentMeta:R(hs),annotation:R(hs),processingInstruction:R(hs),definition:lt.defineModifier("definition"),constant:lt.defineModifier("constant"),function:lt.defineModifier("function"),standard:lt.defineModifier("standard"),local:lt.defineModifier("local"),special:lt.defineModifier("special")};for(let n in O){let e=O[n];e instanceof lt&&(e.name=n)}tf([{tag:O.link,class:"tok-link"},{tag:O.heading,class:"tok-heading"},{tag:O.emphasis,class:"tok-emphasis"},{tag:O.strong,class:"tok-strong"},{tag:O.keyword,class:"tok-keyword"},{tag:O.atom,class:"tok-atom"},{tag:O.bool,class:"tok-bool"},{tag:O.url,class:"tok-url"},{tag:O.labelName,class:"tok-labelName"},{tag:O.inserted,class:"tok-inserted"},{tag:O.deleted,class:"tok-deleted"},{tag:O.literal,class:"tok-literal"},{tag:O.string,class:"tok-string"},{tag:O.number,class:"tok-number"},{tag:[O.regexp,O.escape,O.special(O.string)],class:"tok-string2"},{tag:O.variableName,class:"tok-variableName"},{tag:O.local(O.variableName),class:"tok-variableName tok-local"},{tag:O.definition(O.variableName),class:"tok-variableName tok-definition"},{tag:O.special(O.variableName),class:"tok-variableName2"},{tag:O.definition(O.propertyName),class:"tok-propertyName tok-definition"},{tag:O.typeName,class:"tok-typeName"},{tag:O.namespace,class:"tok-namespace"},{tag:O.className,class:"tok-className"},{tag:O.macroName,class:"tok-macroName"},{tag:O.propertyName,class:"tok-propertyName"},{tag:O.operator,class:"tok-operator"},{tag:O.comment,class:"tok-comment"},{tag:O.meta,class:"tok-meta"},{tag:O.invalid,class:"tok-invalid"},{tag:O.punctuation,class:"tok-punctuation"}]);var Nr;const $i=new _;function nf(n){return Z.define({combine:n?e=>e.concat(n):void 0})}const Ua=new _;class mt{constructor(e,t,i=[],s=""){this.data=e,this.name=s,J.prototype.hasOwnProperty("tree")||Object.defineProperty(J.prototype,"tree",{get(){return Ce(this)}}),this.parser=t,this.extension=[ri.of(this),J.languageData.of((r,o,a)=>{let l=yc(r,o,a),c=l.type.prop($i);if(!c)return[];let h=r.facet(c),u=l.type.prop(Ua);if(u){let f=l.resolve(o-l.from,a);for(let d of u)if(d.test(f,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(h)}}return h})].concat(i)}isActiveAt(e,t,i=-1){return yc(e,t,i).type.prop($i)==this.data}findRegions(e){let t=e.facet(ri);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],s=(r,o)=>{if(r.prop($i)==this.data){i.push({from:o,to:o+r.length});return}let a=r.prop(_.mounted);if(a){if(a.tree.prop($i)==this.data){if(a.overlay)for(let l of a.overlay)i.push({from:l.from+o,to:l.to+o});else i.push({from:o,to:o+r.length});return}else if(a.overlay){let l=i.length;if(s(a.tree,a.overlay[0].from+o),i.length>l)return}}for(let l=0;li.isTop?t:void 0)]}),e.name)}configure(e,t){return new Is(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function Ce(n){let e=n.field(mt.state,!1);return e?e.tree:ke.empty}class CO{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let an=null;class Ws{constructor(e,t,i=[],s,r,o,a,l){this.parser=e,this.state=t,this.fragments=i,this.tree=s,this.treeLen=r,this.viewport=o,this.skipped=a,this.scheduleOn=l,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new Ws(e,t,[],ke.empty,0,i,[],null)}startParse(){return this.parser.startParse(new CO(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=ke.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let s=Date.now()+e;e=()=>Date.now()>s}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Oi.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=an;an=this;try{return e()}finally{an=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Ac(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:s,treeLen:r,viewport:o,skipped:a}=this;if(this.takeTree(),!e.empty){let l=[];if(e.iterChangedRanges((c,h,u,f)=>l.push({fromA:c,toA:h,fromB:u,toB:f})),i=Oi.applyChanges(i,l),s=ke.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){a=[];for(let c of this.skipped){let h=e.mapPos(c.from,1),u=e.mapPos(c.to,-1);he.from&&(this.fragments=Ac(this.fragments,s,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends _u{createParse(t,i,s){let r=s[0].from,o=s[s.length-1].to;return{parsedPos:r,advance(){let l=an;if(l){for(let c of s)l.tempSkipped.push(c);e&&(l.scheduleOn=l.scheduleOn?Promise.all([l.scheduleOn,e]):e)}return this.parsedPos=o,new ke(et.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return an}}function Ac(n,e,t){return Oi.applyChanges(n,[{fromA:e,toA:t,fromB:e,toB:t}])}class ji{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new ji(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=Ws.create(e.facet(ri).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new ji(i)}}mt.state=Te.define({create:ji.init,update(n,e){for(let t of e.effects)if(t.is(mt.setState))return t.value;return e.startState.facet(ri)!=e.state.facet(ri)?ji.init(e.state):n.apply(e)}});let sf=n=>{let e=setTimeout(()=>n(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(sf=n=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(n,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const Hr=typeof navigator<"u"&&(!((Nr=navigator.scheduling)===null||Nr===void 0)&&Nr.isInputPending)?()=>navigator.scheduling.isInputPending():null,TO=xe.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(mt.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(mt.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=sf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEnds+1e3,l=r.context.work(()=>Hr&&Hr()||Date.now()>o,s+(a?0:1e5));this.chunkBudget-=Date.now()-t,(l||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:mt.setState.of(new ji(r.context))})),this.chunkBudget>0&&!(l&&!a)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>ze(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),ri=Z.define({combine(n){return n.length?n[0]:null},enables:n=>[mt.state,TO,K.contentAttributes.compute([n],e=>{let t=e.facet(n);return t&&t.name?{"data-language":t.name}:{}})]});class RO{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}const $O=Z.define(),br=Z.define({combine:n=>{if(!n.length)return" ";let e=n[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(n[0]));return e}});function qs(n){let e=n.facet(br);return e.charCodeAt(0)==9?n.tabSize*e.length:e.length}function Tn(n,e){let t="",i=n.tabSize,s=n.facet(br)[0];if(s==" "){for(;e>=i;)t+=" ",e-=i;s=" "}for(let r=0;r=e?KO(n,t,e):null}class Sr{constructor(e,t={}){this.state=e,this.options=t,this.unit=qs(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:s,simulateDoubleBreak:r}=this.options;return s!=null&&s>=i.from&&s<=i.to?r&&s==e?{text:"",from:e}:(t<0?s-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return _i(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:s}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(s);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const rf=new _;function KO(n,e,t){let i=e.resolveStack(t),s=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(s!=i.node){let r=[];for(let o=s;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return of(i,n,t)}function of(n,e,t){for(let i=n;i;i=i.next){let s=MO(i.node);if(s)return s(Da.create(e,t,i))}return 0}function ZO(n){return n.pos==n.options.simulateBreak&&n.options.simulateDoubleBreak}function MO(n){let e=n.type.prop(rf);if(e)return e;let t=n.firstChild,i;if(t&&(i=t.type.prop(_.closedBy))){let s=n.lastChild,r=s&&i.indexOf(s.name)>-1;return o=>af(o,!0,1,void 0,r&&!ZO(o)?s.from:void 0)}return n.parent==null?EO:null}function EO(){return 0}class Da extends Sr{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new Da(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(UO(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return of(this.context.next,this.base,this.pos)}}function UO(n,e){for(let t=e;t;t=t.parent)if(n==t)return!0;return!1}function FO(n){let e=n.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let s=n.options.simulateBreak,r=n.state.doc.lineAt(t.from),o=s==null||s<=r.from?r.to:Math.min(r.to,s);for(let a=t.to;;){let l=e.childAfter(a);if(!l||l==i)return null;if(!l.type.isSkipped){if(l.from>=o)return null;let c=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+c}}a=l.to}}function DO({closing:n,align:e=!0,units:t=1}){return i=>af(i,e,t,n)}function af(n,e,t,i,s){let r=n.textAfter,o=r.match(/^\s*/)[0].length,a=i&&r.slice(o,o+i.length)==i||s==n.pos+o,l=e?FO(n):null;return l?a?n.column(l.from):n.column(l.to):n.baseIndent+(a?0:n.unit*t)}const LO=n=>n.baseIndent;function Gr({except:n,units:e=1}={}){return t=>{let i=n&&n.test(t.textAfter);return t.baseIndent+(i?0:e*t.unit)}}const XO=200;function BO(){return J.transactionFilter.of(n=>{if(!n.docChanged||!n.isUserEvent("input.type")&&!n.isUserEvent("input.complete"))return n;let e=n.startState.languageDataAt("indentOnInput",n.startState.selection.main.head);if(!e.length)return n;let t=n.newDoc,{head:i}=n.newSelection.main,s=t.lineAt(i);if(i>s.from+XO)return n;let r=t.sliceString(s.from,i);if(!e.some(c=>c.test(r)))return n;let{state:o}=n,a=-1,l=[];for(let{head:c}of o.selection.ranges){let h=o.doc.lineAt(c);if(h.from==a)continue;a=h.from;let u=Fa(o,h.from);if(u==null)continue;let f=/^\s*/.exec(h.text)[0],d=Tn(o,u);f!=d&&l.push({from:h.from,to:h.from+f.length,insert:d})}return l.length?[n,{changes:l,sequential:!0}]:n})}const IO=Z.define(),lf=new _;function WO(n){let e=n.firstChild,t=n.lastChild;return e&&e.tot)continue;if(r&&a.from=e&&c.to>t&&(r=c)}}return r}function zO(n){let e=n.lastChild;return e&&e.to==n.to&&e.type.isError}function zs(n,e,t){for(let i of n.facet(IO)){let s=i(n,e,t);if(s)return s}return qO(n,e,t)}function cf(n,e){let t=e.mapPos(n.from,1),i=e.mapPos(n.to,-1);return t>=i?void 0:{from:t,to:i}}const xr=Y.define({map:cf}),Xn=Y.define({map:cf});function hf(n){let e=[];for(let{head:t}of n.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(n.lineBlockAt(t));return e}const xi=Te.define({create(){return I.none},update(n,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((i,s)=>n=bc(n,i,s)),n=n.map(e.changes);let t=[];for(let i of e.effects)i.is(xr)&&!VO(n,i.value.from,i.value.to)?t.push(i.value):i.is(Xn)&&(n=n.update({filter:(s,r)=>i.value.from!=s||i.value.to!=r,filterFrom:i.value.from,filterTo:i.value.to}));if(t.length){let{preparePlaceholder:i}=e.state.facet(df),s=t.map(r=>(i?I.replace({widget:new JO(i(e.state,r))}):Sc).range(r.from,r.to));n=n.update({add:s})}return e.selection&&(n=bc(n,e.selection.main.head)),n},provide:n=>K.decorations.from(n),toJSON(n,e){let t=[];return n.between(0,e.doc.length,(i,s)=>{t.push(i,s)}),t},fromJSON(n){if(!Array.isArray(n)||n.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{se&&(i=!0)}),i?n.update({filterFrom:e,filterTo:t,filter:(s,r)=>s>=t||r<=e}):n}function Vs(n,e,t){var i;let s=null;return(i=n.field(xi,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!s||s.from>r)&&(s={from:r,to:o})}),s}function VO(n,e,t){let i=!1;return n.between(e,e,(s,r)=>{s==e&&r==t&&(i=!0)}),i}function uf(n,e){return n.field(xi,!1)?e:e.concat(Y.appendConfig.of(pf()))}const jO=n=>{for(let e of hf(n)){let t=zs(n.state,e.from,e.to);if(t)return n.dispatch({effects:uf(n.state,[xr.of(t),ff(n,t)])}),!0}return!1},YO=n=>{if(!n.state.field(xi,!1))return!1;let e=[];for(let t of hf(n)){let i=Vs(n.state,t.from,t.to);i&&e.push(Xn.of(i),ff(n,i,!1))}return e.length&&n.dispatch({effects:e}),e.length>0};function ff(n,e,t=!0){let i=n.state.doc.lineAt(e.from).number,s=n.state.doc.lineAt(e.to).number;return K.announce.of(`${n.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${n.state.phrase("to")} ${s}.`)}const NO=n=>{let{state:e}=n,t=[];for(let i=0;i{let e=n.state.field(xi,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,n.state.doc.length,(i,s)=>{t.push(Xn.of({from:i,to:s}))}),n.dispatch({effects:t}),!0},GO=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:jO},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:YO},{key:"Ctrl-Alt-[",run:NO},{key:"Ctrl-Alt-]",run:HO}],_O={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},df=Z.define({combine(n){return yt(n,_O)}});function pf(n){return[xi,i0]}function mf(n,e){let{state:t}=n,i=t.facet(df),s=o=>{let a=n.lineBlockAt(n.posAtDOM(o.target)),l=Vs(n.state,a.from,a.to);l&&n.dispatch({effects:Xn.of(l)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(n,s,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}const Sc=I.replace({widget:new class extends Ut{toDOM(n){return mf(n,null)}}});class JO extends Ut{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return mf(e,this.value)}}const e0={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class _r extends Mt{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function t0(n={}){let e={...e0,...n},t=new _r(e,!0),i=new _r(e,!1),s=xe.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(ri)!=o.state.facet(ri)||o.startState.field(xi,!1)!=o.state.field(xi,!1)||Ce(o.startState)!=Ce(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let a=new It;for(let l of o.viewportLineBlocks){let c=Vs(o.state,l.from,l.to)?i:zs(o.state,l.from,l.to)?t:null;c&&a.add(l.from,l.from,c)}return a.finish()}}),{domEventHandlers:r}=e;return[s,zu({class:"cm-foldGutter",markers(o){var a;return((a=o.plugin(s))===null||a===void 0?void 0:a.markers)||H.empty},initialSpacer(){return new _r(e,!1)},domEventHandlers:{...r,click:(o,a,l)=>{if(r.click&&r.click(o,a,l))return!0;let c=Vs(o.state,a.from,a.to);if(c)return o.dispatch({effects:Xn.of(c)}),!0;let h=zs(o.state,a.from,a.to);return h?(o.dispatch({effects:xr.of(h)}),!0):!1}}}),pf()]}const i0=K.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class Bn{constructor(e,t){this.specs=e;let i;function s(a){let l=ti.newName();return(i||(i=Object.create(null)))["."+l]=a,l}const r=typeof t.all=="string"?t.all:t.all?s(t.all):void 0,o=t.scope;this.scope=o instanceof mt?a=>a.prop($i)==o.data:o?a=>a==o:void 0,this.style=tf(e.map(a=>({tag:a.tag,class:a.class||s(Object.assign({},a,{tag:null}))})),{all:r}).style,this.module=i?new ti(i):null,this.themeType=t.themeType}static define(e,t){return new Bn(e,t||{})}}const ea=Z.define(),n0=Z.define({combine(n){return n.length?[n[0]]:null}});function Jr(n){let e=n.facet(ea);return e.length?e:n.facet(n0)}function s0(n,e){let t=[o0],i;return n instanceof Bn&&(n.module&&t.push(K.styleModule.of(n.module)),i=n.themeType),i?t.push(ea.computeN([K.darkTheme],s=>s.facet(K.darkTheme)==(i=="dark")?[n]:[])):t.push(ea.of(n)),t}class r0{constructor(e){this.markCache=Object.create(null),this.tree=Ce(e.state),this.decorations=this.buildDeco(e,Jr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=Ce(e.state),i=Jr(e.state),s=i!=Jr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||s)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return I.none;let i=new It;for(let{from:s,to:r}of e.visibleRanges)kO(this.tree,t,(o,a,l)=>{i.add(o,a,this.markCache[l]||(this.markCache[l]=I.mark({class:l})))},s,r);return i.finish()}}const o0=oi.high(xe.fromClass(r0,{decorations:n=>n.decorations})),a0=Bn.define([{tag:O.meta,color:"#404740"},{tag:O.link,textDecoration:"underline"},{tag:O.heading,textDecoration:"underline",fontWeight:"bold"},{tag:O.emphasis,fontStyle:"italic"},{tag:O.strong,fontWeight:"bold"},{tag:O.strikethrough,textDecoration:"line-through"},{tag:O.keyword,color:"#708"},{tag:[O.atom,O.bool,O.url,O.contentSeparator,O.labelName],color:"#219"},{tag:[O.literal,O.inserted],color:"#164"},{tag:[O.string,O.deleted],color:"#a11"},{tag:[O.regexp,O.escape,O.special(O.string)],color:"#e40"},{tag:O.definition(O.variableName),color:"#00f"},{tag:O.local(O.variableName),color:"#30a"},{tag:[O.typeName,O.namespace],color:"#085"},{tag:O.className,color:"#167"},{tag:[O.special(O.variableName),O.macroName],color:"#256"},{tag:O.definition(O.propertyName),color:"#00c"},{tag:O.comment,color:"#940"},{tag:O.invalid,color:"#f00"}]),l0=K.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),gf=1e4,Of="()[]{}",yf=Z.define({combine(n){return yt(n,{afterCursor:!0,brackets:Of,maxScanDistance:gf,renderMatch:u0})}}),c0=I.mark({class:"cm-matchingBracket"}),h0=I.mark({class:"cm-nonmatchingBracket"});function u0(n){let e=[],t=n.matched?c0:h0;return e.push(t.range(n.start.from,n.start.to)),n.end&&e.push(t.range(n.end.from,n.end.to)),e}function xc(n){let e=[],t=n.facet(yf);for(let i of n.selection.ranges){if(!i.empty)continue;let s=Rt(n,i.head,-1,t)||i.head>0&&Rt(n,i.head-1,1,t)||t.afterCursor&&(Rt(n,i.head,1,t)||i.headn.decorations}),d0=[f0,l0];function p0(n={}){return[yf.of(n),d0]}const m0=new _;function ta(n,e,t){let i=n.prop(e<0?_.openedBy:_.closedBy);if(i)return i;if(n.name.length==1){let s=t.indexOf(n.name);if(s>-1&&s%2==(e<0?1:0))return[t[s+e]]}return null}function ia(n){let e=n.type.prop(m0);return e?e(n.node):n}function Rt(n,e,t,i={}){let s=i.maxScanDistance||gf,r=i.brackets||Of,o=Ce(n),a=o.resolveInner(e,t);for(let l=a;l;l=l.parent){let c=ta(l.type,t,r);if(c&&l.from0?e>=h.from&&eh.from&&e<=h.to))return g0(n,e,t,l,h,c,r)}}return O0(n,e,t,o,a.type,s,r)}function g0(n,e,t,i,s,r,o){let a=i.parent,l={from:s.from,to:s.to},c=0,h=a?.cursor();if(h&&(t<0?h.childBefore(i.from):h.childAfter(i.to)))do if(t<0?h.to<=i.from:h.from>=i.to){if(c==0&&r.indexOf(h.type.name)>-1&&h.from0)return null;let c={from:t<0?e-1:e,to:t>0?e+1:e},h=n.doc.iterRange(e,t>0?n.doc.length:0),u=0;for(let f=0;!h.next().done&&f<=r;){let d=h.value;t<0&&(f+=d.length);let p=e+f*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let y=o.indexOf(d[m]);if(!(y<0||i.resolveInner(p+m,1).type!=s))if(y%2==0==t>0)u++;else{if(u==1)return{start:c,end:{from:p+m,to:p+m+1},matched:y>>1==l>>1};u--}}t>0&&(f+=d.length)}return h.done?{start:c,matched:!1}:null}const y0=Object.create(null),vc=[et.none],wc=[],kc=Object.create(null),A0=Object.create(null);for(let[n,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])A0[n]=b0(y0,e);function eo(n,e){wc.indexOf(n)>-1||(wc.push(n),console.warn(e))}function b0(n,e){let t=[];for(let a of e.split(" ")){let l=[];for(let c of a.split(".")){let h=n[c]||O[c];h?typeof h=="function"?l.length?l=l.map(h):eo(c,`Modifier ${c} used at start of tag`):l.length?eo(c,`Tag ${c} used as modifier`):l=Array.isArray(h)?h:[h]:eo(c,`Unknown highlighting tag ${c}`)}for(let c of l)t.push(c)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),s=i+" "+t.map(a=>a.id),r=kc[s];if(r)return r.id;let o=kc[s]=et.define({id:vc.length,name:i,props:[Ju({[i]:t})]});return vc.push(o),o.id}fe.RTL,fe.LTR;const S0=n=>{let{state:e}=n,t=e.doc.lineAt(e.selection.main.from),i=Xa(n.state,t.from);return i.line?x0(n):i.block?w0(n):!1};function La(n,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let s=n(e,t);return s?(i(t.update(s)),!0):!1}}const x0=La(P0,0),v0=La(Af,0),w0=La((n,e)=>Af(n,e,Q0(e)),0);function Xa(n,e){let t=n.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const ln=50;function k0(n,{open:e,close:t},i,s){let r=n.sliceDoc(i-ln,i),o=n.sliceDoc(s,s+ln),a=/\s*$/.exec(r)[0].length,l=/^\s*/.exec(o)[0].length,c=r.length-a;if(r.slice(c-e.length,c)==e&&o.slice(l,l+t.length)==t)return{open:{pos:i-a,margin:a&&1},close:{pos:s+l,margin:l&&1}};let h,u;s-i<=2*ln?h=u=n.sliceDoc(i,s):(h=n.sliceDoc(i,i+ln),u=n.sliceDoc(s-ln,s));let f=/^\s*/.exec(h)[0].length,d=/\s*$/.exec(u)[0].length,p=u.length-d-t.length;return h.slice(f,f+e.length)==e&&u.slice(p,p+t.length)==t?{open:{pos:i+f+e.length,margin:/\s/.test(h.charAt(f+e.length))?1:0},close:{pos:s-d-t.length,margin:/\s/.test(u.charAt(p-1))?1:0}}:null}function Q0(n){let e=[];for(let t of n.selection.ranges){let i=n.doc.lineAt(t.from),s=t.to<=i.to?i:n.doc.lineAt(t.to);s.from>i.from&&s.from==t.to&&(s=t.to==i.to+1?i:n.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=s.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:s.to})}return e}function Af(n,e,t=e.selection.ranges){let i=t.map(r=>Xa(e,r.from).block);if(!i.every(r=>r))return null;let s=t.map((r,o)=>k0(e,i[o],r.from,r.to));if(n!=2&&!s.every(r=>r))return{changes:e.changes(t.map((r,o)=>s[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(n!=1&&s.some(r=>r)){let r=[];for(let o=0,a;os&&(r==o||o>u.from)){s=u.from;let f=/^\s*/.exec(u.text)[0].length,d=f==u.length,p=u.text.slice(f,f+c.length)==c?f:-1;fr.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:a,token:l,indent:c,empty:h,single:u}of i)(u||!h)&&r.push({from:a.from+c,insert:l+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(n!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:a,token:l}of i)if(a>=0){let c=o.from+a,h=c+l.length;o.text[h-o.from]==" "&&h++,r.push({from:c,to:h})}return{changes:r}}return null}const na=zt.define(),Qs=zt.define(),C0=Z.define(),bf=Z.define({combine(n){return yt(n,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,s)=>e(i,s)||t(i,s)})}}),Ba=Te.define({create(){return $t.empty},update(n,e){let t=e.state.facet(bf),i=e.annotation(na);if(i){let l=_e.fromTransaction(e,i.selection),c=i.side,h=c==0?n.undone:n.done;return l?h=Ys(h,h.length,t.minDepth,l):h=vf(h,e.startState.selection),new $t(c==0?i.rest:h,c==0?h:i.rest)}let s=e.annotation(Qs);if((s=="full"||s=="before")&&(n=n.isolate()),e.annotation(Pe.addToHistory)===!1)return e.changes.empty?n:n.addMapping(e.changes.desc);let r=_e.fromTransaction(e),o=e.annotation(Pe.time),a=e.annotation(Pe.userEvent);return r?n=n.addChanges(r,o,a,t,e):e.selection&&(n=n.addSelection(e.startState.selection,o,a,t.newGroupDelay)),(s=="full"||s=="after")&&(n=n.isolate()),n},toJSON(n){return{done:n.done.map(e=>e.toJSON()),undone:n.undone.map(e=>e.toJSON())}},fromJSON(n){return new $t(n.done.map(_e.fromJSON),n.undone.map(_e.fromJSON))}});function T0(n={}){return[Ba,bf.of(n),K.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Ia:e.inputType=="historyRedo"?js:null;return i?(e.preventDefault(),i(t)):!1}})]}function vr(n,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let s=t.field(Ba,!1);if(!s)return!1;let r=s.pop(n,t,e);return r?(i(r),!0):!1}}const Ia=vr(0,!1),js=vr(1,!1),R0=vr(0,!0),$0=vr(1,!0);function Sf(n){return function(e){let t=e.field(Ba,!1);if(!t)return 0;let i=n==0?t.done:t.undone;return i.length-(i.length&&!i[0].changes?1:0)}}const Qc=Sf(0),Pc=Sf(1);class _e{constructor(e,t,i,s,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=s,this.selectionsAfter=r}setSelAfter(e){return new _e(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(e){return new _e(e.changes&&Re.fromJSON(e.changes),[],e.mapped&&Zt.fromJSON(e.mapped),e.startSelection&&A.fromJSON(e.startSelection),e.selectionsAfter.map(A.fromJSON))}static fromTransaction(e,t){let i=ht;for(let s of e.startState.facet(C0)){let r=s(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new _e(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,ht)}static selection(e){return new _e(void 0,ht,void 0,void 0,e)}}function Ys(n,e,t,i){let s=e+1>t+20?e-t-1:0,r=n.slice(s,e);return r.push(i),r}function K0(n,e){let t=[],i=!1;return n.iterChangedRanges((s,r)=>t.push(s,r)),e.iterChangedRanges((s,r,o,a)=>{for(let l=0;l=c&&o<=h&&(i=!0)}}),i}function Z0(n,e){return n.ranges.length==e.ranges.length&&n.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function xf(n,e){return n.length?e.length?n.concat(e):n:e}const ht=[],M0=200;function vf(n,e){if(n.length){let t=n[n.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-M0));return i.length&&i[i.length-1].eq(e)?n:(i.push(e),Ys(n,n.length-1,1e9,t.setSelAfter(i)))}else return[_e.selection([e])]}function E0(n){let e=n[n.length-1],t=n.slice();return t[n.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function to(n,e){if(!n.length)return n;let t=n.length,i=ht;for(;t;){let s=U0(n[t-1],e,i);if(s.changes&&!s.changes.empty||s.effects.length){let r=n.slice(0,t);return r[t-1]=s,r}else e=s.mapped,t--,i=s.selectionsAfter}return i.length?[_e.selection(i)]:ht}function U0(n,e,t){let i=xf(n.selectionsAfter.length?n.selectionsAfter.map(a=>a.map(e)):ht,t);if(!n.changes)return _e.selection(i);let s=n.changes.map(e),r=e.mapDesc(n.changes,!0),o=n.mapped?n.mapped.composeDesc(r):r;return new _e(s,Y.mapEffects(n.effects,e),o,n.startSelection.map(r),i)}const F0=/^(input\.type|delete)($|\.)/;class $t{constructor(e,t,i=0,s=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=s}isolate(){return this.prevTime?new $t(this.done,this.undone):this}addChanges(e,t,i,s,r){let o=this.done,a=o[o.length-1];return a&&a.changes&&!a.changes.empty&&e.changes&&(!i||F0.test(i))&&(!a.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?n.moveByChar(t,e):wr(t,e))}function Be(n){return n.textDirectionAt(n.state.selection.main.head)==fe.LTR}const kf=n=>wf(n,!Be(n)),Qf=n=>wf(n,Be(n));function Pf(n,e){return bt(n,t=>t.empty?n.moveByGroup(t,e):wr(t,e))}const L0=n=>Pf(n,!Be(n)),X0=n=>Pf(n,Be(n));function B0(n,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(n.sliceDoc(e.from,e.to)))||e.firstChild}function kr(n,e,t){let i=Ce(n).resolveInner(e.head),s=t?_.closedBy:_.openedBy;for(let l=e.head;;){let c=t?i.childAfter(l):i.childBefore(l);if(!c)break;B0(n,c,s)?i=c:l=t?c.to:c.from}let r=i.type.prop(s),o,a;return r&&(o=t?Rt(n,i.from,1):Rt(n,i.to,-1))&&o.matched?a=t?o.end.to:o.end.from:a=t?i.to:i.from,A.cursor(a,t?-1:1)}const I0=n=>bt(n,e=>kr(n.state,e,!Be(n))),W0=n=>bt(n,e=>kr(n.state,e,Be(n)));function Cf(n,e){return bt(n,t=>{if(!t.empty)return wr(t,e);let i=n.moveVertically(t,e);return i.head!=t.head?i:n.moveToLineBoundary(t,e)})}const Tf=n=>Cf(n,!1),Rf=n=>Cf(n,!0);function $f(n){let e=n.scrollDOM.clientHeighto.empty?n.moveVertically(o,e,t.height):wr(o,e));if(s.eq(i.selection))return!1;let r;if(t.selfScroll){let o=n.coordsAtPos(i.selection.main.head),a=n.scrollDOM.getBoundingClientRect(),l=a.top+t.marginTop,c=a.bottom-t.marginBottom;o&&o.top>l&&o.bottomKf(n,!1),sa=n=>Kf(n,!0);function ai(n,e,t){let i=n.lineBlockAt(e.head),s=n.moveToLineBoundary(e,t);if(s.head==e.head&&s.head!=(t?i.to:i.from)&&(s=n.moveToLineBoundary(e,t,!1)),!t&&s.head==i.from&&i.length){let r=/^\s*/.exec(n.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(s=A.cursor(i.from+r))}return s}const q0=n=>bt(n,e=>ai(n,e,!0)),z0=n=>bt(n,e=>ai(n,e,!1)),V0=n=>bt(n,e=>ai(n,e,!Be(n))),j0=n=>bt(n,e=>ai(n,e,Be(n))),Y0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).from,1)),N0=n=>bt(n,e=>A.cursor(n.lineBlockAt(e.head).to,-1));function H0(n,e,t){let i=!1,s=Ji(n.selection,r=>{let o=Rt(n,r.head,-1)||Rt(n,r.head,1)||r.head>0&&Rt(n,r.head-1,1)||r.headH0(n,e);function ft(n,e,t){let i=Ji(n.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=e&&(s=A.range(s.head,s.anchor));let r=t(s);return A.range(s.anchor,r.head,r.goalColumn,r.bidiLevel||void 0,r.assoc)});return i.eq(n.state.selection)?!1:(n.dispatch(At(n.state,i)),!0)}function Zf(n,e){return ft(n,e,t=>n.moveByChar(t,e))}const Mf=n=>Zf(n,!Be(n)),Ef=n=>Zf(n,Be(n));function Uf(n,e){return ft(n,e,t=>n.moveByGroup(t,e))}const _0=n=>Uf(n,!Be(n)),J0=n=>Uf(n,Be(n)),ey=n=>{let e=!Be(n);return ft(n,e,t=>kr(n.state,t,e))},ty=n=>{let e=Be(n);return ft(n,e,t=>kr(n.state,t,e))};function Ff(n,e){return ft(n,e,t=>n.moveVertically(t,e))}const Df=n=>Ff(n,!1),Lf=n=>Ff(n,!0);function Xf(n,e){return ft(n,e,t=>n.moveVertically(t,e,$f(n).height))}const Tc=n=>Xf(n,!1),Rc=n=>Xf(n,!0),iy=n=>ft(n,!0,e=>ai(n,e,!0)),ny=n=>ft(n,!1,e=>ai(n,e,!1)),sy=n=>{let e=!Be(n);return ft(n,e,t=>ai(n,t,e))},ry=n=>{let e=Be(n);return ft(n,e,t=>ai(n,t,e))},oy=n=>ft(n,!1,e=>A.cursor(n.lineBlockAt(e.head).from)),ay=n=>ft(n,!0,e=>A.cursor(n.lineBlockAt(e.head).to)),$c=({state:n,dispatch:e})=>(e(At(n,{anchor:0})),!0),Kc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.doc.length})),!0),Zc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:0})),!0),Mc=({state:n,dispatch:e})=>(e(At(n,{anchor:n.selection.main.anchor,head:n.doc.length})),!0),ly=({state:n,dispatch:e})=>(e(n.update({selection:{anchor:0,head:n.doc.length},userEvent:"select"})),!0),cy=({state:n,dispatch:e})=>{let t=Qr(n).map(({from:i,to:s})=>A.range(i,Math.min(s+1,n.doc.length)));return e(n.update({selection:A.create(t),userEvent:"select"})),!0},hy=({state:n,dispatch:e})=>{let t=Ji(n.selection,i=>{let s=Ce(n),r=s.resolveStack(i.from,1);if(i.empty){let o=s.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:a}=o;if((a.from=i.to||a.to>i.to&&a.from<=i.from)&&o.next)return A.range(a.to,a.from)}return i});return t.eq(n.selection)?!1:(e(At(n,t)),!0)};function Bf(n,e){let{state:t}=n,i=t.selection,s=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let a=r;;){let l=n.moveVertically(a,e);if(l.heado.to){s.some(c=>c.head==l.head)||s.push(l);break}else{if(l.head==a.head)break;a=l}}}return s.length==i.ranges.length?!1:(n.dispatch(At(t,A.create(s,s.length-1))),!0)}const uy=n=>Bf(n,!1),fy=n=>Bf(n,!0),dy=({state:n,dispatch:e})=>{let t=n.selection,i=null;return t.ranges.length>1?i=A.create([t.main]):t.main.empty||(i=A.create([A.cursor(t.main.head)])),i?(e(At(n,i)),!0):!1};function In(n,e){if(n.state.readOnly)return!1;let t="delete.selection",{state:i}=n,s=i.changeByRange(r=>{let{from:o,to:a}=r;if(o==a){let l=e(r);lo&&(t="delete.forward",l=us(n,l,!0)),o=Math.min(o,l),a=Math.max(a,l)}else o=us(n,o,!1),a=us(n,a,!0);return o==a?{range:r}:{changes:{from:o,to:a},range:A.cursor(o,os(n)))i.between(e,e,(s,r)=>{se&&(e=t?r:s)});return e}const If=(n,e,t)=>In(n,i=>{let s=i.from,{state:r}=n,o=r.doc.lineAt(s),a,l;if(t&&!e&&s>o.from&&sIf(n,!1,!0),Wf=n=>If(n,!0,!1),qf=(n,e)=>In(n,t=>{let i=t.head,{state:s}=n,r=s.doc.lineAt(i),o=s.charCategorizer(i);for(let a=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?s.doc.lines:1)&&(i+=e?1:-1);break}let l=Ze(r.text,i-r.from,e)+r.from,c=r.text.slice(Math.min(i,l)-r.from,Math.max(i,l)-r.from),h=o(c);if(a!=null&&h!=a)break;(c!=" "||i!=t.head)&&(a=h),i=l}return i}),zf=n=>qf(n,!1),py=n=>qf(n,!0),my=n=>In(n,e=>{let t=n.lineBlockAt(e.head).to;return e.headIn(n,e=>{let t=n.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),Oy=n=>In(n,e=>{let t=n.moveToLineBoundary(e,!0).head;return e.head{if(n.readOnly)return!1;let t=n.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:se.of(["",""])},range:A.cursor(i.from)}));return e(n.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},Ay=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=n.changeByRange(i=>{if(!i.empty||i.from==0||i.from==n.doc.length)return{range:i};let s=i.from,r=n.doc.lineAt(s),o=s==r.from?s-1:Ze(r.text,s-r.from,!1)+r.from,a=s==r.to?s+1:Ze(r.text,s-r.from,!0)+r.from;return{changes:{from:o,to:a,insert:n.doc.slice(s,a).append(n.doc.slice(o,s))},range:A.cursor(a)}});return t.changes.empty?!1:(e(n.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function Qr(n){let e=[],t=-1;for(let i of n.selection.ranges){let s=n.doc.lineAt(i.from),r=n.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=n.doc.lineAt(i.to-1)),t>=s.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:s.from,to:r.to,ranges:[i]});t=r.number+1}return e}function Vf(n,e,t){if(n.readOnly)return!1;let i=[],s=[];for(let r of Qr(n)){if(t?r.to==n.doc.length:r.from==0)continue;let o=n.doc.lineAt(t?r.to+1:r.from-1),a=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+n.lineBreak});for(let l of r.ranges)s.push(A.range(Math.min(n.doc.length,l.anchor+a),Math.min(n.doc.length,l.head+a)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:n.lineBreak+o.text});for(let l of r.ranges)s.push(A.range(l.anchor-a,l.head-a))}}return i.length?(e(n.update({changes:i,scrollIntoView:!0,selection:A.create(s,n.selection.mainIndex),userEvent:"move.line"})),!0):!1}const by=({state:n,dispatch:e})=>Vf(n,e,!1),Sy=({state:n,dispatch:e})=>Vf(n,e,!0);function jf(n,e,t){if(n.readOnly)return!1;let i=[];for(let r of Qr(n))t?i.push({from:r.from,insert:n.doc.slice(r.from,r.to)+n.lineBreak}):i.push({from:r.to,insert:n.lineBreak+n.doc.slice(r.from,r.to)});let s=n.changes(i);return e(n.update({changes:s,selection:n.selection.map(s,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const xy=({state:n,dispatch:e})=>jf(n,e,!1),vy=({state:n,dispatch:e})=>jf(n,e,!0),wy=n=>{if(n.state.readOnly)return!1;let{state:e}=n,t=e.changes(Qr(e).map(({from:s,to:r})=>(s>0?s--:r{let r;if(n.lineWrapping){let o=n.lineBlockAt(s.head),a=n.coordsAtPos(s.head,s.assoc||1);a&&(r=o.bottom+n.documentTop-a.bottom+n.defaultLineHeight/2)}return n.moveVertically(s,!0,r)}).map(t);return n.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function ky(n,e){if(/\(\)|\[\]|\{\}/.test(n.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=Ce(n).resolveInner(e),i=t.childBefore(e),s=t.childAfter(e),r;return i&&s&&i.to<=e&&s.from>=e&&(r=i.type.prop(_.closedBy))&&r.indexOf(s.name)>-1&&n.doc.lineAt(i.to).from==n.doc.lineAt(s.from).from&&!/\S/.test(n.sliceDoc(i.to,s.from))?{from:i.to,to:s.from}:null}const Ec=Yf(!1),Qy=Yf(!0);function Yf(n){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(s=>{let{from:r,to:o}=s,a=e.doc.lineAt(r),l=!n&&r==o&&ky(e,r);n&&(r=o=(o<=a.to?a:e.doc.lineAt(o)).to);let c=new Sr(e,{simulateBreak:r,simulateDoubleBreak:!!l}),h=Fa(c,r);for(h==null&&(h=_i(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));oa.from&&r{let s=[];for(let o=i.from;o<=i.to;){let a=n.doc.lineAt(o);a.number>t&&(i.empty||i.to>a.from)&&(e(a,s,i),t=a.number),o=a.to+1}let r=n.changes(s);return{changes:s,range:A.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}const Py=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let t=Object.create(null),i=new Sr(n,{overrideIndentation:r=>{let o=t[r];return o??-1}}),s=Wa(n,(r,o,a)=>{let l=Fa(i,r.from);if(l==null)return;/\S/.test(r.text)||(l=0);let c=/^\s*/.exec(r.text)[0],h=Tn(n,l);(c!=h||a.fromn.readOnly?!1:(e(n.update(Wa(n,(t,i)=>{i.push({from:t.from,insert:n.facet(br)})}),{userEvent:"input.indent"})),!0),Hf=({state:n,dispatch:e})=>n.readOnly?!1:(e(n.update(Wa(n,(t,i)=>{let s=/^\s*/.exec(t.text)[0];if(!s)return;let r=_i(s,n.tabSize),o=0,a=Tn(n,Math.max(0,r-qs(n)));for(;o(n.setTabFocusMode(),!0),Ty=[{key:"Ctrl-b",run:kf,shift:Mf,preventDefault:!0},{key:"Ctrl-f",run:Qf,shift:Ef},{key:"Ctrl-p",run:Tf,shift:Df},{key:"Ctrl-n",run:Rf,shift:Lf},{key:"Ctrl-a",run:Y0,shift:oy},{key:"Ctrl-e",run:N0,shift:ay},{key:"Ctrl-d",run:Wf},{key:"Ctrl-h",run:ra},{key:"Ctrl-k",run:my},{key:"Ctrl-Alt-h",run:zf},{key:"Ctrl-o",run:yy},{key:"Ctrl-t",run:Ay},{key:"Ctrl-v",run:sa}],Ry=[{key:"ArrowLeft",run:kf,shift:Mf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:L0,shift:_0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:V0,shift:sy,preventDefault:!0},{key:"ArrowRight",run:Qf,shift:Ef,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:X0,shift:J0,preventDefault:!0},{mac:"Cmd-ArrowRight",run:j0,shift:ry,preventDefault:!0},{key:"ArrowUp",run:Tf,shift:Df,preventDefault:!0},{mac:"Cmd-ArrowUp",run:$c,shift:Zc},{mac:"Ctrl-ArrowUp",run:Cc,shift:Tc},{key:"ArrowDown",run:Rf,shift:Lf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:Kc,shift:Mc},{mac:"Ctrl-ArrowDown",run:sa,shift:Rc},{key:"PageUp",run:Cc,shift:Tc},{key:"PageDown",run:sa,shift:Rc},{key:"Home",run:z0,shift:ny,preventDefault:!0},{key:"Mod-Home",run:$c,shift:Zc},{key:"End",run:q0,shift:iy,preventDefault:!0},{key:"Mod-End",run:Kc,shift:Mc},{key:"Enter",run:Ec,shift:Ec},{key:"Mod-a",run:ly},{key:"Backspace",run:ra,shift:ra,preventDefault:!0},{key:"Delete",run:Wf,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:zf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:py,preventDefault:!0},{mac:"Mod-Backspace",run:gy,preventDefault:!0},{mac:"Mod-Delete",run:Oy,preventDefault:!0}].concat(Ty.map(n=>({mac:n.key,run:n.run,shift:n.shift}))),$y=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:I0,shift:ey},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:W0,shift:ty},{key:"Alt-ArrowUp",run:by},{key:"Shift-Alt-ArrowUp",run:xy},{key:"Alt-ArrowDown",run:Sy},{key:"Shift-Alt-ArrowDown",run:vy},{key:"Mod-Alt-ArrowUp",run:uy},{key:"Mod-Alt-ArrowDown",run:fy},{key:"Escape",run:dy},{key:"Mod-Enter",run:Qy},{key:"Alt-l",mac:"Ctrl-l",run:cy},{key:"Mod-i",run:hy,preventDefault:!0},{key:"Mod-[",run:Hf},{key:"Mod-]",run:Nf},{key:"Mod-Alt-\\",run:Py},{key:"Shift-Mod-k",run:wy},{key:"Shift-Mod-\\",run:G0},{key:"Mod-/",run:S0},{key:"Alt-A",run:v0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Cy}].concat(Ry),Ky={key:"Tab",run:Nf,shift:Hf};class Gf{constructor(e,t,i,s){this.state=e,this.pos=t,this.explicit=i,this.view=s,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=Ce(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),s=t.text.slice(i-t.from,this.pos-t.from),r=s.search(Jf(e,!1));return r<0?null:{from:i+r,to:this.pos,text:s.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}}function Uc(n){let e=Object.keys(n).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function Zy(n){let e=Object.create(null),t=Object.create(null);for(let{label:s}of n){e[s[0]]=!0;for(let r=1;rtypeof s=="string"?{label:s}:s),[t,i]=e.every(s=>/^\w+$/.test(s.label))?[/\w*$/,/\w+$/]:Zy(e);return s=>{let r=s.matchBefore(i);return r||s.explicit?{from:r?r.from:s.pos,options:e,validFor:t}:null}}function My(n,e){return t=>{for(let i=Ce(t.state).resolveInner(t.pos,-1);i;i=i.parent){if(n.indexOf(i.name)>-1)return null;if(i.type.isTop)break}return e(t)}}let Fc=class{constructor(e,t,i,s){this.completion=e,this.source=t,this.match=i,this.score=s}};function yi(n){return n.selection.main.from}function Jf(n,e){var t;let{source:i}=n,s=e&&i[0]!="^",r=i[i.length-1]!="$";return!s&&!r?n:new RegExp(`${s?"^":""}(?:${i})${r?"$":""}`,(t=n.flags)!==null&&t!==void 0?t:n.ignoreCase?"i":"")}const qa=zt.define();function Ey(n,e,t,i){let{main:s}=n.selection,r=t-s.from,o=i-s.from;return{...n.changeByRange(a=>{if(a!=s&&t!=i&&n.sliceDoc(a.from+r,a.from+o)!=n.sliceDoc(t,i))return{range:a};let l=n.toText(e);return{changes:{from:a.from+r,to:i==s.from?a.to:a.from+o,insert:l},range:A.cursor(a.from+r+l.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const Dc=new WeakMap;function Uy(n){if(!Array.isArray(n))return n;let e=Dc.get(n);return e||Dc.set(n,e=_f(n)),e}const Ns=Y.define(),Rn=Y.define();class Fy{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t=48&&Q<=57||Q>=97&&Q<=122?2:Q>=65&&Q<=90?1:0:(P=ma(Q))!=P.toLowerCase()?1:P!=P.toUpperCase()?2:0;(!x||w==1&&g||C==0&&w!=0)&&(t[u]==Q||i[u]==Q&&(f=!0)?o[u++]=x:o.length&&(y=!1)),C=w,x+=Qt(Q)}return u==l&&o[0]==0&&y?this.result(-100+(f?-200:0),o,e):d==l&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):a>-1?this.ret(-700-e.length,[a,a+this.pattern.length]):d==l?this.ret(-900-e.length,[p,m]):u==l?this.result(-100+(f?-200:0)+-700+(y?0:-1100),o,e):t.length==2?null:this.result((s[0]?-700:0)+-200+-1100,s,e)}result(e,t,i){let s=[],r=0;for(let o of t){let a=o+(this.astral?Qt(Ne(i,o)):1);r&&s[r-1]==o?s[r-1]=a:(s[r++]=o,s[r++]=a)}return this.ret(e-i.length,s)}}class Dy{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:Ly,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>Lc(e(i),t(i)),optionClass:(e,t)=>i=>Lc(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function Lc(n,e){return n?e?n+" "+e:n:e}function Ly(n,e,t,i,s,r){let o=n.textDirection==fe.RTL,a=o,l=!1,c="top",h,u,f=e.left-s.left,d=s.right-e.right,p=i.right-i.left,m=i.bottom-i.top;if(a&&f=m||x>e.top?h=t.bottom-e.top:(c="bottom",h=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,y=(e.right-e.left)/r.offsetWidth;return{style:`${c}: ${h/g}px; max-width: ${u/y}px`,class:"cm-completionInfo-"+(l?o?"left-narrow":"right-narrow":a?"left":"right")}}const za=Y.define();function Xy(n){let e=n.addToOptions.slice();return n.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(s=>"cm-completionIcon-"+s)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,s,r){let o=document.createElement("span");o.className="cm-completionLabel";let a=t.displayLabel||t.label,l=0;for(let c=0;cl&&o.appendChild(document.createTextNode(a.slice(l,h)));let f=o.appendChild(document.createElement("span"));f.appendChild(document.createTextNode(a.slice(h,u))),f.className="cm-completionMatchedText",l=u}return lt.position-i.position).map(t=>t.render)}function io(n,e,t){if(n<=t)return{from:0,to:n};if(e<0&&(e=0),e<=n>>1){let s=Math.floor(e/t);return{from:s*t,to:(s+1)*t}}let i=Math.ceil((n-e)/t);return{from:n-i*t,to:n-(i-1)*t}}class By{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:l=>this.placeInfo(l),key:this},this.space=null,this.currentClass="";let s=e.state.field(t),{options:r,selected:o}=s.open,a=e.state.facet(Ke);this.optionContent=Xy(a),this.optionClass=a.optionClass,this.tooltipClass=a.tooltipClass,this.range=io(r.length,o,a.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",l=>{let{options:c}=e.state.field(t).open;for(let h=l.target,u;h&&h!=this.dom;h=h.parentNode)if(h.nodeName=="LI"&&(u=/-(\d+)$/.exec(h.id))&&+u[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;h!=null&&(e.dispatch({effects:za.of(h)}),l.preventDefault())}}),this.dom.addEventListener("focusout",l=>{let c=e.state.field(this.stateField,!1);c&&c.tooltip&&e.state.facet(Ke).closeOnBlur&&l.relatedTarget!=e.contentDOM&&e.dispatch({effects:Rn.of(null)})}),this.showOptions(r,s.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),s=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=s){let{options:r,selected:o,disabled:a}=i.open;(!s.open||s.open.options!=r)&&(this.range=io(r.length,o,e.state.facet(Ke).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),a!=((t=s.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!a)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected=this.range.to)&&(this.range=io(t.options.length,t.selected,this.view.state.facet(Ke).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:s}=t.options[t.selected],{info:r}=s;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(s);if(!o)return;"then"in o?o.then(a=>{a&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(a,s)}).catch(a=>ze(this.view.state,a,"completion info")):(this.addInfoPane(o,s),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:s,destroy:r}=e;i.appendChild(s),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,s=this.range.from;i;i=i.nextSibling,s++)i.nodeName!="LI"||!i.id?s--:s==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&Wy(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),s=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return s.top>Math.min(r.bottom,t.bottom)-10||s.bottom{o.target==s&&o.preventDefault()});let r=null;for(let o=i.from;oi.from||i.from==0))if(r=f,typeof c!="string"&&c.header)s.appendChild(c.header(c));else{let d=s.appendChild(document.createElement("completion-section"));d.textContent=f}}const h=s.appendChild(document.createElement("li"));h.id=t+"-"+o,h.setAttribute("role","option");let u=this.optionClass(a);u&&(h.className=u);for(let f of this.optionContent){let d=f(a,this.view.state,this.view,l);d&&h.appendChild(d)}}return i.from&&s.classList.add("cm-completionListIncompleteTop"),i.tonew By(t,n,e)}function Wy(n,e){let t=n.getBoundingClientRect(),i=e.getBoundingClientRect(),s=t.height/n.offsetHeight;i.topt.bottom&&(n.scrollTop+=(i.bottom-t.bottom)/s)}function Xc(n){return(n.boost||0)*100+(n.apply?10:0)+(n.info?5:0)+(n.type?1:0)}function qy(n,e){let t=[],i=null,s=null,r=h=>{t.push(h);let{section:u}=h.completion;if(u){i||(i=[]);let f=typeof u=="string"?u:u.name;i.some(d=>d.name==f)||i.push(typeof u=="string"?{name:f}:u)}},o=e.facet(Ke);for(let h of n)if(h.hasResult()){let u=h.result.getMatch;if(h.result.filter===!1)for(let f of h.result.options)r(new Fc(f,h.source,u?u(f):[],1e9-t.length));else{let f=e.sliceDoc(h.from,h.to),d,p=o.filterStrict?new Dy(f):new Fy(f);for(let m of h.result.options)if(d=p.match(m.label)){let g=m.displayLabel?u?u(m,d.matched):[]:d.matched,y=d.score+(m.boost||0);if(r(new Fc(m,h.source,g,y)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:x}=m.section;s||(s=Object.create(null)),s[x]=Math.max(y,s[x]||-1e9)}}}}if(i){let h=Object.create(null),u=0,f=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?s[p.name]-s[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.namef.score-u.score||c(u.completion,f.completion))){let u=h.completion;!l||l.label!=u.label||l.detail!=u.detail||l.type!=null&&u.type!=null&&l.type!=u.type||l.apply!=u.apply||l.boost!=u.boost?a.push(h):Xc(h.completion)>Xc(l)&&(a[a.length-1]=h),l=h.completion}return a}class Ki{constructor(e,t,i,s,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=s,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new Ki(this.options,Bc(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,s,r,o){if(s&&!o&&e.some(c=>c.isPending))return s.setDisabled();let a=qy(e,t);if(!a.length)return s&&e.some(c=>c.isPending)?s.setDisabled():null;let l=t.facet(Ke).selectOnOpen?0:-1;if(s&&s.selected!=l&&s.selected!=-1){let c=s.options[s.selected].completion;for(let h=0;hh.hasResult()?Math.min(c,h.from):c,1e8),create:Hy,above:r.aboveCursor},s?s.timestamp:Date.now(),l,!1)}map(e){return new Ki(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new Ki(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class Hs{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Hs(Yy,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(Ke),r=(i.override||t.languageDataAt("autocomplete",yi(t)).map(Uy)).map(l=>(this.active.find(h=>h.source==l)||new ut(l,this.active.some(h=>h.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((l,c)=>l==this.active[c])&&(r=this.active);let o=this.open,a=e.effects.some(l=>l.is(Va));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(l=>l.hasResult()&&e.changes.touchesRange(l.from,l.to))||!zy(r,this.active)||a?o=Ki.build(r,t,this.id,o,i,a):o&&o.disabled&&!r.some(l=>l.isPending)&&(o=null),!o&&r.every(l=>!l.isPending)&&r.some(l=>l.hasResult())&&(r=r.map(l=>l.hasResult()?new ut(l.source,0):l));for(let l of e.effects)l.is(za)&&(o=o&&o.setSelected(l.value,this.id));return r==this.active&&o==this.open?this:new Hs(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?Vy:jy}}function zy(n,e){if(n==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=n+"-"+e),t}const Yy=[];function ed(n,e){if(n.isUserEvent("input.complete")){let i=n.annotation(qa);if(i&&e.activateOnCompletion(i))return 12}let t=n.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:n.isUserEvent("delete.backward")?2:n.selection?8:n.docChanged?16:0}class ut{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=ed(e,t),s=this;(i&8||i&16&&this.touches(e))&&(s=new ut(s.source,0)),i&4&&s.state==0&&(s=new ut(this.source,1)),s=s.updateFor(e,i);for(let r of e.effects)if(r.is(Ns))s=new ut(s.source,1,r.value);else if(r.is(Rn))s=new ut(s.source,0);else if(r.is(Va))for(let o of r.value)o.source==s.source&&(s=o);return s}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(yi(e.state))}}class Fi extends ut{constructor(e,t,i,s,r,o){super(e,3,t),this.limit=i,this.result=s,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let s=this.result;s.map&&!e.changes.empty&&(s=s.map(s,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),a=yi(e.state);if(a>o||!s||t&2&&(yi(e.startState)==this.from||at.map(e))}}),He=Te.define({create(){return Hs.start()},update(n,e){return n.update(e)},provide:n=>[yr.from(n,e=>e.tooltip),K.contentAttributes.from(n,e=>e.attrs)]});function ja(n,e){const t=e.completion.apply||e.completion.label;let i=n.state.field(He).active.find(s=>s.source==e.source);return i instanceof Fi?(typeof t=="string"?n.dispatch({...Ey(n.state,t,i.from,i.to),annotations:qa.of(e.completion)}):t(n,e.completion,i.from,i.to),!0):!1}const Hy=Iy(He,ja);function fs(n,e="option"){return t=>{let i=t.state.field(He,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+s*(n?1:-1):n?0:o-1;return a<0?a=e=="page"?0:o-1:a>=o&&(a=e=="page"?o-1:0),t.dispatch({effects:za.of(a)}),!0}}const Gy=n=>{let e=n.state.field(He,!1);return n.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestampn.state.field(He,!1)?(n.dispatch({effects:Ns.of(!0)}),!0):!1,_y=n=>{let e=n.state.field(He,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(n.dispatch({effects:Rn.of(null)}),!0)};class Jy{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const eA=50,tA=1e3,iA=xe.fromClass(class{constructor(n){this.view=n,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of n.state.field(He).active)e.isPending&&this.startQuery(e)}update(n){let e=n.state.field(He),t=n.state.facet(Ke);if(!n.selectionSet&&!n.docChanged&&n.startState.field(He)==e)return;let i=n.transactions.some(r=>{let o=ed(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;reA&&Date.now()-o.time>tA){for(let a of o.context.abortListeners)try{a()}catch(l){ze(this.view.state,l)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...n.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),n.transactions.some(r=>r.effects.some(o=>o.is(Ns)))&&(this.pendingStart=!0);let s=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),s):-1,this.composing!=0)for(let r of n.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:n}=this.view,e=n.field(He);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}startQuery(n){let{state:e}=this.view,t=yi(e),i=new Gf(e,t,n.explicit,this.view),s=new Jy(n,i);this.running.push(s),Promise.resolve(n.source(i)).then(r=>{s.context.aborted||(s.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:Rn.of(null)}),ze(this.view.state,r)})}scheduleAccept(){this.running.every(n=>n.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(Ke).updateSyncTime))}accept(){var n;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(Ke),i=this.view.state.field(He);for(let s=0;sa.source==r.active.source);if(o&&o.isPending)if(r.done==null){let a=new ut(r.active.source,0);for(let l of r.updates)a=a.update(l,t);a.isPending||e.push(a)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:Va.of(e)})}},{eventHandlers:{blur(n){let e=this.view.state.field(He,!1);if(e&&e.tooltip&&this.view.state.facet(Ke).closeOnBlur){let t=e.open&&Xu(this.view,e.open.tooltip);(!t||!t.dom.contains(n.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:Rn.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:Ns.of(!1)}),20),this.composing=0}}}),nA=typeof navigator=="object"&&/Win/.test(navigator.platform),sA=oi.highest(K.domEventHandlers({keydown(n,e){let t=e.state.field(He,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||n.key.length>1||n.ctrlKey&&!(nA&&n.altKey)||n.metaKey)return!1;let i=t.open.options[t.open.selected],s=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||s.result.commitCharacters;return r&&r.indexOf(n.key)>-1&&ja(e,i),!1}})),td=K.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class rA{constructor(e,t,i,s){this.field=e,this.line=t,this.from=i,this.to=s}}class Ya{constructor(e,t,i){this.field=e,this.from=t,this.to=i}map(e){let t=e.mapPos(this.from,-1,De.TrackDel),i=e.mapPos(this.to,1,De.TrackDel);return t==null||i==null?null:new Ya(this.field,t,i)}}class Na{constructor(e,t){this.lines=e,this.fieldPositions=t}instantiate(e,t){let i=[],s=[t],r=e.doc.lineAt(t),o=/^\s*/.exec(r.text)[0];for(let l of this.lines){if(i.length){let c=o,h=/^\t*/.exec(l)[0].length;for(let u=0;unew Ya(l.field,s[l.line]+l.from,s[l.line]+l.to));return{text:i,ranges:a}}static parse(e){let t=[],i=[],s=[],r;for(let o of e.split(/\r\n?|\n/)){for(;r=/[#$]\{(?:(\d+)(?::([^{}]*))?|((?:\\[{}]|[^{}])*))\}/.exec(o);){let a=r[1]?+r[1]:null,l=r[2]||r[3]||"",c=-1;a===0&&(a=1e9);let h=l.replace(/\\[{}]/g,u=>u[1]);for(let u=0;u=c&&f.field++}for(let u of s)if(u.line==i.length&&u.from>r.index){let f=r[2]?3+(r[1]||"").length:2;u.from-=f,u.to-=f}s.push(new rA(c,i.length,r.index,r.index+h.length)),o=o.slice(0,r.index)+l+o.slice(r.index+r[0].length)}o=o.replace(/\\([{}])/g,(a,l,c)=>{for(let h of s)h.line==i.length&&h.from>c&&(h.from--,h.to--);return l}),i.push(o)}return new Na(i,s)}}let oA=I.widget({widget:new class extends Ut{toDOM(){let n=document.createElement("span");return n.className="cm-snippetFieldPosition",n}ignoreEvent(){return!1}}}),aA=I.mark({class:"cm-snippetField"});class en{constructor(e,t){this.ranges=e,this.active=t,this.deco=I.set(e.map(i=>(i.from==i.to?oA:aA).range(i.from,i.to)),!0)}map(e){let t=[];for(let i of this.ranges){let s=i.map(e);if(!s)return null;t.push(s)}return new en(t,this.active)}selectionInsideField(e){return e.ranges.every(t=>this.ranges.some(i=>i.field==this.active&&i.from<=t.from&&i.to>=t.to))}}const Wn=Y.define({map(n,e){return n&&n.map(e)}}),lA=Y.define(),$n=Te.define({create(){return null},update(n,e){for(let t of e.effects){if(t.is(Wn))return t.value;if(t.is(lA)&&n)return new en(n.ranges,t.value)}return n&&e.docChanged&&(n=n.map(e.changes)),n&&e.selection&&!n.selectionInsideField(e.selection)&&(n=null),n},provide:n=>K.decorations.from(n,e=>e?e.deco:I.none)});function Ha(n,e){return A.create(n.filter(t=>t.field==e).map(t=>A.range(t.from,t.to)))}function cA(n){let e=Na.parse(n);return(t,i,s,r)=>{let{text:o,ranges:a}=e.instantiate(t.state,s),{main:l}=t.state.selection,c={changes:{from:s,to:r==l.from?l.to:r,insert:se.of(o)},scrollIntoView:!0,annotations:i?[qa.of(i),Pe.userEvent.of("input.complete")]:void 0};if(a.length&&(c.selection=Ha(a,0)),a.some(h=>h.field>0)){let h=new en(a,0),u=c.effects=[Wn.of(h)];t.state.field($n,!1)===void 0&&u.push(Y.appendConfig.of([$n,pA,mA,td]))}t.dispatch(t.state.update(c))}}function id(n){return({state:e,dispatch:t})=>{let i=e.field($n,!1);if(!i||n<0&&i.active==0)return!1;let s=i.active+n,r=n>0&&!i.ranges.some(o=>o.field==s+n);return t(e.update({selection:Ha(i.ranges,s),effects:Wn.of(r?null:new en(i.ranges,s)),scrollIntoView:!0})),!0}}const hA=({state:n,dispatch:e})=>n.field($n,!1)?(e(n.update({effects:Wn.of(null)})),!0):!1,uA=id(1),fA=id(-1),dA=[{key:"Tab",run:uA,shift:fA},{key:"Escape",run:hA}],Ic=Z.define({combine(n){return n.length?n[0]:dA}}),pA=oi.highest(Or.compute([Ic],n=>n.facet(Ic)));function Ye(n,e){return{...e,apply:cA(n)}}const mA=K.domEventHandlers({mousedown(n,e){let t=e.state.field($n,!1),i;if(!t||(i=e.posAtCoords({x:n.clientX,y:n.clientY}))==null)return!1;let s=t.ranges.find(r=>r.from<=i&&r.to>=i);return!s||s.field==t.active?!1:(e.dispatch({selection:Ha(t.ranges,s.field),effects:Wn.of(t.ranges.some(r=>r.field>s.field)?new en(t.ranges,s.field):null),scrollIntoView:!0}),!0)}}),Kn={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},mi=Y.define({map(n,e){let t=e.mapPos(n,-1,De.TrackAfter);return t??void 0}}),Ga=new class extends ei{};Ga.startSide=1;Ga.endSide=-1;const nd=Te.define({create(){return H.empty},update(n,e){if(n=n.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);n=n.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(mi)&&(n=n.update({add:[Ga.range(t.value,t.value+1)]}));return n}});function gA(){return[yA,nd]}const so="()[]{}<>«»»«[]{}";function sd(n){for(let e=0;e{if((OA?n.composing:n.compositionStarted)||n.state.readOnly)return!1;let s=n.state.selection.main;if(i.length>2||i.length==2&&Qt(Ne(i,0))==1||e!=s.from||t!=s.to)return!1;let r=SA(n.state,i);return r?(n.dispatch(r),!0):!1}),AA=({state:n,dispatch:e})=>{if(n.readOnly)return!1;let i=rd(n,n.selection.main.head).brackets||Kn.brackets,s=null,r=n.changeByRange(o=>{if(o.empty){let a=xA(n.doc,o.head);for(let l of i)if(l==a&&Pr(n.doc,o.head)==sd(Ne(l,0)))return{changes:{from:o.head-l.length,to:o.head+l.length},range:A.cursor(o.head-l.length)}}return{range:s=o}});return s||e(n.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!s},bA=[{key:"Backspace",run:AA}];function SA(n,e){let t=rd(n,n.selection.main.head),i=t.brackets||Kn.brackets;for(let s of i){let r=sd(Ne(s,0));if(e==s)return r==s?kA(n,s,i.indexOf(s+s+s)>-1,t):vA(n,s,r,t.before||Kn.before);if(e==r&&od(n,n.selection.main.from))return wA(n,s,r)}return null}function od(n,e){let t=!1;return n.field(nd).between(0,n.doc.length,i=>{i==e&&(t=!0)}),t}function Pr(n,e){let t=n.sliceString(e,e+2);return t.slice(0,Qt(Ne(t,0)))}function xA(n,e){let t=n.sliceString(e-2,e);return Qt(Ne(t,0))==t.length?t:t.slice(1)}function vA(n,e,t,i){let s=null,r=n.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:mi.of(o.to+e.length),range:A.range(o.anchor+e.length,o.head+e.length)};let a=Pr(n.doc,o.head);return!a||/\s/.test(a)||i.indexOf(a)>-1?{changes:{insert:e+t,from:o.head},effects:mi.of(o.head+e.length),range:A.cursor(o.head+e.length)}:{range:s=o}});return s?null:n.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function wA(n,e,t){let i=null,s=n.changeByRange(r=>r.empty&&Pr(n.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:A.cursor(r.head+t.length)}:i={range:r});return i?null:n.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function kA(n,e,t,i){let s=i.stringPrefixes||Kn.stringPrefixes,r=null,o=n.changeByRange(a=>{if(!a.empty)return{changes:[{insert:e,from:a.from},{insert:e,from:a.to}],effects:mi.of(a.to+e.length),range:A.range(a.anchor+e.length,a.head+e.length)};let l=a.head,c=Pr(n.doc,l),h;if(c==e){if(Wc(n,l))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(od(n,l)){let f=t&&n.sliceDoc(l,l+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:l,to:l+f.length,insert:f},range:A.cursor(l+f.length)}}}else{if(t&&n.sliceDoc(l-2*e.length,l)==e+e&&(h=qc(n,l-2*e.length,s))>-1&&Wc(n,h))return{changes:{insert:e+e+e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)};if(n.charCategorizer(l)(c)!=ye.Word&&qc(n,l,s)>-1&&!QA(n,l,e,s))return{changes:{insert:e+e,from:l},effects:mi.of(l+e.length),range:A.cursor(l+e.length)}}return{range:r=a}});return r?null:n.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function Wc(n,e){let t=Ce(n).resolveInner(e+1);return t.parent&&t.from==e}function QA(n,e,t,i){let s=Ce(n).resolveInner(e,-1),r=i.reduce((o,a)=>Math.max(o,a.length),0);for(let o=0;o<5;o++){let a=n.sliceDoc(s.from,Math.min(s.to,s.from+t.length+r)),l=a.indexOf(t);if(!l||l>-1&&i.indexOf(a.slice(0,l))>-1){let h=s.firstChild;for(;h&&h.from==s.from&&h.to-h.from>t.length+l;){if(n.sliceDoc(h.to-t.length,h.to)==t)return!1;h=h.firstChild}return!0}let c=s.to==e&&s.parent;if(!c)break;s=c}return!1}function qc(n,e,t){let i=n.charCategorizer(e);if(i(n.sliceDoc(e-1,e))!=ye.Word)return e;for(let s of t){let r=e-s.length;if(n.sliceDoc(r,e)==s&&i(n.sliceDoc(r-1,r))!=ye.Word)return r}return-1}function PA(n={}){return[sA,He,Ke.of(n),iA,CA,td]}const ad=[{key:"Ctrl-Space",run:no},{mac:"Alt-`",run:no},{mac:"Alt-i",run:no},{key:"Escape",run:_y},{key:"ArrowDown",run:fs(!0)},{key:"ArrowUp",run:fs(!1)},{key:"PageDown",run:fs(!0,"page")},{key:"PageUp",run:fs(!1,"page")},{key:"Enter",run:Gy}],CA=oi.highest(Or.computeN([Ke],n=>n.facet(Ke).defaultKeymap?[ad]:[]));var zc={};class Gs{constructor(e,t,i,s,r,o,a,l,c,h=0,u){this.p=e,this.stack=t,this.state=i,this.reducePos=s,this.pos=r,this.score=o,this.buffer=a,this.bufferBase=l,this.curContext=c,this.lookAhead=h,this.parent=u}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let s=e.parser.context;return new Gs(e,[],t,i,i,0,[],0,s?new Vc(s,s.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,s=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[s])===null||t===void 0)&&t.isAnonymous)&&(c==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=h):this.p.lastBigReductionSizel;)this.stack.pop();this.reduceContext(s,c)}storeNode(e,t,i,s=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,s);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let a=!1;for(let l=o;l>0&&this.buffer[l-2]>i;l-=4)if(this.buffer[l-1]>=0){a=!0;break}if(a)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,s>4&&(s-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=s}}shift(e,t,i,s){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=s;let a=o.stateFlag(r,1);!a&&(s>i||t<=o.maxNode)&&(this.reducePos=s),this.pushState(r,a?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,s,4)}else this.pos=s,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,s,4)}apply(e,t,i,s){e&65536?this.reduce(e):this.shift(e,t,i,s)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let s=this.pos;this.reducePos=this.pos=s+e.length,this.pushState(t,s),this.buffer.push(i,s,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),s=e.bufferBase+t;for(;e&&s==e.bufferBase;)e=e.parent;return new Gs(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,s,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new TA(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let s=[];for(let r=0,o;rl&1&&a==o)||s.push(t[r],o)}t=s}let i=[];for(let s=0;s>19,s=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],s,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(s,r)=>{if(!t.includes(s))return t.push(s),e.allActions(s,o=>{if(!(o&393216))if(o&65536){let a=(o>>19)-r;if(a>1){let l=o&65535,c=this.stack.length-a*3;if(c>=0&&e.getGoto(this.stack[c],l,!1)>=0)return a<<19|65536|l}}else{let a=i(o,r+1);if(a!=null)return a}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}}class Vc{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class TA{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let s=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=s}}class _s{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new _s(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new _s(this.stack,this.pos,this.index)}}function dn(n,e=Uint16Array){if(typeof n!="string")return n;let t=null;for(let i=0,s=0;i=92&&o--,o>=34&&o--;let l=o-32;if(l>=46&&(l-=46,a=!0),r+=l,a)break;r*=46}t?t[s++]=r:t=new e(r)}return t}class Ps{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const jc=new Ps;class RA{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=jc,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,s=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(s==this.ranges.length-1)return null;let o=this.ranges[++s];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,s;if(t>=0&&t=this.chunk2Pos&&ia.to&&(this.chunk2=this.chunk2.slice(0,a.to-i)),s=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),s}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=jc,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let s of this.ranges){if(s.from>=t)break;s.to>e&&(i+=this.input.read(Math.max(s.from,e),Math.min(s.to,t)))}return i}}class Di{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;ld(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}Di.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class oa{constructor(e,t,i){this.precTable=t,this.elseToken=i,this.data=typeof e=="string"?dn(e):e}token(e,t){let i=e.pos,s=0;for(;;){let r=e.next<0,o=e.resolveOffset(1,1);if(ld(this.data,e,t,0,this.data,this.precTable),e.token.value>-1)break;if(this.elseToken==null)return;if(r||s++,o==null)break;e.reset(o,e.token)}s&&(e.reset(i,e.token),e.acceptToken(this.elseToken,s))}}oa.prototype.contextual=Di.prototype.fallback=Di.prototype.extend=!1;class qn{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function ld(n,e,t,i,s,r){let o=0,a=1<0){let p=n[d];if(l.allows(p)&&(e.token.value==-1||e.token.value==p||$A(p,e.token.value,s,r))){e.acceptToken(p);break}}let h=e.next,u=0,f=n[o+2];if(e.next<0&&f>u&&n[c+f*3-3]==65535){o=n[c+f*3-1];continue e}for(;u>1,p=c+d+(d<<1),m=n[p],g=n[p+1]||65536;if(h=g)u=d+1;else{o=n[p+2],e.advance();continue e}}break}}function Yc(n,e,t){for(let i=e,s;(s=n[i])!=65535;i++)if(s==t)return i-e;return-1}function $A(n,e,t,i){let s=Yc(t,i,e);return s<0||Yc(t,i,n)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(n.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:n.length}}class KA{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?Nc(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?Nc(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof ke){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}}class ZA{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Ps)}getActions(e){let t=0,i=null,{parser:s}=e.p,{tokenizers:r}=s,o=s.stateSlot(e.state,3),a=e.curContext?e.curContext.hash:0,l=0;for(let c=0;cu.end+25&&(l=Math.max(u.lookAhead,l)),u.value!=0)){let f=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!h.extend&&(i=u,t>f))break}}for(;this.actions.length>t;)this.actions.pop();return l&&e.setLookAhead(l),!i&&e.pos==this.stream.end&&(i=new Ps,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Ps,{pos:i,p:s}=e;return t.start=i,t.end=Math.min(i+1,s.stream.end),t.value=i==s.stream.end?s.parser.eofTerm:0,t}updateCachedToken(e,t,i){let s=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(s,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(a>>1)){(a&1)==0?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=this.stream.clipPos(s+1)}putAction(e,t,i,s){for(let r=0;re.bufferLength*4?new KA(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],s,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(a);else{if(this.advanceStack(a,i,e))continue;{s||(s=[],r=[]),s.push(a);let l=this.tokens.getMainToken(a);r.push(l.value,l.end)}}break}}if(!i.length){let o=s&&FA(s);if(o)return nt&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw nt&&s&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&s){let o=this.stoppedAt!=null&&s[0].pos>this.stoppedAt?s[0]:this.runRecovery(s,r,i);if(o)return nt&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((a,l)=>l.score-a.score);i.length>o;)i.pop();i.some(a=>a.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&c.buffer.length>500)if((a.score-c.score||a.buffer.length-c.buffer.length)>0)i.splice(l--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,a)=>a.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&s>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let c=e.curContext&&e.curContext.tracker.strict,h=c?e.curContext.hash:0;for(let u=this.fragments.nodeAt(s);u;){let f=this.parser.nodeSet.types[u.type.id]==u.type?r.getGoto(e.state,u.type.id):-1;if(f>-1&&u.length&&(!c||(u.prop(_.contextHash)||0)==h))return e.useNode(u,f),nt&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(u.type.id)})`),!0;if(!(u instanceof ke)||u.children.length==0||u.positions[0]>0)break;let d=u.children[0];if(d instanceof ke&&u.positions[0]==0)u=d;else break}}let a=r.stateSlot(e.state,4);if(a>0)return e.reduce(a),nt&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(a&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let l=this.tokens.getActions(e);for(let c=0;cs?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return Hc(e,t),!0}}runRecovery(e,t,i){let s=null,r=!1;for(let o=0;o ":"";if(a.deadEnd&&(r||(r=!0,a.restart(),nt&&console.log(h+this.stackID(a)+" (restarted)"),this.advanceFully(a,i))))continue;let u=a.split(),f=h;for(let d=0;d<10&&u.forceReduce()&&(nt&&console.log(f+this.stackID(u)+" (via force-reduce)"),!this.advanceFully(u,i));d++)nt&&(f=this.stackID(u)+" -> ");for(let d of a.recoverByInsert(l))nt&&console.log(h+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>a.pos?(c==a.pos&&(c++,l=0),a.recoverByDelete(l,c),nt&&console.log(h+this.stackID(a)+` (via recover-delete ${this.parser.getName(l)})`),Hc(a,i)):(!s||s.scoren;class UA{constructor(e){this.start=e.start,this.shift=e.shift||oo,this.reduce=e.reduce||oo,this.reuse=e.reuse||oo,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Js extends _u{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let a=0;ae.topRules[a][1]),s=[];for(let a=0;a=0)r(h,l,a[c++]);else{let u=a[c+-h];for(let f=-h;f>0;f--)r(a[c++],l,u);c++}}}this.nodeSet=new Ka(t.map((a,l)=>et.define({name:l>=this.minRepeatTerm?void 0:a,id:l,props:s[l],top:i.indexOf(l)>-1,error:l==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(l)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=Yu;let o=dn(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let a=0;atypeof a=="number"?new Di(o,a):a),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let s=new MA(this,e,t,i);for(let r of this.wrappers)s=r(s,e,t,i);return s}getGoto(e,t,i=!1){let s=this.goto;if(t>=s[0])return-1;for(let r=s[t+1];;){let o=s[r++],a=o&1,l=s[r++];if(a&&i)return l;for(let c=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),s=i?t(i):void 0;for(let r=this.stateSlot(e,1);s==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=Dt(this.data,r+2);else break;s=t(Dt(this.data,r+1))}return s}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=Dt(this.data,i+2);else break;if((this.data[i+2]&1)==0){let s=this.data[i+1];t.some((r,o)=>o&1&&r==s)||t.push(this.data[i],s)}}return t}configure(e){let t=Object.assign(Object.create(Js.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let s=e.tokenizers.find(r=>r.from==i);return s?s.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,s)=>{let r=e.specializers.find(a=>a.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[s]=Gc(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let s=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scoren.external(t,i)<<1|e}return n.get}const DA=316,LA=317,_c=1,XA=2,BA=3,IA=4,WA=318,qA=320,zA=321,VA=5,jA=6,YA=0,aa=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],cd=125,NA=59,la=47,HA=42,GA=43,_A=45,JA=60,eb=44,tb=63,ib=46,nb=91,sb=new UA({start:!1,shift(n,e){return e==VA||e==jA||e==qA?n:e==zA},strict:!1}),rb=new qn((n,e)=>{let{next:t}=n;(t==cd||t==-1||e.context)&&n.acceptToken(WA)},{contextual:!0,fallback:!0}),ob=new qn((n,e)=>{let{next:t}=n,i;aa.indexOf(t)>-1||t==la&&((i=n.peek(1))==la||i==HA)||t!=cd&&t!=NA&&t!=-1&&!e.context&&n.acceptToken(DA)},{contextual:!0}),ab=new qn((n,e)=>{n.next==nb&&!e.context&&n.acceptToken(LA)},{contextual:!0}),lb=new qn((n,e)=>{let{next:t}=n;if(t==GA||t==_A){if(n.advance(),t==n.next){n.advance();let i=!e.context&&e.canShift(_c);n.acceptToken(i?_c:XA)}}else t==tb&&n.peek(1)==ib&&(n.advance(),n.advance(),(n.next<48||n.next>57)&&n.acceptToken(BA))},{contextual:!0});function ao(n,e){return n>=65&&n<=90||n>=97&&n<=122||n==95||n>=192||!e&&n>=48&&n<=57}const cb=new qn((n,e)=>{if(n.next!=JA||!e.dialectEnabled(YA)||(n.advance(),n.next==la))return;let t=0;for(;aa.indexOf(n.next)>-1;)n.advance(),t++;if(ao(n.next,!0)){for(n.advance(),t++;ao(n.next,!1);)n.advance(),t++;for(;aa.indexOf(n.next)>-1;)n.advance(),t++;if(n.next==eb)return;for(let i=0;;i++){if(i==7){if(!ao(n.next,!0))return;break}if(n.next!="extends".charCodeAt(i))break;n.advance(),t++}}n.acceptToken(IA,-t)}),hb=Ju({"get set async static":O.modifier,"for while do if else switch try catch finally return throw break continue default case defer":O.controlKeyword,"in of await yield void typeof delete instanceof as satisfies":O.operatorKeyword,"let var const using function class extends":O.definitionKeyword,"import export from":O.moduleKeyword,"with debugger new":O.keyword,TemplateString:O.special(O.string),super:O.atom,BooleanLiteral:O.bool,this:O.self,null:O.null,Star:O.modifier,VariableName:O.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":O.function(O.variableName),VariableDefinition:O.definition(O.variableName),Label:O.labelName,PropertyName:O.propertyName,PrivatePropertyName:O.special(O.propertyName),"CallExpression/MemberExpression/PropertyName":O.function(O.propertyName),"FunctionDeclaration/VariableDefinition":O.function(O.definition(O.variableName)),"ClassDeclaration/VariableDefinition":O.definition(O.className),"NewExpression/VariableName":O.className,PropertyDefinition:O.definition(O.propertyName),PrivatePropertyDefinition:O.definition(O.special(O.propertyName)),UpdateOp:O.updateOperator,"LineComment Hashbang":O.lineComment,BlockComment:O.blockComment,Number:O.number,String:O.string,Escape:O.escape,ArithOp:O.arithmeticOperator,LogicOp:O.logicOperator,BitOp:O.bitwiseOperator,CompareOp:O.compareOperator,RegExp:O.regexp,Equals:O.definitionOperator,Arrow:O.function(O.punctuation),": Spread":O.punctuation,"( )":O.paren,"[ ]":O.squareBracket,"{ }":O.brace,"InterpolationStart InterpolationEnd":O.special(O.brace),".":O.derefOperator,", ;":O.separator,"@":O.meta,TypeName:O.typeName,TypeDefinition:O.definition(O.typeName),"type enum interface implements namespace module declare":O.definitionKeyword,"abstract global Privacy readonly override":O.modifier,"is keyof unique infer asserts":O.operatorKeyword,JSXAttributeValue:O.attributeValue,JSXText:O.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":O.angleBracket,"JSXIdentifier JSXNameSpacedName":O.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":O.attributeName,"JSXBuiltin/JSXIdentifier":O.standard(O.tagName)}),ub={__proto__:null,export:20,as:25,from:33,default:36,async:41,function:42,in:52,out:55,const:56,extends:60,this:64,true:72,false:72,null:84,void:88,typeof:92,super:108,new:142,delete:154,yield:163,await:167,class:172,public:235,private:235,protected:235,readonly:237,instanceof:256,satisfies:259,import:292,keyof:349,unique:353,infer:359,asserts:395,is:397,abstract:417,implements:419,type:421,let:424,var:426,using:429,interface:435,enum:439,namespace:445,module:447,declare:451,global:455,defer:471,for:476,of:485,while:488,with:492,do:496,if:500,else:502,switch:506,case:512,try:518,catch:522,finally:526,return:530,throw:534,break:538,continue:542,debugger:546},fb={__proto__:null,async:129,get:131,set:133,declare:195,public:197,private:197,protected:197,static:199,abstract:201,override:203,readonly:209,accessor:211,new:401},db={__proto__:null,"<":193},pb=Js.deserialize({version:14,states:"$F|Q%TQlOOO%[QlOOO'_QpOOP(lO`OOO*zQ!0MxO'#CiO+RO#tO'#CjO+aO&jO'#CjO+oO#@ItO'#DaO.QQlO'#DgO.bQlO'#DrO%[QlO'#DzO0fQlO'#ESOOQ!0Lf'#E['#E[O1PQ`O'#EXOOQO'#Ep'#EpOOQO'#Il'#IlO1XQ`O'#GsO1dQ`O'#EoO1iQ`O'#EoO3hQ!0MxO'#JrO6[Q!0MxO'#JsO6uQ`O'#F]O6zQ,UO'#FtOOQ!0Lf'#Ff'#FfO7VO7dO'#FfO9XQMhO'#F|O9`Q`O'#F{OOQ!0Lf'#Js'#JsOOQ!0Lb'#Jr'#JrO9eQ`O'#GwOOQ['#K_'#K_O9pQ`O'#IYO9uQ!0LrO'#IZOOQ['#J`'#J`OOQ['#I_'#I_Q`QlOOQ`QlOOO9}Q!L^O'#DvO:UQlO'#EOO:]QlO'#EQO9kQ`O'#GsO:dQMhO'#CoO:rQ`O'#EnO:}Q`O'#EyO;hQMhO'#FeO;xQ`O'#GsOOQO'#K`'#K`O;}Q`O'#K`O<]Q`O'#G{O<]Q`O'#G|O<]Q`O'#HOO9kQ`O'#HRO=SQ`O'#HUO>kQ`O'#CeO>{Q`O'#HcO?TQ`O'#HiO?TQ`O'#HkO`QlO'#HmO?TQ`O'#HoO?TQ`O'#HrO?YQ`O'#HxO?_Q!0LsO'#IOO%[QlO'#IQO?jQ!0LsO'#ISO?uQ!0LsO'#IUO9uQ!0LrO'#IWO@QQ!0MxO'#CiOASQpO'#DlQOQ`OOO%[QlO'#EQOAjQ`O'#ETO:dQMhO'#EnOAuQ`O'#EnOBQQ!bO'#FeOOQ['#Cg'#CgOOQ!0Lb'#Dq'#DqOOQ!0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%Ui%V>PR0f*yQ$viS(u#v+iS)c$b$cQ)e$dQ*[$xS*e${*YQ*t%OQ*u%QQ+Q%^Q+R%_Q+V%cQ.lPQ=}>XQ>O>YQ>Z>]R>[>^Q+O%]Q.nSR#[WR'Z!el!tQ!r!v!y!z'`'l'm'n-e-u1o5{5}S'V!e-]U*j$|*Z*oS-Y'W'_S0U*k*qQ0^*rQ2u-cQ4v0[R4{0_R({#xQ!fQT-d'`-e]!qQ!r'`-e1o5{Q#p]R'i < TypeParamList in out const TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewTarget new NewExpression ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression TypeArgList CompareOp < declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression InstantiationExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast < ArrowFunction TypeParamList SequenceExpression InstantiationExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate asserts is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration defer ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:380,context:sb,nodeProps:[["isolate",-8,5,6,14,37,39,51,53,55,""],["group",-26,9,17,19,68,207,211,215,216,218,221,224,234,237,243,245,247,249,252,258,264,266,268,270,272,274,275,"Statement",-34,13,14,32,35,36,42,51,54,55,57,62,70,72,76,80,82,84,85,110,111,120,121,136,139,141,142,143,144,145,147,148,167,169,171,"Expression",-23,31,33,37,41,43,45,173,175,177,178,180,181,182,184,185,186,188,189,190,201,203,205,206,"Type",-3,88,103,109,"ClassItem"],["openedBy",23,"<",38,"InterpolationStart",56,"[",60,"{",73,"(",160,"JSXStartCloseTag"],["closedBy",-2,24,168,">",40,"InterpolationEnd",50,"]",61,"}",74,")",165,"JSXEndTag"]],propSources:[hb],skippedNodes:[0,5,6,278],repeatNodeCount:37,tokenData:"$Fq07[R!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#:O!R![#<_![!]#I_!]!^#Jk!^!_#Ku!_!`$![!`!a$$v!a!b$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new oa("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOx~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!U~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(c~~",141,340),new oa("j~RQYZXz{^~^O(Q~~aP!P!Qd~iO(R~~",25,323)],topRules:{Script:[0,7],SingleExpression:[1,276],SingleClassItem:[2,277]},dialects:{jsx:0,ts:15175},dynamicPrecedences:{80:1,82:1,94:1,169:1,199:1},specialized:[{term:327,get:n=>ub[n]||-1},{term:343,get:n=>fb[n]||-1},{term:95,get:n=>db[n]||-1}],tokenPrec:15201}),hd=[Ye("function ${name}(${params}) {\n ${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ye("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n ${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ye("for (let ${name} of ${collection}) {\n ${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ye("do {\n ${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ye("while (${}) {\n ${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ye(`try { \${} } catch (\${error}) { \${} @@ -20,12 +20,19 @@ constructor(\${params}) { \${} } -}`,{label:"class",detail:"definition",type:"keyword"}),Ye('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ye('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],hb=od.concat([Ye("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Ye("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Ye("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Hc=new dO,ad=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const ub=["FunctionDeclaration"],fb={FunctionDeclaration:cn("function"),ClassDeclaration:cn("class"),ClassExpression:()=>!0,EnumDeclaration:cn("constant"),TypeAliasDeclaration:cn("type"),NamespaceDeclaration:cn("namespace"),VariableDefinition(n,e){n.matchContext(ub)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function ld(n,e){let t=Hc.get(e);if(t)return t;let i=[],s=!0;function r(o,a){let l=n.sliceString(o.from,o.to);i.push({label:l,type:a})}return e.cursor(be.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let a=fb[o.name];if(a&&a(o,r)||ad.has(o.name))return!1}else if(o.to-o.from>8192){for(let a of ld(n,o.node))i.push(a);return!1}}),Hc.set(e,i),i}const Gc=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,cd=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function db(n){let e=Ce(n.state).resolveInner(n.pos,-1);if(cd.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&Gc.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)ad.has(s.name)&&(i=i.concat(ld(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:Gc}}const Xt=Xs.define({name:"javascript",parser:cb.configure({props:[ef.add({IfStatement:Nr({except:/^\s*({|else\b)/}),TryStatement:Nr({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:MO,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:ZO({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Nr({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),sf.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":DO,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),hd={test:n=>/^JSX/.test(n.name),facet:_u({commentTokens:{block:{open:"{/*",close:"*/}"}}})},pb=Xt.configure({dialect:"ts"},"typescript"),mb=Xt.configure({dialect:"jsx",props:[Za.add(n=>n.isTop?[hd]:void 0)]}),gb=Xt.configure({dialect:"jsx ts",props:[Za.add(n=>n.isTop?[hd]:void 0)]},"typescript");let ud=n=>({label:n,type:"keyword"});const fd="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(ud),Ob=fd.concat(["declare","implements","private","protected","public"].map(ud));function yb(n={}){let e=n.jsx?n.typescript?gb:mb:n.typescript?pb:Xt,t=n.typescript?hb.concat(Ob):od.concat(fd);return new kO(e,[Xt.data.of({autocomplete:Ty(cd,Yf(t))}),Xt.data.of({autocomplete:db}),n.jsx?Sb:[]])}function Ab(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function _c(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const bb=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Sb=$.inputHandler.of((n,e,t,i,s)=>{if((bb?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!Xt.isActiveAt(n.state,e,-1))return!1;let r=s(),{state:o}=r,a=o.changeByRange(l=>{var c;let{head:h}=l,u=Ce(o).resolveInner(h-1,-1),f;if(u.name=="JSXStartTag"&&(u=u.parent),!(o.doc.sliceString(h-1,h)!=i||u.name=="JSXAttributeValue"&&u.to>h)){if(i==">"&&u.name=="JSXFragmentTag")return{range:l,changes:{from:h,insert:""}};if(i=="/"&&u.name=="JSXStartCloseTag"){let d=u.parent,p=d.parent;if(p&&d.from==h-2&&((f=_c(o.doc,p.firstChild,h))||((c=p.firstChild)===null||c===void 0?void 0:c.name)=="JSXFragmentTag")){let m=`${f}>`;return{range:A.cursor(h+m.length,-1),changes:{from:h,insert:m}}}}else if(i==">"){let d=Ab(u);if(d&&d.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(h,h+2))&&(f=_c(o.doc,d,h)))return{range:l,changes:{from:h,insert:``}}}}return{range:l}});return a.changes.empty?!1:(n.dispatch([r,o.update(a,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),Jc=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n;class Yi{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?a=>r(Jc(a)):Jc,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Ne(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=fa(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Qt(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,a=!0;;r++){let l=s.charCodeAt(r),c=this.match(l,o,a,this.bufferPos+this.bufferStart,r==s.length-1);if(c)return this.value=c,this;if(r==s.length-1)break;a&&rthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=_s(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||s.to<=t){let a=new Li(t,e.sliceString(t,i));return oo.set(e,a),a}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=_s(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Li.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(pd.prototype[Symbol.iterator]=md.prototype[Symbol.iterator]=function(){return this});function xb(n){try{return new RegExp(n,Na),!0}catch{return!1}}function _s(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}const vb=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=jg(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,h,u]=o,f=h?+h.slice(1):0,d=c?+c:a.number;if(c&&u){let g=d/100;l&&(g=g*(l=="-"?-1:1)+a.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else c&&l&&(d=d*(l=="-"?-1:1)+a.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),m=A.cursor(p.from+Math.max(0,Math.min(f,p.length)));n.dispatch({effects:[i,$.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},wb={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},kb=K.define({combine(n){return yt(n,wb,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function Qb(n){return[$b,Rb]}const Pb=B.mark({class:"cm-selectionMatch"}),Cb=B.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function eh(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=ye.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=ye.Word)}function Tb(n,e,t,i){return n(e.sliceDoc(t,t+1))==ye.Word&&n(e.sliceDoc(i-1,i))==ye.Word}const Rb=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(kb),{state:t}=n,i=t.selection;if(i.ranges.length>1)return B.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return B.none;let l=t.wordAt(s.head);if(!l)return B.none;o=t.charCategorizer(s.head),r=t.sliceDoc(l.from,l.to)}else{let l=s.to-s.from;if(l200)return B.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(eh(o,t,s.from,s.to)&&Tb(o,t,s.from,s.to)))return B.none}else if(r=t.sliceDoc(s.from,s.to),!r)return B.none}let a=[];for(let l of n.visibleRanges){let c=new Yi(t.doc,r,l.from,l.to);for(;!c.next().done;){let{from:h,to:u}=c.value;if((!o||eh(o,t,h,u))&&(s.empty&&h<=s.from&&u>=s.to?a.push(Cb.range(h,u)):(h>=s.to||u<=s.from)&&a.push(Pb.range(h,u)),a.length>e.maxMatches))return B.none}}return B.set(a)}},{decorations:n=>n.decorations}),$b=$.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Kb=({state:n,dispatch:e})=>{let{selection:t}=n,i=A.create(t.ranges.map(s=>n.wordAt(s.head)||A.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function Zb(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,a=new Yi(n.doc,e,i[i.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new Yi(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(l=>l.from==a.value.from))continue;if(r){let l=n.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const Mb=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return Kb({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=Zb(n,i);return s?(e(n.update({selection:n.selection.addRange(A.range(s.from,s.to),!1),effects:$.scrollIntoView(s.to)})),!0):!1},tn=K.define({combine(n){return yt(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Yb(e),scrollToMatch:e=>$.scrollIntoView(e)})}});class gd{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||xb(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` -`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new Xb(this):new Fb(this)}getCursor(e,t=0,i){let s=e.doc?e:_.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Pi(this,s,t,i):Qi(this,s,t,i)}}class Od{constructor(e){this.spec=e}}function Eb(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let a=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(a,e,i,s)}}function Qi(n,e,t,i){let s;return n.wholeWord&&(s=Ub(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=Eb(n.test,e,s)),new Yi(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function Ub(n,e){return(t,i,s,r)=>((r>t||r+s.length=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Qi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}function Db(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Pi(n,e,t,i){let s;return n.wholeWord&&(s=Lb(e.charCategorizer(e.selection.main.head))),n.test&&(s=Db(n.test,e,s)),new pd(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function Js(n,e){return n.slice(Ze(n,e,!1),e)}function er(n,e){return n.slice(e,Ze(n,e))}function Lb(n){return(e,t,i)=>!i[0].length||(n(Js(i.input,i.index))!=ye.Word||n(er(i.input,i.index))!=ye.Word)&&(n(er(i.input,i.index+i[0].length))!=ye.Word||n(Js(i.input,i.index+i[0].length))!=ye.Word)}class Xb extends Od{nextMatch(e,t,i){let s=Pi(this.spec,e,i,e.doc.length).next();return s.done&&(s=Pi(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Pi(this.spec,e,r,i),a=null;for(;!o.next().done;)a=o.value;if(a&&(r==t||a.from>r+10))return a;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Pi(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}const Zn=z.define(),Ha=z.define(),Gt=Te.define({create(n){return new ao(aa(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Zn)?n=new ao(t.value.create(),n.panel):t.is(Ha)&&(n=new ao(n.query,t.value?Ga:null));return n},provide:n=>Vi.from(n,e=>e.panel)});class ao{constructor(e,t){this.query=e,this.panel=t}}const Bb=B.mark({class:"cm-searchMatch"}),Ib=B.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Wb=xe.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(Gt))}update(n){let e=n.state.field(Gt);(e!=n.startState.field(Gt)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return B.none;let{view:t}=this,i=new Bt;for(let s=0,r=t.visibleRanges,o=r.length;sr[s+1].from-500;)l=r[++s].to;n.highlight(t.state,a,l,(c,h)=>{let u=t.state.selection.ranges.some(f=>f.from==c&&f.to==h);i.add(c,h,u?Ib:Bb)})}return i.finish()}},{decorations:n=>n.decorations});function qn(n){return e=>{let t=e.state.field(Gt,!1);return t&&t.query.spec.valid?n(e,t):bd(e)}}const tr=qn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=A.single(i.from,i.to),r=n.state.facet(tn);return n.dispatch({selection:s,effects:[_a(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),Ad(n),!0}),ir=qn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=A.single(s.from,s.to),o=n.state.facet(tn);return n.dispatch({selection:r,effects:[_a(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),Ad(n),!0}),qb=qn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:A.create(t.map(i=>A.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),zb=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let a=new Yi(n.doc,n.sliceDoc(i,s));!a.next().done;){if(r.length>1e3)return!1;a.value.from==i&&(o=r.length),r.push(A.range(a.value.from,a.value.to))}return e(n.update({selection:A.create(r,o),userEvent:"select.search.matches"})),!0},th=qn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,a=[],l,c,h=[];o.precise?o.from==i&&o.to==s&&(c=t.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(t,o.from,o.to),h.push($.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let u=n.state.changes(a);return o&&(l=A.single(o.from,o.to).map(u),h.push(_a(n,o)),h.push(t.facet(tn).scrollToMatch(l.main,n))),n.dispatch({changes:u,selection:l,effects:h,userEvent:"input.replace"}),!0}),Vb=qn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:a}=s;a&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:$.announce.of(i),userEvent:"input.replace.all"}),!0});function Ga(n){return n.state.facet(tn).createPanel(n)}function aa(n,e){var t,i,s,r,o;let a=n.selection.main,l=a.empty||a.to>a.from+100?"":n.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=n.facet(tn);return new gd({search:((t=e?.literal)!==null&&t!==void 0?t:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:c.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:c.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:c.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function yd(n){let e=Fu(n,Ga);return e&&e.dom.querySelector("[main-field]")}function Ad(n){let e=yd(n);e&&e==n.root.activeElement&&e.select()}const bd=n=>{let e=n.state.field(Gt,!1);if(e&&e.panel){let t=yd(n);if(t&&t!=n.root.activeElement){let i=aa(n.state,e.query.spec);i.valid&&n.dispatch({effects:Zn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Ha.of(!0),e?Zn.of(aa(n.state,e.query.spec)):z.appendConfig.of(Hb)]});return!0},Sd=n=>{let e=n.state.field(Gt,!1);if(!e||!e.panel)return!1;let t=Fu(n,Ga);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Ha.of(!1)}),!0},jb=[{key:"Mod-f",run:bd,scope:"editor search-panel"},{key:"F3",run:tr,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:tr,shift:ir,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Sd,scope:"editor search-panel"},{key:"Mod-Shift-l",run:zb},{key:"Mod-Alt-g",run:vb},{key:"Mod-d",run:Mb,preventDefault:!0}];class Yb{constructor(e){this.view=e;let t=this.query=e.state.field(Gt).query.spec;this.commit=this.commit.bind(this),this.searchField=he("input",{value:t.search,placeholder:st(e,"Find"),"aria-label":st(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=he("input",{value:t.replace,placeholder:st(e,"Replace"),"aria-label":st(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=he("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=he("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=he("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return he("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=he("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>tr(e),[st(e,"next")]),i("prev",()=>ir(e),[st(e,"previous")]),i("select",()=>qb(e),[st(e,"all")]),he("label",null,[this.caseField,st(e,"match case")]),he("label",null,[this.reField,st(e,"regexp")]),he("label",null,[this.wordField,st(e,"by word")]),...e.state.readOnly?[]:[he("br"),this.replaceField,i("replace",()=>th(e),[st(e,"replace")]),i("replaceAll",()=>Vb(e),[st(e,"replace all")])],he("button",{name:"close",onclick:()=>Sd(e),"aria-label":st(e,"close"),type:"button"},["×"])])}commit(){let e=new gd({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Zn.of(e)}))}keydown(e){sg(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?ir:tr)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),th(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Zn)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(tn).top}}function st(n,e){return n.state.phrase(e)}const fs=30,ds=/[\s\.,:;?!]/;function _a(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-fs),o=Math.min(s,t+fs),a=n.state.sliceDoc(r,o);if(r!=i.from){for(let l=0;la.length-fs;l--)if(!ds.test(a[l-1])&&ds.test(a[l])){a=a.slice(0,l);break}}return $.announce.of(`${n.state.phrase("current match")}. ${a} ${n.state.phrase("on line")} ${i.number}.`)}const Nb=$.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),Hb=[Gt,ri.low(Wb),Nb];class ih{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class di{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(Kt).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new Bt,a=[],l=0,c=i.doc.iter(),h=0,u=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!a.length)break;let m,g;if(a.length)m=l,g=a.reduce((x,C)=>Math.min(x,C.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>u)break;g=p.to,a.push(p),d++}for(;dx.from||x.to==m))a.push(x),d++,g=Math.min(x.to,g);else{g=Math.min(x.from,g);break}}g=Math.min(g,u);let y=!1;if(a.some(x=>x.from==m&&(x.to==g||g==u))&&(y=m==g,!y&&g-m<10)){let x=m-(h+c.value.length);x>0&&(c.next(x),h=m);for(let C=m;;){if(C>=g){y=!0;break}if(!c.lineBreak&&h+c.value.length>C)break;C=h+c.value.length,h+=c.value.length,c.next()}}let b=Td(a);if(y)o.add(m,m,B.widget({widget:new nS(b),diagnostics:a.slice()}));else{let x=a.reduce((C,k)=>k.markClass?C+" "+k.markClass:C,"");o.add(m,g,B.mark({class:"cm-lintRange cm-lintRange-"+b+x,diagnostics:a.slice(),inclusiveEnd:a.some(C=>C.to>g)}))}if(l=g,l==u)break;for(let x=0;x{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new ih(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new ih(i.from,r,i.diagnostic)}}),i}function xd(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(Kt).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(Qr))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function Gb(n,e){return n.field(gt,!1)?e:e.concat(z.appendConfig.of(Kd))}function vd(n,e){return{effects:Gb(n,[Qr.of(e)])}}const Qr=z.define(),wd=z.define(),kd=z.define(),gt=Te.define({create(){return new di(B.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Ni(t,n.selected.diagnostic,r)||Ni(t,null,r)}!t.size&&s&&e.state.facet(Kt).autoPanel&&(s=null),n=new di(t,s,i)}for(let t of e.effects)if(t.is(Qr)){let i=e.state.facet(Kt).autoPanel?t.value.length?nr.open:null:n.panel;n=di.init(t.value,i,e.state)}else t.is(wd)?n=new di(n.diagnostics,t.value?nr.open:null,n.selected):t.is(kd)&&(n=new di(n.diagnostics,n.panel,t.value));return n},provide:n=>[Vi.from(n,e=>e.panel),$.decorations.from(n,e=>e.diagnostics)]}),_b=B.mark({class:"cm-lintRange cm-lintRange-active"});function Jb(n,e,t){let{diagnostics:i}=n.state.field(gt),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(l,c,{spec:h})=>{if(e>=l&&e<=c&&(l==c||(e>l||t>0)&&(eCd(n,t,!1)))}const nh=n=>{let e=n.state.field(gt,!1);return!e||!e.panel?!1:(n.dispatch({effects:wd.of(!1)}),!0)},eS=xe.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(Kt);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){clearTimeout(this.timeout);let n=Date.now();if(nPromise.resolve(i(this.view))),i=>{this.view.state.doc==e.doc&&this.view.dispatch(vd(this.view.state,i.reduce((s,r)=>s.concat(r))))},i=>{ze(this.view.state,i)})}}update(n){let e=n.state.facet(Kt);(n.docChanged||e!=n.startState.facet(Kt)||e.needsRefresh&&e.needsRefresh(n))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}});function tS(n,e,t){let i=[],s=-1;for(let r of n)r.then(o=>{i.push(o),clearTimeout(s),i.length==n.length?e(i):s=setTimeout(()=>e(i),200)},t)}const Kt=K.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...yt(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:sh,tooltipFilter:sh,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function sh(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function iS(n,e={}){return[Kt.of({source:n,config:e}),eS,Kd]}function Pd(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;ir.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function Cd(n,e,t){var i;let s=t?Pd(e.actions):[];return he("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},he("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let a=!1,l=d=>{if(d.preventDefault(),a)return;a=!0;let p=Ni(n.state.field(gt).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:c}=r,h=s[o]?c.indexOf(s[o]):-1,u=h<0?c:[c.slice(0,h),he("u",c.slice(h,h+1)),c.slice(h+1)],f=r.markClass?" "+r.markClass:"";return he("button",{type:"button",class:"cm-diagnosticAction"+f,onclick:l,onmousedown:l,"aria-label":` Action: ${c}${h<0?"":` (access key "${s[o]})"`}.`},u)}),e.source&&he("div",{class:"cm-diagnosticSource"},e.source))}class nS extends Ut{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return he("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class rh{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Cd(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class nr{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)nh(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=Pd(r.actions);for(let a=0;a{for(let r=0;rnh(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(gt).selected;if(!e)return-1;for(let t=0;t{for(let h of c.diagnostics){if(o.has(h))continue;o.add(h);let u=-1,f;for(let d=i;di&&(this.items.splice(i,u-i),s=!0)),t&&f.diagnostic==t.diagnostic?f.dom.hasAttribute("aria-selected")||(f.dom.setAttribute("aria-selected","true"),r=f):f.dom.hasAttribute("aria-selected")&&f.dom.removeAttribute("aria-selected"),i++}});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:a,panel:l})=>{let c=l.height/this.list.offsetHeight;a.topl.bottom&&(this.list.scrollTop+=(a.bottom-l.bottom)/c)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(gt),i=Ni(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:kd.of(i)})}static open(e){return new nr(e)}}function Qs(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function ps(n){return Qs(``,'width="6" height="3"')}const sS=$.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:ps("#f11")},".cm-lintRange-warning":{backgroundImage:ps("orange")},".cm-lintRange-info":{backgroundImage:ps("#999")},".cm-lintRange-hint":{backgroundImage:ps("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function rS(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function Td(n){let e="hint",t=1;for(let i of n){let s=rS(i.severity);s>t&&(t=s,e=i.severity)}return e}class Rd extends Mt{constructor(e){super(),this.diagnostics=e,this.severity=Td(e)}toDOM(e){let t=document.createElement("div");t.className="cm-lint-marker cm-lint-marker-"+this.severity;let i=this.diagnostics,s=e.state.facet(Pr).tooltipFilter;return s&&(i=s(i,e.state)),i.length&&(t.onmouseover=()=>aS(e,t,i)),t}}function oS(n,e){let t=i=>{let s=e.getBoundingClientRect();if(!(i.clientX>s.left-10&&i.clientXs.top-10&&i.clientYe.getBoundingClientRect()}}})}),e.onmouseout=e.onmousemove=null,oS(n,e)}let{hoverTime:s}=n.state.facet(Pr),r=setTimeout(i,s);e.onmouseout=()=>{clearTimeout(r),e.onmouseout=e.onmousemove=null},e.onmousemove=()=>{clearTimeout(r),r=setTimeout(i,s)}}function lS(n,e){let t=Object.create(null);for(let s of e){let r=n.lineAt(s.from);(t[r.from]||(t[r.from]=[])).push(s)}let i=[];for(let s in t)i.push(new Rd(t[s]).range(+s));return N.of(i,!0)}const cS=Bu({class:"cm-gutter-lint",markers:n=>n.state.field(la),widgetMarker:(n,e,t)=>{let i=[];return n.state.field(la).between(t.from,t.to,(s,r,o)=>{s>t.from&&si.is(Ja)?i.value:t,n)},provide:n=>gr.from(n)}),hS=$.baseTheme({".cm-gutter-lint":{width:"1.4em","& .cm-gutterElement":{padding:".2em"}},".cm-lint-marker":{width:"1em",height:"1em"},".cm-lint-marker-info":{content:Qs('')},".cm-lint-marker-warning":{content:Qs('')},".cm-lint-marker-error":{content:Qs('')}}),uS=Eu(Jb,{hideOn:xd}),Kd=[gt,$.decorations.compute([gt],n=>{let{selected:e,panel:t}=n.field(gt);return!e||!t||e.from==e.to?B.none:B.set([_b.range(e.from,e.to)])}),uS,sS],Pr=K.define({combine(n){return yt(n,{hoverTime:300,markerFilter:null,tooltipFilter:null})}});function fS(n={}){return[Pr.of(n),la,cS,hS,$d]}const Zd=1,Ue=Object.freeze({ready:"studio.ready",documentOpen:"document.open",documentReplace:"document.replace",documentChanged:"document.changed",documentSave:"document.save",documentSetReadOnly:"document.setReadOnly",documentResources:"document.resources",editorInsert:"editor.insert",editorFormat:"editor.format",editorSetTheme:"editor.setTheme",editorGetState:"editor.getState",diagnosticsPublish:"diagnostics.publish"});function dS(n,e={},t=null,i=null){return{protocolVersion:Zd,type:n,documentID:t,...i===null?{}:{sessionID:i},payload:e}}function pS(n){if(window.WKWebViewJavascriptBridge){n(window.WKWebViewJavascriptBridge);return}if(window.WKWVJBCallbacks){window.WKWVJBCallbacks.push(n);return}window.webkit?.messageHandlers?.iOS_Native_InjectJavascript&&(window.WKWVJBCallbacks=[n],window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null))}function nn(n,e,t={},i=null,s=()=>{},r=null){if(!n){s({result:"unavailable"});return}n.callHandler(e,dS(e,t,i,r),s)}function mS(n){const e={capabilities:["jsx","format","search","completion","diagnostics"]};nn(n,Ue.ready,e)}const gS=[{id:"$storage.getString",arguments:["key"],returns:"string",documentation:"Read a package-scoped string. Missing keys return an empty string."},{id:"$storage.setString",arguments:["key","value"],returns:"boolean",documentation:"Set a package-scoped string, limited to 256 KiB of UTF-8. Check the success result."},{id:"$storage.getJSON",arguments:["key"],returns:"json",documentation:"Read a package-scoped JSON object. Missing or invalid values return an empty object."},{id:"$storage.setJSON",arguments:["key","value"],returns:"boolean",documentation:"Store a valid JSON object, limited to 256 KiB encoded. Check the success result."},{id:"$storage.compareAndSetString",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a string only when it still matches expected. A missing key matches an empty string. Conflicts return false; reread and retry a bounded number of times. Requires the shared storage container."},{id:"$storage.compareAndSetJSON",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a JSON object if its current value equals expected, independent of property order. A missing key matches an empty object. Wrong types and conflicts return false. Requires the shared storage container."},{id:"$storage.remove",arguments:["key"],returns:"boolean",documentation:"Remove a key from this package only."},{id:"$storage.keys",arguments:[],returns:"string[]",documentation:"List keys in this package's namespace."},{id:"$storage.clear",arguments:[],returns:"boolean",documentation:"Clear this package's storage. Other packages are unaffected."}].map(n=>({minimumRuntimeVersion:"1.0",...n,preview:"initialState"})),OS=[{id:"$notifications.status",group:"notifications",value:{authorization:"authorized"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.pending",group:"notifications",value:[],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.schedule",group:"notifications",value:{key:"daily",status:"scheduled"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$notifications.cancel",group:"notifications",value:{key:"daily",status:"cancellationRequested"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$health.dailyStatistics",group:"health",value:{metric:"steps",unit:"count",aggregation:"sum",timeZone:"UTC",items:[{date:"2026-01-01",value:6840,hasSamples:!0}]},platforms:["ios"],authorization:"healthRead",notes:"Runtime 1.6. Read-only daily HealthKit statistics on installed iPhone/iPad widgets. Declare health and minimumRuntimeVersion 1.6, review Health access in native Settings. No separate System Access toggle. Missing readings are null/hasSamples false and cannot establish read denial. No raw samples, persistence or queries in future/Live Activity presentations. Preview fixtures never access real Health data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHealth.swift",operation:"read",mock:"editable"},{id:"$calendar.create",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$calendar.update",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$weather.forecast",group:"weather",value:{provider:"MET Norway",attribution:{text:"Weather data from MET Norway",url:"https://www.met.no/en/free-meteorological-data/Download-services"},latitude:37.33,longitude:-122.01,fetchedAt:"2026-01-01T12:00:00Z",isStale:!1,hours:[{time:"2026-01-01T12:00:00Z",temperatureC:21,windMetersPerSecond:2,precipitationMM:0,condition:"partlycloudy_day"}]},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeWeather.swift",operation:"read",mock:"editable"},{id:"$alarms.status",group:"alarms",value:{authorization:"authorized"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.pending",group:"alarms",value:[],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.schedule",group:"alarms",value:{key:"focus",status:"scheduled",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.cancel",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.stop",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.pause",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.resume",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$documents.list",group:"documents",value:[{id:"550e8400-e29b-41d4-a716-446655440000",name:"Sample.json",type:"json",bytes:17},{id:"550e8400-e29b-41d4-a716-446655440001",name:"Sample.csv",type:"csv",bytes:24}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readJSON",group:"documents",value:{goal:12,done:7},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readCSV",group:"documents",value:{headers:["day","value"],rows:[["Monday","7"],["Tuesday","9"]],truncated:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$contacts.selected",group:"contacts",value:[{id:"sample.contact",name:"Alex Example",organization:"Sample",phones:["+1 202 555 0100"],emails:["alex@example.com"]}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeContacts.swift",operation:"read",mock:"editable"},{id:"$maps.search",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.geocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["address"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.reverseGeocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.snapshot",group:"maps",value:{image:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",width:256,height:256,provider:"Apple Maps"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$home.items",group:"home",value:[{id:"sample.light",name:"Living Room Lamp",kind:"power",value:!0,isCached:!0,metric:"power",unit:"boolean"},{id:"scene-sample",name:"Evening",kind:"scene",value:null,isCached:!0,metric:"scene",unit:"none"}],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"read",mock:"editable"},{id:"$home.setPower",group:"home",value:{id:"sample.light",value:!0,status:"acknowledged"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"},{id:"$home.runScene",group:"home",value:{id:"scene-sample",status:"acknowledged",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"}],ca="2026-01-01T00:00:00Z",zt="2026-01-01T12:00:00Z",lo=(n,e)=>({value:n,unit:e,hasSamples:!0,start:ca,end:zt}),oh=(n,e,t)=>Object.entries(e).map(([i,s])=>({id:`$${n}.${i}`,group:n,value:s,legacy:[t,i]})),yS=[{id:"$music.isAvailable",group:"music",value:!0},{id:"$music.authorizationStatus",group:"music",value:"authorized"},{id:"$music.current",group:"music",value:{provider:"appleMusic",state:"playing",hasItem:!0,title:"Morning Light",artist:"ScriptWidget Sessions",album:"Focus",duration:224,position:86,capturedAt:zt}},{id:"$services.status",group:"services",value:"connected"},{id:"$services.profile",group:"services",value:{service:"github",subject:"42",username:"octocat",displayName:"Mona",publicRepositories:32,privateRepositories:8,followers:128,following:24}},...oh("device",{screen:{width:390,height:844,scale:3},language:"en",model:"iPhone",name:"My iPhone",battery:{level:.8,state:"unplugged"},systemVersion:"26.0",isdarkmode:!1,totalDiskSpace:128e9,freeDiskSpace:64e9},"device"),...oh("system",{appInfo:{name:"ScriptWidget",bundleId:"com.everettjf.scriptwidget",version:"27.1.2",build:"27012"},locale:"en_US",preferredLanguages:["en-US"],timeZone:{identifier:"UTC",abbreviation:"GMT",offsetSeconds:0},is24HourClock:!1,calendarInfo:{identifier:"gregorian",firstWeekday:1,minimumDaysInFirstWeek:1},systemUptime:3600,memory:{physical:8589934592},thermalState:"nominal",lowPowerMode:!1,brightness:.5,reduceMotionEnabled:!1,platform:"ios",hostName:"My iPhone",processName:"ScriptWidgetWidget",osVersionString:"Version 26.0",processorCount:6,activeProcessorCount:6},"system"),{id:"$photos.isAvailable",group:"photos",value:!0},{id:"$photos.authorizationStatus",group:"photos",value:"authorized"},{id:"$photos.requestAuthorization",group:"photos",value:!0},{id:"$photos.items",group:"photos",value:{status:"ready",items:[{id:"sample.photo",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fbPe3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDQK/QnooooGFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9uKKKK7TxwooooAKKKKACiiigAooooAKKKKACs/VNUsNGsX1HUpBFDGMkn+Q9Sewqtruvab4c099S1STYi8AfxMeyqO5NfInjDxnqfi++865Pl26H91CDwo9T6t6mhs5cTiVSXmX/ABx49v8Axdc+UmYbKM/u4vX/AGm9T+g/U6/w38fv4buRpOqMTYynr18pj3H+ye4/H1z5TRU3PHVean7S+p+gSOkiCSMhlYZBHIIPcU6vmn4YfEL+zXTw5rb/AOjscQyN/wAsyf4Sf7p7Ht9On0tVHuUKyqx5kFFFFBsFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABTXdIkMkhwo5JNOrjPEN8ZJfsUZ+VeW9z/8AWry84zOGXYd4iSu9ku7O7L8FLF1lSjt19Av/AB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1zpU7Znt88g9N8eejDuOjDg9iP038P+INH8UaRDrmhTrcWs67kdf1BHUEdCDyDUNWPrsFjo4mPZ9Uf//S+tKKKK6z8/CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSSRwxtLKwVVGSTwABSTTRW8TTzsERBkseABXhHi3xfLrchsrIlLVT9C5Hc+3oPz9nGNzOpVUFdkvi/xjJrDmw08lbVTyehkI7n29B+ftwNFFbJWPNnNyd2FFFFMkKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvWvhP8W9b+F+r+bBm40+dh9otieG7bk/uuB379D2x5LRSLp1JU5KcHZo//0/rSiiius/PwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtYWublgiIMsx6AU26ureyt3urpwkaDJY14H4q8V3GvzeTDmO1Q/Kvdvdv8O1OMbmVWqoIk8WeLZtdlNrbZS1Q8Du59T/AEFcXRRWyVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/9T60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKKKKACq15eW2n2z3d44SNBkk0y/v7XTbV7y9cJGg5J/kPU18/eJfE114hucnKW6H5I/6n1P8qqMbmVWqoLzJPFHim58QXGxcx2yH5E9fdvf+VcpRRWqVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKo6jqNppVo17etsRfzJ9B6mm6pqlnpFm17ettReg7k+gHrXz34h8Q3niC786c7Y1+5GOij+p9TVRjcxq1lBeY/xH4ku/EN1vk+SFD8kfYe59TXOUUVqedKTbuwooopiCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9b60oqRYZX+4pP0FWV03UX+5byH6Kf8K6z4CzKVFay6Drj/AHLKc/SNv8KsJ4V8Tv8Ac026P0h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wQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/ayiiivVAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9rKKKK9UAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0f2sooor1QCiiigAooooAKKKKACiiigAooooAKKKKACiq15eWun2r3t7IsUUY3MzHAApbW6tr62S8tHEkUqhlZeQQaduoFiiiikAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB/9L9rKKKK9UAooooAKKKKACiiigAooooAKKKKACs/VdVsNFsZNS1OQRQxjJJ/kB3J7Cquva/pnhvTn1PVJNiLwAPvMeyqO5P+eK+P/GPjTU/GF9510fLt0P7qEHhR6n1Y9zXRRoOo/Iyq1VD1L3jrx9f+MLrykzDZRn93F6/7T+p/QdvU7Pw1+IL+GbkaTqjFrCVuvXymP8AEP8AZPcfiO+fJqK9F0ouPJbQ4lUfNzH6FI6SoJIyGVhkEcgg9xTq+ZPhd8Rf7MdPDeuP/ozHEMjf8syf4Sf7p7en06fTdeXVpOm7M74TU1dB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V6UIKKsjJu4UUUVYgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvoL4IfHTVfhdfjTNS3XWiztmSHq0RPWSPPf1Xo3sea+faKzq0o1IuE1oVGbi+aJ+5Gi61pXiLS4Na0SdLm1uF3xyIcgj+hHQg8g8HmtSvyU+DHxs1r4Vap5Em660i4bM9tnkHp5keeA47jow4PYj9UPDviPRfFmjQa/4fnW5tbhdyOv6gjqCDwQeQa+ZxeElQl5Hq0ayqLzP//S+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACo5ZYoI2mmYIiDLMTgADuaSeeG2ha4uGCIgyzHgACvnbxp42m1+Q2NgSlmp+hkI7n29B+J9tKVJzdkTKViXxt44k1x203TSUtFPJ6GQjuf9n0H4n284oor0oxUVZGLdwoooqgCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr2H4QfGLXvhTrPm2+bjTZ2H2m1J4btvT+64Hfv0PbHj1FROEZxcZrQcZOLuj//T+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKgubm3s7d7q6cRxxjLMegFNu7y2sLZ7y8cRxxjLMe1fN/jDxlc+JJ/IgzHaIflTux/vN7+g7VpSpObJlKxL4y8aXHiKY2lpmOzQ8L0Lkd2/oK4OiivSjFRVkYt3CiiiqAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//1PqCiiivszygooooAKKKKACiiigAooooAKKKKACiiigAooooAKqX19aabave3riOKMZJP+etN1HUbPSrN76/cRxoOSf5D1J9K+afFfiy88TXeTmO2Q/u4/6t6n+XataVJzfkTKViXxd4vu/EtzsTMdrGfkj9f9pvf+VcbRRXoxioqyMW7hRRRVAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//V+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACs/VNUstHsnv799kafmT2AHcmmavq9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NicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fave3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDTt1AnooopAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9vKKKK7T0wooooAKKKKACiiigAooooAKKKKACs/VNUsNG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9P8Aaf0H6n8zWd4++Itr4XibTtOIlv2HTqsYPdvf0H4njr8qXl5dahcve3shllkO5mY5JNdVDD83vS2NYU76sn1TVL/Wb59R1KQyzSHJY/yHoB2FZ9FFeilbY6AooooAKKKKACiiigCSGaW3lWeBijoQysDggjoQa+s/h349i8U2n2G/IW/hX5h08xR/EP6j+lfJFW7G+u9MvI7+xcxzRHcrDqDWVWkqisROPMj75orhvA3jW08X6duOI7uIATR/+zL/ALJ/TpXc15couLszlatowoooqQCiiigAooooAKKKKACiiigAoor5v+OXx2svh5av4f8ADzLPrUq/VbdSOGf1b+6v4njAOlOnKpLlgioU3N8sS58bfjlp/wANrJtH0crca1MvyJ1WEHo8nv8A3V79Tx14j4Z/GOx+IsK2eq7bfWEX94g4WbA++nv/AHl7dRx0+Ab+/vdUvZdR1GVp552LySOcszHkkk0y0u7mxuY7yykaKWJgyOpwykdCCK9eeWQlS5Hv3FnPDtLMsI8LN2e6fZ/5H6wUV4f8HfixB47iXw/rDLFq6D5QcKLgDunbeO6/iOMge6yQTQnEqMp9xivmq1CdGThNH4HmeS4vLqjpYqm1br0foyKipY4JpjiJGY+wzXRWHh2aRhJffIv90dT/AIVnGLexngMpxWOkoYeDfn0Xqw8O2DSTfbpB8qcL7n/61drTI40iQRxjao4AFPrshHlVj9pyXKoZbho4eDu92+7CiiiqPWCiiigAooooA//V/byiiiu09MKKKKACiiigArxz4h/EuLQw+jaEwe8PDydVi/xb+Xf0rK+InxPFr5mheGpMy8rLOv8AD6qh9fU9u3PT50JLEsxyTXbQw9/embU6fVj5ZZZ5WmnYu7klmY5JJ6kmo6KK7jcKKKKACiiigAooooAKKKKACiiigDU0bWL/AEHUY9U019ksZ/AjuCO4Pevsjwl4qsPFulrf2nyyLxLGTyjf4Hse9fEddB4a8Sah4X1RNTsD04dD0de4P9D2NYV6POrrcicOY+5KKxfD+v6f4k0xNU01so3DKfvK3dT7itqvMatozlYUUUUgCiiigAooooAKKK+Vvjx8fofBkcvhLwhIsmrONss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Wex41eg6Ts9i7RRRXMYn/0friiiivqD6AKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACkZlRS7nAHJJpHdI0MkhCqoySeAAK8J8Z+NX1Zm0zS2K2w4Zuhk/wDsf51cIOT0Lp03N2RL408bNqJbStJbFuOHcdX9h/s/z+leZUUV3RioqyPQjFRVkFFFFUUFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAV738Fvjfqnwyvhpmo7rnRpmzJF1aInq8ee/qvQ+x5rwSioqU41I8sloTOCmuWR+2Oj6zpfiDTIdZ0adbi1uFDxyIcgj+hHQg8g8GtOvym+Dvxm1j4Xan5Em650mdsz2+eQf+ekeeAw7jow4PYj9P8Aw/4h0fxTpEOu6DOtxa3C7kdf1BHUEdCDyDXz2JwsqL8jxq+HdJ+R/9L64ooor6g+gCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSyxwxtNMwVFGSTwABTZpobaJp52CIgyzHgACvAfGHjKXXZDZWJKWin6FyO59vQfn7XTpubNKdNzehL4y8aSay50/TiVtFPJ6GQj19vQfnXntFFd0YqKsj0IxUVZBRRRVDCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr134S/F3XPhbq/m2+bjTp2H2i2J4btvT+64Hfv0PbHkVFROCmuWS0FKKkuWR//0/riiiivqD6AKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAqG4uILSBrm5cJGgyzHoBTbu7t7G3e7u3EcaDLMe1fPXizxdceIZ/IhzHaoflTu3+039B2rSnTc2aU6bmyXxf4wn1+U2trlLRDwO7kd2/oK4eiiu2MVFWR6EYqKsgoooqhhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//U+uKKKK+oPoAooooAKKKKACiiigAooooAKKKKACiiigAooooAKq3t7a6daveXjhI0GST/AJ602/v7TTLR729cJGg5J/kPUmvnXxR4pu/EdzzmO3Q/u4/6n1P8q0p03M1pUnN+RJ4q8V3XiK42LmO2Q/Inr/tN7/yrkaKK7UklZHfGKirIKKKKoYUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9X64ooor6g+gCiiigAooooAKKKKACiiigAooooAKKKKACqGpalZ6TZtfXz7I1/Mn0A7k03VdVstGs2vr59qL0Hcn0A7mvnLxH4jvfEV558/yxL/AKuMdFH9T6mtadPm9DWlSc/Qk8S+JrzxHd+ZJ8kKH93H2HufU1zNFFdqSSsjvSSVkFFFFMYUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//1vriipFilf7ik/QVZXTtQf7kEh+in/CvqD6ApUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf/AApcy7iuYNFdOngvxc/TTbn8Y2H8xVhfAPjJ+mnTfiMfzpc8e4XRyFFdwvw38bv009/xZB/NqsL8LfHbf8uOPrJH/wDFUvaR7hzLuef0V6Svwl8cN1tkX6yJ/Q1ZX4P+M26pCv1kH9AaXtYdxc67nltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AAJz/wCyUvbw7hzx7njlZesaxY6JZNe3zYUcADqx9APWvSvHfg6P4daE+u+JNQgVfuxxJuMkr/3UBAz7noB1r4j13Xr7xBem7vDgDhEHRR6D+p710UIqpqtjejT9pr0JPEHiC+8Q3hubo7UXhIx0Uf4+prBoorvStojvSS0QUUUUxhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//2Q==",width:384,height:256},{id:"sample.photo.4",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiuc9UKKKKACiiigAooooAKKK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KKKKACjpyaQkAZPAFeI+NfHJvd+kaM+Iekkg/j9h/s+/f6dU3Y1pUnUdkeh+N/2gPEdx4aPgPRJ8RDKS3Sn940eMeWp9OxbqRx06/M9FFZt3PTo0YUlaCCiiikbBRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABX0/8Cvj7deBJo/C/ip2m0ZzhH5ZrYnuO5T1Xt1HcH5gopmNajGtFwmtD9wLS7tb+1jvrGRZoZlDo6EMrKRkEEcEEVYr8xPgf8d7/wCHN0ug68WuNFlblerW5J5dPVe7L+I5yD+l2najYavYxanpcyz286h45EOVZT0INVc+TxeDnh5Wlt0ZdooooOM//9H60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApGZUUu5wBySaR3SNDJIQqqMkngACvBvGnjZ9WZtM0titqDhm6GT/7H+dJuxrSpOo7Im8a+OG1ItpOkNi36O46v7D/Z/n9K8woorNu560IKC5YhRRRSLCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAK98+Cvxw1T4ZXw0zUd1zo07Zki6tET1ePPf1XofrzXgdFMyq0o1YuE1oftro2s6X4h0yHWdFnW5tbhd8ciHII/oR0IPIPBrTr8o/g58Z9Z+Fup+TJuudJnbM9vnkHp5keeA47jow4PYj9QvD3iHRvFWjw69oE63NrcLuR1/UEdQQeCDyDTTPlMbgpYeXddGf/9L60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSyxwxtNMwVFGSTwAB3NNnnhtoWuLhgiIMsx4AAr5+8Y+M5tekNlYkpaKfoXI7n29B+J9k3Y2o0XUdkS+MvGsmtO2nacSlop5PQyEdz7eg/E155RRWbdz1YQUFyxCiiikWFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABXrvwk+L2ufCzWPNt83GnTsPtNqTw3ben91wO/foe2PIqKDOpTjUi4TV0f/T+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtIHublwkaDLMegFNu7u2sbZ7u7cRxoMsx7V87+LfF9z4in8iHMdoh+VO7H+839B2pN2NqNF1H5EvjDxjP4gmNra5jtEPC93I7t/QVw1FFZtnqwgorliFFFFIsKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9T60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAqre3trp1q95euI40GST/nrTNQ1C00u0e9vnCRoOSf5D1Jr5y8U+KrvxJdZOY7dD+7j/qfU/wAqTdjejRdR+RL4r8WXXiO52LmO1Q/Inr/tN7/yrkKKKzPVjFRVkFFFFIoKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP//V+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAqhqep2ekWb318+yNPzJ9AO5NM1XVrLRbJr6/fai9B3Y9gB3NfN/iPxJe+I7zz7j5Yl/wBXGOij+p9TUt2OihQdR+RJ4m8T3niO78yT5IEP7uPsPc+prmaKKg9SMVFWQUUUUigooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/W+tKKkWKV/uKT9BVlNO1CT7kEjfRT/hWR9rcpUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf8AwoFzLuYNFdMvgvxc/TTbn8Y2H8xVlfAPjJ+mnTfiMfzoF7SPc5Ciu4X4b+N36ae/4sg/masL8LfHb/8ALjj6yR//ABVIXtYfzI8/or0lPhL44brbIv1kT+hqynwf8Zt1SFfrIP6A0C9tD+ZHltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AnP8A7JQL6xT/AJjxysrWNZsdDsmvr5sKOAB1Y+gHrXpXjvwfF8OdBfXfEmoQKv3Yok3GSV/7qAgZ9z0A618Q69r194gvTd3hwBwiDoo9B/U96TdjrwtNVveWw/xB4hvvEV6bm6O1F4SMdFH+PqawaKKg9dJJWQUUUUhhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/9k=",width:384,height:256}],unavailableCount:0,fetchedAt:zt,source:"system",stale:!1}},{id:"$calendar.isAvailable",group:"calendar",value:!0},{id:"$calendar.authorizationStatus",group:"calendar",value:"authorized"},{id:"$calendar.requestAuthorization",group:"calendar",value:!0},{id:"$calendar.calendars",group:"calendar",value:[{id:"sample.personal",title:"Personal"}]},{id:"$calendar.events",group:"calendar",value:{status:"ready",items:[{id:"sample.event",calendarID:"sample.personal",title:"Read and recharge",start:"2026-01-01T15:00:00Z",end:"2026-01-01T15:30:00Z",allDay:!1}],fetchedAt:zt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.isAvailable",group:"reminders",value:!0},{id:"$reminders.authorizationStatus",group:"reminders",value:"authorized"},{id:"$reminders.requestAuthorization",group:"reminders",value:!0},{id:"$reminders.lists",group:"reminders",value:[{id:"sample.reminders",title:"Personal"}]},{id:"$reminders.items",group:"reminders",value:{status:"ready",items:[{id:"sample.reminder",listID:"sample.reminders",title:"Read a chapter",due:"2026-01-01T16:00:00Z",hasTime:!0,completed:!1,completedAt:null,priority:0}],fetchedAt:zt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.create",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.update",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.setCompleted",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$health.authorizationStatus",group:"health",value:"notDisclosed"},{id:"$health.sleepSummary",group:"health",value:{start:ca,end:zt,timeZone:"UTC",hasSamples:!0,totalSleepSeconds:27e3,inBedSeconds:30600,awakeSeconds:1800,stages:{unspecified:0,core:16200,deep:5400,rem:5400},sourceCount:1,truncated:!1,conflictSeconds:0,aggregation:"union-awake-rem-deep-core-unspecified"}},{id:"$health.activitySummary",group:"health",value:{date:"2026-01-01",timeZone:"UTC",hasSamples:!0,moveMode:"activeEnergy",move:{value:480,goal:600,unit:"kcal"},exercise:{value:26,goal:30,unit:"min"},stand:{value:9,goal:12,unit:"count"}}},{id:"$health.workouts",group:"health",value:{start:ca,end:zt,timeZone:"UTC",hasSamples:!0,truncated:!1,items:[{id:"550e8400-e29b-41d4-a716-446655440000",activity:"running",start:"2026-01-01T09:00:00.000Z",end:"2026-01-01T09:45:00.000Z",duration:2700,energyKcal:285,distanceMeters:5200}]}},{id:"$health.isAvailable",group:"health",value:!0},{id:"$health.requestAuthorization",group:"health",value:!0,legacy:["health"]},{id:"$health.stepCountToday",group:"health",value:lo(6840,"count"),legacy:["health.stepCountToday"]},{id:"$health.activeEnergyToday",group:"health",value:lo(420,"kcal"),legacy:["health.activeEnergyToday"]},{id:"$health.heartRateLatest",group:"health",value:lo(72,"bpm"),legacy:["health.heartRateLatest"]},{id:"$location.isAvailable",group:"location",value:!0},{id:"$location.authorizationStatus",group:"location",value:"authorizedWhenInUse"},{id:"$location.isAuthorizedForWidgetUpdates",group:"location",value:!0},{id:"$location.requestAuthorization",group:"location",value:!0,legacy:["location.authorization"]},{id:"$location.current",group:"location",value:{latitude:37.3349,longitude:-122.009,altitude:0,accuracy:10,verticalAccuracy:10,speed:-1,course:-1,timestamp:zt,accuracyAuthorization:"full",age:0,isStale:!1},legacy:["location"]}],AS={music:{platforms:["ios"],authorization:"musicRead",notes:"Runtime 1.4. Read-only Music app playback, not every audio player. Requires an installed owner, music permission and Music library approval in native Settings. current() is asynchronous and returns provider, state, hasItem, nullable title/artist/album/duration/position and capturedAt. State may be playing while details are absent (Home Sharing). Native player access is main-thread-only: synchronous hosts prepare one snapshot before JSC waits; background previews capture on the main queue. No playback/queue mutation, scans, artwork, credential or subscription inference. No live queries in future entries/Live Activities. Main system-player API is unavailable on macOS; Web supplies editable samples, never actual device access."},services:{platforms:["ios","macos"],authorization:"serviceAccount",notes:"Runtime 1.4: status(service) and profile(service) are asynchronous. Only provider: github. Unknown providers reject with service_operation. Requires an installed owner and services permission. profile additionally requires network and api.github.com in networkDomains, a native connected GitHub account and explicit owner grant. Native Settings handles credentials; scripts cannot log in or obtain tokens. profile returns service, subject, username, displayName, publicRepositories, privateRepositories, followers and following (missing values are null). No live queries in future entries or Live Activities. Eight shared data queries; native requests also share the eight concurrent/32 total network budget, while Web uses its existing preview network budget. Web uses editable best-state samples only; it never authenticates or sends these requests."},photos:{platforms:["ios","macos"],authorization:"photosRead",notes:"Requires photos permission and explicit native photo/album selection (none by default). Limited Photos authorization is supported. items({limit:1..4,offset:0..63,maxAgeSeconds:0..86400}) returns bounded, metadata-stripped JPEG thumbnails as image data URLs. Four 768px / 128KiB thumbnails at most; private snapshots expire after 24h and are rechecked against current access, selected sources and asset revisions. Cloud-only items report unavailableCount; download them in Photos first. Future timeline/Live Activity presentations read matching snapshots only. Web uses editable sample data and photosSelection IDs; no actual library access."},reminders:{platforms:["ios","macos"],authorization:"remindersRead",notes:"Requires reminders in widget.json and full system Reminders access. Reads require native Settings selected lists. create/update/setCompleted additionally require remindersWrite and a native declared action, stable requestID, durable replay receipts and an unchanged selected list. Web writes update preview-only items/receipts; receipt identities are derived from that state, with configurable API errors. Use lists() for IDs. items() selects pending due dates or completed completion dates in a positive window of at most 31 days, up to 50 items. Undated pending reminders are excluded. remindersSelection mocks the user scope without granting permission."},calendar:{platforms:["ios","macos"],authorization:"calendarRead",notes:"Requires calendar in widget.json and full system Calendar access. The user's native Settings source selection limits metadata, events and cached snapshots; scripts cannot enlarge it. Use calendars() for permitted IDs and show setup when no sources are selected. Queries are read-only, limited to 31 days and 50 items. Preview calendarSelection simulates this scope without granting package permission."},device:{platforms:["ios","macos"],authorization:"none",notes:"Device values depend on hardware. Some legacy Mac values are placeholders; inspect the API documentation before using them as measurements."},system:{platforms:["ios","macos"],authorization:"none",notes:"System metadata, not whole-device CPU, FPS or network traffic monitoring. Hardware-specific values may be unavailable."},health:{platforms:["ios"],authorization:"healthRead",notes:"Read-only HealthKit. Request access in the app. Runtime 1.4 adds sleepSummary (up to 7 days / 256 samples, union with explicit stage-conflict precedence), activitySummary (one local Gregorian day including active-energy or move-time mode and optional goals), and workouts (up to 31 days / 50 fully-contained summaries, optional kcal/meters). These require an explicit health manifest; all share the query budget and cannot run in future/Live Activity presentations. No Health readings are persisted by the API. Authorization completion does not reveal whether individual read types were granted; empty results must not be labelled permission denied. API 1.3 readings add hasSamples: false means no readable samples, never a read-denial verdict. Existing value/unit/start/end fields remain."},location:{platforms:["ios"],authorization:"locationWhenInUse",notes:"Package 2.0 requires location permission. Request system access in the app. Widgets also require isAuthorizedForWidgetUpdates. Cache is rechecked against authorization and precision, discarded after 24 hours or revocation, and reports age/isStale."}},bS=[...yS.map(n=>{const e=n.id.split(".")[1],t=n.group==="music"&&e==="current"||n.group==="services"||["calendar","reminders","photos"].includes(n.group)&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="health"&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e),i=n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e)||["calendar","reminders","photos"].includes(n.group)&&["events","items"].includes(e);return{...n,...AS[n.group],minimumRuntimeVersion:["music","services","reminders","photos"].includes(n.group)||n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)?"1.4":["calendar"].includes(n.group)||["$health.authorizationStatus","$location.isAuthorizedForWidgetUpdates"].includes(n.id)?"1.3":"1.0",arguments:n.group==="services"?["service"]:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?["options"]:i?["options?"]:[],...n.group==="reminders"&&["create","update","setCompleted"].includes(e)?{authorization:"remindersWrite"}:{},asynchronous:t,nativeSource:`Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntime${n.group[0].toUpperCase()}${n.group.slice(1)}.swift`,operation:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?"write":e==="requestAuthorization"?"authorization":["isAvailable","authorizationStatus","isAuthorizedForWidgetUpdates"].includes(e)?"availability":"read",mock:"editable"}}),...OS],$e={globalProperties:{background:{type:"color",documentation:"Background color, hex value, or named color."},backgroundMaterial:{type:"enum",values:["none","ultraThin","thin","regular","thick","ultraThick"],documentation:"Runtime API 1.4. Public SwiftUI frosted material inside the widget, not Home Screen wallpaper blur or system Liquid Glass. At most four material backgrounds per tree. background supplies an opaque-composited Reduce Transparency fallback. In accented/vibrant mode local material is omitted for system rendering; none keeps the ordinary background."},color:{type:"color",documentation:"Foreground color, hex value, or named color."},font:{type:"enum",values:["largeTitle","title","title2","title3","headline","subheadline","body","callout","footnote","caption","caption2"],documentation:"Semantic text style."},fontWeight:{type:"enum",values:["ultraLight","thin","light","regular","medium","semibold","bold","heavy","black"],documentation:"Font weight."},fontDesign:{type:"enum",values:["default","rounded","serif","monospaced"],documentation:"Font design."},frame:{type:"number|string",documentation:'Square size (64 or "64"), width,height ("64,48"), or flexible frame ("max", "max,48").'},padding:{type:"number|string",documentation:"Padding amount or edge description."},corner:{type:"number",documentation:"Corner radius."},opacity:{type:"number",documentation:"Opacity from 0 through 1."},alignment:{type:"enum",values:["center","leading","trailing","top","bottom","topLeading","topTrailing","bottomLeading","bottomTrailing","firstTextBaseline","lastTextBaseline"],documentation:"Layout alignment."},clip:{type:"enum",values:["circle","rect","capsule","ellipse"],documentation:"Clip the view to a shape."},rotation:{type:"number",documentation:"Rotation in degrees."},rotation3d:{type:"string",documentation:"Static degree,x,y,z rotation with four finite numbers and a nonzero axis. Invalid values are ignored; axis magnitude is normalized. Reduce Motion removes the tilt. This does not read device motion or provide parallax."},shadow:{type:"string",documentation:"Shadow color, radius, and offset description."},animation:{type:"string",documentation:"iOS public SwiftUI scheduled clock/swing effect. Mac renders static standard-clock poses; other effects remain at rest. Signed clockCustom intervals specify a half-turn (full cycle = 2 * abs(interval)), minimum magnitude 0.25 seconds. App previews can animate; WidgetKit decides cadence and may freeze. Reduced motion/luminance freezes standard clock poses and keeps custom/swing effects at rest. Dynamic scripts are not rerun on animation ticks."},widgetAccentable:{type:"boolean",documentation:"Group this view into the accent layer in tinted and vibrant widget appearances."},linkurl:{type:"url",documentation:"Widget deep link URL."}},components:{VStack:{documentation:"Arrange children vertically.",children:!0,properties:{spacing:{type:"number"}}},HStack:{documentation:"Arrange children horizontally.",children:!0,properties:{spacing:{type:"number"}}},ZStack:{documentation:"Overlay children.",children:!0,properties:{}},VGrid:{documentation:"Vertical lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["leading","center","trailing"]}}},HGrid:{documentation:"Horizontal lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["top","center","bottom","firstTextBaseline","lastTextBaseline"]}}},Text:{documentation:"Display text content.",children:!1,properties:{text:{type:"string"}}},Date:{documentation:"Display a formatted date.",children:!1,properties:{date:{type:"date|number",required:!0},style:{type:"enum",values:["time","date","relative","offset","timer"]}}},Image:{documentation:"Display a bundled, remote, or SF Symbol image.",children:!1,properties:{systemName:{type:"string"},name:{type:"string"},id:{type:"string",deprecated:"Use name."},url:{type:"url"},src:{type:"url",deprecated:"Use url."},ratio:{type:"number"},mode:{type:"enum",values:["fit","fill"]},accentedRenderingMode:{type:"enum",values:["accented","desaturated","accentedDesaturated","fullColor"],documentation:"Control how the image is rendered in tinted and clear widget appearances."}}},Gif:{documentation:"Display a bounded package GIF using system decoding: up to 8 MiB input and 1,048,576 canvas pixels. iOS retains at most 60 downsampled frames / 4 MiB decoded pixels; more frames fall back to the first frame. Mac, Reduce Motion and reduced luminance use a static first frame. Active iOS previews use public SwiftUI timing with variable frame delays. Snapshots, inactive scenes, Mac and accessibility fallbacks use the first frame. No private clock bridge or continuous WidgetKit guarantee.",children:!1,properties:{file:{type:"string",required:!0}}},Spacer:{documentation:"Flexible layout space.",children:!1,properties:{minLength:{type:"number"}}},Rect:{documentation:"Rectangle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},RoundedRect:{documentation:"Filled rounded rectangle.",children:!1,properties:{radius:{type:"number"}}},Capsule:{documentation:"Capsule shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Ellipse:{documentation:"Ellipse shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Circle:{documentation:"Circle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Gauge:{documentation:"Display a gauge or instrument.",children:!1,properties:{type:{type:"string"},value:{type:"number"},style:{type:"enum",values:["circular","linear"]},text:{type:"string"},current:{type:"string"},min:{type:"string"},max:{type:"string"},angle:{type:"number"},thickness:{type:"number"},needleColor:{type:"color"},label:{type:"string"},title:{type:"string"},sections:{type:"string"}}},Chart:{documentation:"Render chart data.",children:!1,availability:{ios:"16.0",macos:"26.0"},properties:{type:{type:"enum",values:["bar","bar-x","bar-y","bar-gantt","line","point","line-point","area","rect","rule-x"]},data:{type:"json",required:!0},category:{type:"boolean"},hideLegend:{type:"boolean"},hideXAxis:{type:"boolean"},hideYAxis:{type:"boolean"}}},Link:{documentation:"Open a URL when selected.",children:!0,properties:{url:{type:"url",required:!0}}},Divider:{documentation:"Horizontal or vertical separator.",children:!1,properties:{thickness:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Line:{documentation:"Fixed-length line.",children:!1,properties:{thickness:{type:"number"},length:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Icon:{documentation:"SF Symbol icon.",children:!1,properties:{systemName:{type:"string",required:!0},size:{type:"number"}}},Label:{documentation:"Text paired with an SF Symbol.",children:!1,properties:{title:{type:"string"},systemName:{type:"string",required:!0}}},Progress:{documentation:"Linear or circular progress.",children:!1,properties:{value:{type:"number",required:!0},total:{type:"number"},label:{type:"string"},style:{type:"enum",values:["linear","circular"]},trackColor:{type:"color"},thickness:{type:"number"}}},Ring:{documentation:"Circular progress ring.",children:!1,properties:{value:{type:"number",required:!0},thickness:{type:"number"},trackColor:{type:"color"}}},Badge:{documentation:"Compact status badge.",children:!1,properties:{text:{type:"string"},radius:{type:"number"}}},Chip:{documentation:"Outlined metadata chip.",children:!1,properties:{text:{type:"string"},radius:{type:"number"},borderColor:{type:"color"}}},Stat:{documentation:"Title, value, and subtitle statistic.",children:!1,properties:{title:{type:"string"},value:{type:"string",required:!0},subtitle:{type:"string"},mutedColor:{type:"color"}}},Button:{documentation:"Interactive widget button. Use actionID to share a declared Package 2.0 action with Siri, Shortcuts, and Control Widgets.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["action","onClick","actionID"],properties:{action:{type:"enum",values:["reload"],conflicts:["actionID"]},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",conflicts:["action","onClick"]}}},Toggle:{documentation:"Interactive widget toggle. A declared actionID requires a package-relative storage stateKey.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["onClick","actionID"],properties:{on:{type:"boolean",required:!0},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",requires:["stateKey"],conflicts:["onClick"]},stateKey:{type:"storage-key",requires:["actionID"]}}}},functions:{...Object.fromEntries(gS.map(n=>[n.id,n])),...Object.fromEntries(bS.map(n=>[n.id,{documentation:n.notes,minimumRuntimeVersion:n.minimumRuntimeVersion,arguments:n.arguments,returns:n.asynchronous?"Promise":typeof n.value=="object"?"json":typeof n.value}])),"$icloud.readJSON":{documentation:"Read cached JSON and revision; conflicts preserve all heads. Requires icloud permission and a native connection. Never certifies upload.",arguments:["name"],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.writeJSON":{documentation:"Save a new immutable JSON revision locally from a user action. Requires the revision from readJSON. Background exchange is eventual.",arguments:["name","value","expectedRevision"],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.resolveJSON":{documentation:"Explicitly resolve all observed conflicting heads into a new revision. Stale tokens fail; originals remain.",arguments:["name","value","expectedRevision"],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.sync":{documentation:"Exchange materialized revisions with iCloud; requires a user action. Upload completion is unknown.",arguments:[],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.status":{documentation:"Read native connection state. In the app, explicitly connect packages to separate stores for isolation or the same store ID to share JSON documents. Scripts cannot choose store IDs. Sync is eventual; local $storage is not migrated. Web uses preview mocks.",arguments:[],returns:"Promise",minimumRuntimeVersion:"1.5"},"$file.exists":{documentation:"Return whether a regular file is locally present inside this package, including binary assets. Missing files, directories, unsafe paths and links return false. Does not download iCloud files or read outside the package. Web preview uses workspace file presence.",arguments:["path"],returns:"boolean",minimumRuntimeVersion:"1.3"},"$file.read":{documentation:"Read package-relative UTF-8 text. Missing or unavailable files return an empty string.",arguments:["path"],returns:"string"},"$file.readJSON":{documentation:"Read a package-relative JSON object.",arguments:["path"],returns:"json"},fetch:{documentation:"Perform a network request and return its response text. Existing HTTP methods keep this string result."},"$http.getResponse":{documentation:"GET response metadata: {status, body, headers}. Headers are limited to content-type, cache-control, expires, last-modified, date and retry-after (lowercase; each at most 2048 UTF-8 bytes). Network permissions, public-host policy, redirects, body limits and timeline restrictions still apply. HTTP error statuses resolve; transport errors reject.",arguments:["url","options?"],returns:"Promise",minimumRuntimeVersion:"1.3"},importJS:{documentation:"Import a package-relative JavaScript file."},"$dataSource.request":{documentation:"Call a declared Data Source Plugin operation. Requires Package 2.0 plugins, network permission, and networkDomains declarations.",arguments:["pluginID","operationID","parameters"],returns:"Promise"},"$xml.parse":{documentation:"Parse up to 256 KiB of XML into {name, attributes, text, children}. DTDs and external entities are rejected; depth and node limits apply.",arguments:["source"],returns:"XMLNode"}}};function SS(n,e){const t=Object.entries(e.properties??{}).filter(([,s])=>s.required).map(([s,r])=>`${s}=${r.type.includes("number")||r.type==="boolean"?"{${}}":'"${}"'}`).join(" "),i=t?` ${t}`:"";return e.children?`<${n}${i}> +}`,{label:"class",detail:"definition",type:"keyword"}),Ye('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ye('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],mb=hd.concat([Ye("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Ye("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Ye("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Jc=new yO,ud=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function cn(n){return(e,t)=>{let i=e.node.getChild("VariableDefinition");return i&&t(i,n),!0}}const gb=["FunctionDeclaration"],Ob={FunctionDeclaration:cn("function"),ClassDeclaration:cn("class"),ClassExpression:()=>!0,EnumDeclaration:cn("constant"),TypeAliasDeclaration:cn("type"),NamespaceDeclaration:cn("namespace"),VariableDefinition(n,e){n.matchContext(gb)||e(n,"variable")},TypeDefinition(n,e){e(n,"type")},__proto__:null};function fd(n,e){let t=Jc.get(e);if(t)return t;let i=[],s=!0;function r(o,a){let l=n.sliceString(o.from,o.to);i.push({label:l,type:a})}return e.cursor(be.IncludeAnonymous).iterate(o=>{if(s)s=!1;else if(o.name){let a=Ob[o.name];if(a&&a(o,r)||ud.has(o.name))return!1}else if(o.to-o.from>8192){for(let a of fd(n,o.node))i.push(a);return!1}}),Jc.set(e,i),i}const eh=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,dd=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function yb(n){let e=Ce(n.state).resolveInner(n.pos,-1);if(dd.indexOf(e.name)>-1)return null;let t=e.name=="VariableName"||e.to-e.from<20&&eh.test(n.state.sliceDoc(e.from,e.to));if(!t&&!n.explicit)return null;let i=[];for(let s=e;s;s=s.parent)ud.has(s.name)&&(i=i.concat(fd(n.state.doc,s)));return{options:i,from:t?e.from:n.pos,validFor:eh}}const Bt=Is.define({name:"javascript",parser:pb.configure({props:[rf.add({IfStatement:Gr({except:/^\s*({|else\b)/}),TryStatement:Gr({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:LO,SwitchBody:n=>{let e=n.textAfter,t=/^\s*\}/.test(e),i=/^\s*(case|default)\b/.test(e);return n.baseIndent+(t?0:i?1:2)*n.unit},Block:DO({closing:"}"}),ArrowFunction:n=>n.baseIndent+n.unit,"TemplateString BlockComment":()=>null,"Statement Property":Gr({except:/^\s*{/}),JSXElement(n){let e=/^\s*<\//.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},JSXEscape(n){let e=/\s*\}/.test(n.textAfter);return n.lineIndent(n.node.from)+(e?0:n.unit)},"JSXOpenTag JSXSelfClosingTag"(n){return n.column(n.node.from)+n.unit}}),lf.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":WO,BlockComment(n){return{from:n.from+2,to:n.to-2}},JSXElement(n){let e=n.firstChild;if(!e||e.name=="JSXSelfClosingTag")return null;let t=n.lastChild;return{from:e.to,to:t.type.isError?n.to:t.from}},"JSXSelfClosingTag JSXOpenTag"(n){var e;let t=(e=n.firstChild)===null||e===void 0?void 0:e.nextSibling,i=n.lastChild;return!t||t.type.isError?null:{from:t.to,to:i.type.isError?n.to:i.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),pd={test:n=>/^JSX/.test(n.name),facet:nf({commentTokens:{block:{open:"{/*",close:"*/}"}}})},Ab=Bt.configure({dialect:"ts"},"typescript"),bb=Bt.configure({dialect:"jsx",props:[Ua.add(n=>n.isTop?[pd]:void 0)]}),Sb=Bt.configure({dialect:"jsx ts",props:[Ua.add(n=>n.isTop?[pd]:void 0)]},"typescript");let md=n=>({label:n,type:"keyword"});const gd="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(md),xb=gd.concat(["declare","implements","private","protected","public"].map(md));function vb(n={}){let e=n.jsx?n.typescript?Sb:bb:n.typescript?Ab:Bt,t=n.typescript?mb.concat(xb):hd.concat(gd);return new RO(e,[Bt.data.of({autocomplete:My(dd,_f(t))}),Bt.data.of({autocomplete:yb}),n.jsx?Qb:[]])}function wb(n){for(;;){if(n.name=="JSXOpenTag"||n.name=="JSXSelfClosingTag"||n.name=="JSXFragmentTag")return n;if(n.name=="JSXEscape"||!n.parent)return null;n=n.parent}}function th(n,e,t=n.length){for(let i=e?.firstChild;i;i=i.nextSibling)if(i.name=="JSXIdentifier"||i.name=="JSXBuiltin"||i.name=="JSXNamespacedName"||i.name=="JSXMemberExpression")return n.sliceString(i.from,Math.min(i.to,t));return""}const kb=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),Qb=K.inputHandler.of((n,e,t,i,s)=>{if((kb?n.composing:n.compositionStarted)||n.state.readOnly||e!=t||i!=">"&&i!="/"||!Bt.isActiveAt(n.state,e,-1))return!1;let r=s(),{state:o}=r,a=o.changeByRange(l=>{var c;let{head:h}=l,u=Ce(o).resolveInner(h-1,-1),f;if(u.name=="JSXStartTag"&&(u=u.parent),!(o.doc.sliceString(h-1,h)!=i||u.name=="JSXAttributeValue"&&u.to>h)){if(i==">"&&u.name=="JSXFragmentTag")return{range:l,changes:{from:h,insert:""}};if(i=="/"&&u.name=="JSXStartCloseTag"){let d=u.parent,p=d.parent;if(p&&d.from==h-2&&((f=th(o.doc,p.firstChild,h))||((c=p.firstChild)===null||c===void 0?void 0:c.name)=="JSXFragmentTag")){let m=`${f}>`;return{range:A.cursor(h+m.length,-1),changes:{from:h,insert:m}}}}else if(i==">"){let d=wb(u);if(d&&d.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(o.doc.sliceString(h,h+2))&&(f=th(o.doc,d,h)))return{range:l,changes:{from:h,insert:``}}}}return{range:l}});return a.changes.empty?!1:(n.dispatch([r,o.update(a,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),ih=typeof String.prototype.normalize=="function"?n=>n.normalize("NFKD"):n=>n;class Yi{constructor(e,t,i=0,s=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,s),this.bufferStart=i,this.normalize=r?a=>r(ih(a)):ih,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Ne(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=ma(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=Qt(e);let s=this.normalize(t);if(s.length)for(let r=0,o=i,a=!0;;r++){let l=s.charCodeAt(r),c=this.match(l,o,a,this.bufferPos+this.bufferStart,r==s.length-1);if(c)return this.value=c,this;if(r==s.length-1)break;a&&rthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,s=i+t[0].length;if(this.matchPos=er(this.text,s+(i==s?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||s.to<=t){let a=new Li(t,e.sliceString(t,i));return lo.set(e,a),a}if(s.from==t&&s.to==i)return s;let{text:r,from:o}=s;return o>t&&(r=e.sliceString(t,o)+r,o=t),s.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,s=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,s,t)))return this.value={from:i,to:s,precise:!0,match:t},this.matchPos=er(this.text,s+(i==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Li.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(yd.prototype[Symbol.iterator]=Ad.prototype[Symbol.iterator]=function(){return this});function Pb(n){try{return new RegExp(n,_a),!0}catch{return!1}}function er(n,e){if(e>=n.length)return e;let t=n.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}const Cb=n=>{let{state:e}=n,t=String(e.doc.lineAt(n.state.selection.main.head).number),{close:i,result:s}=_g(n,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return s.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){n.dispatch({effects:i});return}let a=e.doc.lineAt(e.selection.main.head),[,l,c,h,u]=o,f=h?+h.slice(1):0,d=c?+c:a.number;if(c&&u){let g=d/100;l&&(g=g*(l=="-"?-1:1)+a.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else c&&l&&(d=d*(l=="-"?-1:1)+a.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),m=A.cursor(p.from+Math.max(0,Math.min(f,p.length)));n.dispatch({effects:[i,K.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},Tb={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Rb=Z.define({combine(n){return yt(n,Tb,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function $b(n){return[Ub,Eb]}const Kb=I.mark({class:"cm-selectionMatch"}),Zb=I.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function nh(n,e,t,i){return(t==0||n(e.sliceDoc(t-1,t))!=ye.Word)&&(i==e.doc.length||n(e.sliceDoc(i,i+1))!=ye.Word)}function Mb(n,e,t,i){return n(e.sliceDoc(t,t+1))==ye.Word&&n(e.sliceDoc(i-1,i))==ye.Word}const Eb=xe.fromClass(class{constructor(n){this.decorations=this.getDeco(n)}update(n){(n.selectionSet||n.docChanged||n.viewportChanged)&&(this.decorations=this.getDeco(n.view))}getDeco(n){let e=n.state.facet(Rb),{state:t}=n,i=t.selection;if(i.ranges.length>1)return I.none;let s=i.main,r,o=null;if(s.empty){if(!e.highlightWordAroundCursor)return I.none;let l=t.wordAt(s.head);if(!l)return I.none;o=t.charCategorizer(s.head),r=t.sliceDoc(l.from,l.to)}else{let l=s.to-s.from;if(l200)return I.none;if(e.wholeWords){if(r=t.sliceDoc(s.from,s.to),o=t.charCategorizer(s.head),!(nh(o,t,s.from,s.to)&&Mb(o,t,s.from,s.to)))return I.none}else if(r=t.sliceDoc(s.from,s.to),!r)return I.none}let a=[];for(let l of n.visibleRanges){let c=new Yi(t.doc,r,l.from,l.to);for(;!c.next().done;){let{from:h,to:u}=c.value;if((!o||nh(o,t,h,u))&&(s.empty&&h<=s.from&&u>=s.to?a.push(Zb.range(h,u)):(h>=s.to||u<=s.from)&&a.push(Kb.range(h,u)),a.length>e.maxMatches))return I.none}}return I.set(a)}},{decorations:n=>n.decorations}),Ub=K.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),Fb=({state:n,dispatch:e})=>{let{selection:t}=n,i=A.create(t.ranges.map(s=>n.wordAt(s.head)||A.cursor(s.head)),t.mainIndex);return i.eq(t)?!1:(e(n.update({selection:i})),!0)};function Db(n,e){let{main:t,ranges:i}=n.selection,s=n.wordAt(t.head),r=s&&s.from==t.from&&s.to==t.to;for(let o=!1,a=new Yi(n.doc,e,i[i.length-1].to);;)if(a.next(),a.done){if(o)return null;a=new Yi(n.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(l=>l.from==a.value.from))continue;if(r){let l=n.wordAt(a.value.from);if(!l||l.from!=a.value.from||l.to!=a.value.to)continue}return a.value}}const Lb=({state:n,dispatch:e})=>{let{ranges:t}=n.selection;if(t.some(r=>r.from===r.to))return Fb({state:n,dispatch:e});let i=n.sliceDoc(t[0].from,t[0].to);if(n.selection.ranges.some(r=>n.sliceDoc(r.from,r.to)!=i))return!1;let s=Db(n,i);return s?(e(n.update({selection:n.selection.addRange(A.range(s.from,s.to),!1),effects:K.scrollIntoView(s.to)})),!0):!1},tn=Z.define({combine(n){return yt(n,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new Jb(e),scrollToMatch:e=>K.scrollIntoView(e)})}});class bd{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||Pb(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` +`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new zb(this):new Ib(this)}getCursor(e,t=0,i){let s=e.doc?e:J.create({doc:e});return i==null&&(i=s.doc.length),this.regexp?Pi(this,s,t,i):Qi(this,s,t,i)}}class Sd{constructor(e){this.spec=e}}function Xb(n,e,t){return(i,s,r,o)=>{if(t&&!t(i,s,r,o))return!1;let a=i>=o&&s<=o+r.length?r.slice(i-o,s-o):e.doc.sliceString(i,s);return n(a,e,i,s)}}function Qi(n,e,t,i){let s;return n.wholeWord&&(s=Bb(e.doc,e.charCategorizer(e.selection.main.head))),n.test&&(s=Xb(n.test,e,s)),new Yi(e.doc,n.unquoted,t,i,n.caseSensitive?void 0:r=>r.toLowerCase(),s)}function Bb(n,e){return(t,i,s,r)=>((r>t||r+s.length=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Qi(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}function Wb(n,e,t){return(i,s,r)=>(!t||t(i,s,r))&&n(r[0],e,i,s)}function Pi(n,e,t,i){let s;return n.wholeWord&&(s=qb(e.charCategorizer(e.selection.main.head))),n.test&&(s=Wb(n.test,e,s)),new yd(e.doc,n.search,{ignoreCase:!n.caseSensitive,test:s},t,i)}function tr(n,e){return n.slice(Ze(n,e,!1),e)}function ir(n,e){return n.slice(e,Ze(n,e))}function qb(n){return(e,t,i)=>!i[0].length||(n(tr(i.input,i.index))!=ye.Word||n(ir(i.input,i.index))!=ye.Word)&&(n(ir(i.input,i.index+i[0].length))!=ye.Word||n(tr(i.input,i.index+i[0].length))!=ye.Word)}class zb extends Sd{nextMatch(e,t,i){let s=Pi(this.spec,e,i,e.doc.length).next();return s.done&&(s=Pi(this.spec,e,0,t).next()),s.done?null:s.value}prevMatchInRange(e,t,i){for(let s=1;;s++){let r=Math.max(t,i-s*1e4),o=Pi(this.spec,e,r,i),a=null;for(;!o.next().done;)a=o.value;if(a&&(r==t||a.from>r+10))return a;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let s=i.length;s>0;s--){let r=+i.slice(0,s);if(r>0&&r=t)return null;s.push(i.value)}return s}highlight(e,t,i,s){let r=Pi(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)s(r.value.from,r.value.to)}}const Zn=Y.define(),Ja=Y.define(),_t=Te.define({create(n){return new co(ca(n).create(),null)},update(n,e){for(let t of e.effects)t.is(Zn)?n=new co(t.value.create(),n.panel):t.is(Ja)&&(n=new co(n.query,t.value?el:null));return n},provide:n=>Vi.from(n,e=>e.panel)});class co{constructor(e,t){this.query=e,this.panel=t}}const Vb=I.mark({class:"cm-searchMatch"}),jb=I.mark({class:"cm-searchMatch cm-searchMatch-selected"}),Yb=xe.fromClass(class{constructor(n){this.view=n,this.decorations=this.highlight(n.state.field(_t))}update(n){let e=n.state.field(_t);(e!=n.startState.field(_t)||n.docChanged||n.selectionSet||n.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:n,panel:e}){if(!e||!n.spec.valid)return I.none;let{view:t}=this,i=new It;for(let s=0,r=t.visibleRanges,o=r.length;sr[s+1].from-500;)l=r[++s].to;n.highlight(t.state,a,l,(c,h)=>{let u=t.state.selection.ranges.some(f=>f.from==c&&f.to==h);i.add(c,h,u?jb:Vb)})}return i.finish()}},{decorations:n=>n.decorations});function zn(n){return e=>{let t=e.state.field(_t,!1);return t&&t.query.spec.valid?n(e,t):wd(e)}}const nr=zn((n,{query:e})=>{let{to:t}=n.state.selection.main,i=e.nextMatch(n.state,t,t);if(!i)return!1;let s=A.single(i.from,i.to),r=n.state.facet(tn);return n.dispatch({selection:s,effects:[tl(n,i),r.scrollToMatch(s.main,n)],userEvent:"select.search"}),vd(n),!0}),sr=zn((n,{query:e})=>{let{state:t}=n,{from:i}=t.selection.main,s=e.prevMatch(t,i,i);if(!s)return!1;let r=A.single(s.from,s.to),o=n.state.facet(tn);return n.dispatch({selection:r,effects:[tl(n,s),o.scrollToMatch(r.main,n)],userEvent:"select.search"}),vd(n),!0}),Nb=zn((n,{query:e})=>{let t=e.matchAll(n.state,1e3);return!t||!t.length?!1:(n.dispatch({selection:A.create(t.map(i=>A.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),Hb=({state:n,dispatch:e})=>{let t=n.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:s}=t.main,r=[],o=0;for(let a=new Yi(n.doc,n.sliceDoc(i,s));!a.next().done;){if(r.length>1e3)return!1;a.value.from==i&&(o=r.length),r.push(A.range(a.value.from,a.value.to))}return e(n.update({selection:A.create(r,o),userEvent:"select.search.matches"})),!0},sh=zn((n,{query:e})=>{let{state:t}=n,{from:i,to:s}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,a=[],l,c,h=[];o.precise?o.from==i&&o.to==s&&(c=t.toText(e.getReplacement(o)),a.push({from:o.from,to:o.to,insert:c}),o=e.nextMatch(t,o.from,o.to),h.push(K.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let u=n.state.changes(a);return o&&(l=A.single(o.from,o.to).map(u),h.push(tl(n,o)),h.push(t.facet(tn).scrollToMatch(l.main,n))),n.dispatch({changes:u,selection:l,effects:h,userEvent:"input.replace"}),!0}),Gb=zn((n,{query:e})=>{if(n.state.readOnly)return!1;let t=[];for(let s of e.matchAll(n.state,1e9)){let{from:r,to:o,precise:a}=s;a&&t.push({from:r,to:o,insert:e.getReplacement(s)})}if(!t.length)return!1;let i=n.state.phrase("replaced $ matches",t.length)+".";return n.dispatch({changes:t,effects:K.announce.of(i),userEvent:"input.replace.all"}),!0});function el(n){return n.state.facet(tn).createPanel(n)}function ca(n,e){var t,i,s,r,o;let a=n.selection.main,l=a.empty||a.to>a.from+100?"":n.sliceDoc(a.from,a.to);if(e&&!l)return e;let c=n.facet(tn);return new bd({search:((t=e?.literal)!==null&&t!==void 0?t:c.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:c.caseSensitive,literal:(s=e?.literal)!==null&&s!==void 0?s:c.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:c.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:c.wholeWord})}function xd(n){let e=Bu(n,el);return e&&e.dom.querySelector("[main-field]")}function vd(n){let e=xd(n);e&&e==n.root.activeElement&&e.select()}const wd=n=>{let e=n.state.field(_t,!1);if(e&&e.panel){let t=xd(n);if(t&&t!=n.root.activeElement){let i=ca(n.state,e.query.spec);i.valid&&n.dispatch({effects:Zn.of(i)}),t.focus(),t.select()}}else n.dispatch({effects:[Ja.of(!0),e?Zn.of(ca(n.state,e.query.spec)):Y.appendConfig.of(tS)]});return!0},kd=n=>{let e=n.state.field(_t,!1);if(!e||!e.panel)return!1;let t=Bu(n,el);return t&&t.dom.contains(n.root.activeElement)&&n.focus(),n.dispatch({effects:Ja.of(!1)}),!0},_b=[{key:"Mod-f",run:wd,scope:"editor search-panel"},{key:"F3",run:nr,shift:sr,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:nr,shift:sr,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:kd,scope:"editor search-panel"},{key:"Mod-Shift-l",run:Hb},{key:"Mod-Alt-g",run:Cb},{key:"Mod-d",run:Lb,preventDefault:!0}];class Jb{constructor(e){this.view=e;let t=this.query=e.state.field(_t).query.spec;this.commit=this.commit.bind(this),this.searchField=he("input",{value:t.search,placeholder:st(e,"Find"),"aria-label":st(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=he("input",{value:t.replace,placeholder:st(e,"Replace"),"aria-label":st(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=he("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=he("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=he("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(s,r,o){return he("button",{class:"cm-button",name:s,onclick:r,type:"button"},o)}this.dom=he("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,i("next",()=>nr(e),[st(e,"next")]),i("prev",()=>sr(e),[st(e,"previous")]),i("select",()=>Nb(e),[st(e,"all")]),he("label",null,[this.caseField,st(e,"match case")]),he("label",null,[this.reField,st(e,"regexp")]),he("label",null,[this.wordField,st(e,"by word")]),...e.state.readOnly?[]:[he("br"),this.replaceField,i("replace",()=>sh(e),[st(e,"replace")]),i("replaceAll",()=>Gb(e),[st(e,"replace all")])],he("button",{name:"close",onclick:()=>kd(e),"aria-label":st(e,"close"),type:"button"},["×"])])}commit(){let e=new bd({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:Zn.of(e)}))}keydown(e){cg(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?sr:nr)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),sh(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(Zn)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(tn).top}}function st(n,e){return n.state.phrase(e)}const ds=30,ps=/[\s\.,:;?!]/;function tl(n,{from:e,to:t}){let i=n.state.doc.lineAt(e),s=n.state.doc.lineAt(t).to,r=Math.max(i.from,e-ds),o=Math.min(s,t+ds),a=n.state.sliceDoc(r,o);if(r!=i.from){for(let l=0;la.length-ds;l--)if(!ps.test(a[l-1])&&ps.test(a[l])){a=a.slice(0,l);break}}return K.announce.of(`${n.state.phrase("current match")}. ${a} ${n.state.phrase("on line")} ${i.number}.`)}const eS=K.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),tS=[_t,oi.low(Yb),eS];class rh{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class di{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let s=i.facet(Kt).markerFilter;s&&(e=s(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new It,a=[],l=0,c=i.doc.iter(),h=0,u=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!a.length)break;let m,g;if(a.length)m=l,g=a.reduce((b,C)=>Math.min(b,C.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>u)break;g=p.to,a.push(p),d++}for(;db.from||b.to==m))a.push(b),d++,g=Math.min(b.to,g);else{g=Math.min(b.from,g);break}}g=Math.min(g,u);let y=!1;if(a.some(b=>b.from==m&&(b.to==g||g==u))&&(y=m==g,!y&&g-m<10)){let b=m-(h+c.value.length);b>0&&(c.next(b),h=m);for(let C=m;;){if(C>=g){y=!0;break}if(!c.lineBreak&&h+c.value.length>C)break;C=h+c.value.length,h+=c.value.length,c.next()}}let x=Zd(a);if(y)o.add(m,m,I.widget({widget:new lS(x),diagnostics:a.slice()}));else{let b=a.reduce((C,Q)=>Q.markClass?C+" "+Q.markClass:C,"");o.add(m,g,I.mark({class:"cm-lintRange cm-lintRange-"+x+b,diagnostics:a.slice(),inclusiveEnd:a.some(C=>C.to>g)}))}if(l=g,l==u)break;for(let b=0;b{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new rh(s,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new rh(i.from,r,i.diagnostic)}}),i}function Qd(n,e){let t=e.pos,i=e.end||t,s=n.state.facet(Kt).hideOn(n,t,i);if(s!=null)return s;let r=n.startState.doc.lineAt(e.pos);return!!(n.effects.some(o=>o.is(Cr))||n.changes.touchesRange(r.from,Math.max(r.to,i)))}function iS(n,e){return n.field(gt,!1)?e:e.concat(Y.appendConfig.of(Ud))}function Pd(n,e){return{effects:iS(n,[Cr.of(e)])}}const Cr=Y.define(),Cd=Y.define(),Td=Y.define(),gt=Te.define({create(){return new di(I.none,null,null)},update(n,e){if(e.docChanged&&n.diagnostics.size){let t=n.diagnostics.map(e.changes),i=null,s=n.panel;if(n.selected){let r=e.changes.mapPos(n.selected.from,1);i=Ni(t,n.selected.diagnostic,r)||Ni(t,null,r)}!t.size&&s&&e.state.facet(Kt).autoPanel&&(s=null),n=new di(t,s,i)}for(let t of e.effects)if(t.is(Cr)){let i=e.state.facet(Kt).autoPanel?t.value.length?rr.open:null:n.panel;n=di.init(t.value,i,e.state)}else t.is(Cd)?n=new di(n.diagnostics,t.value?rr.open:null,n.selected):t.is(Td)&&(n=new di(n.diagnostics,n.panel,t.value));return n},provide:n=>[Vi.from(n,e=>e.panel),K.decorations.from(n,e=>e.diagnostics)]}),nS=I.mark({class:"cm-lintRange cm-lintRange-active"});function sS(n,e,t){let{diagnostics:i}=n.state.field(gt),s,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(l,c,{spec:h})=>{if(e>=l&&e<=c&&(l==c||(e>l||t>0)&&(eKd(n,t,!1)))}const oh=n=>{let e=n.state.field(gt,!1);return!e||!e.panel?!1:(n.dispatch({effects:Cd.of(!1)}),!0)},rS=xe.fromClass(class{constructor(n){this.view=n,this.timeout=-1,this.set=!0;let{delay:e}=n.state.facet(Kt);this.lintTime=Date.now()+e,this.run=this.run.bind(this),this.timeout=setTimeout(this.run,e)}run(){clearTimeout(this.timeout);let n=Date.now();if(nPromise.resolve(i(this.view))),i=>{this.view.state.doc==e.doc&&this.view.dispatch(Pd(this.view.state,i.reduce((s,r)=>s.concat(r))))},i=>{ze(this.view.state,i)})}}update(n){let e=n.state.facet(Kt);(n.docChanged||e!=n.startState.facet(Kt)||e.needsRefresh&&e.needsRefresh(n))&&(this.lintTime=Date.now()+e.delay,this.set||(this.set=!0,this.timeout=setTimeout(this.run,e.delay)))}force(){this.set&&(this.lintTime=Date.now(),this.run())}destroy(){clearTimeout(this.timeout)}});function oS(n,e,t){let i=[],s=-1;for(let r of n)r.then(o=>{i.push(o),clearTimeout(s),i.length==n.length?e(i):s=setTimeout(()=>e(i),200)},t)}const Kt=Z.define({combine(n){return{sources:n.map(e=>e.source).filter(e=>e!=null),...yt(n.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:ah,tooltipFilter:ah,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,s,r)=>e(i,s,r)||t(i,s,r):e:t,autoPanel:(e,t)=>e||t})}}});function ah(n,e){return n?e?(t,i)=>e(n(t,i),i):n:e}function aS(n,e={}){return[Kt.of({source:n,config:e}),rS,Ud]}function $d(n){let e=[];if(n)e:for(let{name:t}of n){for(let i=0;ir.toLowerCase()==s.toLowerCase())){e.push(s);continue e}}e.push("")}return e}function Kd(n,e,t){var i;let s=t?$d(e.actions):[];return he("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},he("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(n):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let a=!1,l=d=>{if(d.preventDefault(),a)return;a=!0;let p=Ni(n.state.field(gt).diagnostics,e);p&&r.apply(n,p.from,p.to)},{name:c}=r,h=s[o]?c.indexOf(s[o]):-1,u=h<0?c:[c.slice(0,h),he("u",c.slice(h,h+1)),c.slice(h+1)],f=r.markClass?" "+r.markClass:"";return he("button",{type:"button",class:"cm-diagnosticAction"+f,onclick:l,onmousedown:l,"aria-label":` Action: ${c}${h<0?"":` (access key "${s[o]})"`}.`},u)}),e.source&&he("div",{class:"cm-diagnosticSource"},e.source))}class lS extends Ut{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return he("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class lh{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Kd(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class rr{constructor(e){this.view=e,this.items=[];let t=s=>{if(!(s.ctrlKey||s.altKey||s.metaKey)){if(s.keyCode==27)oh(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=$d(r.actions);for(let a=0;a{for(let r=0;roh(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(gt).selected;if(!e)return-1;for(let t=0;t{for(let h of c.diagnostics){if(o.has(h))continue;o.add(h);let u=-1,f;for(let d=i;di&&(this.items.splice(i,u-i),s=!0)),t&&f.diagnostic==t.diagnostic?f.dom.hasAttribute("aria-selected")||(f.dom.setAttribute("aria-selected","true"),r=f):f.dom.hasAttribute("aria-selected")&&f.dom.removeAttribute("aria-selected"),i++}});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:a,panel:l})=>{let c=l.height/this.list.offsetHeight;a.topl.bottom&&(this.list.scrollTop+=(a.bottom-l.bottom)/c)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(gt),i=Ni(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:Td.of(i)})}static open(e){return new rr(e)}}function Cs(n,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(n)}')`}function ms(n){return Cs(``,'width="6" height="3"')}const cS=K.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:ms("#f11")},".cm-lintRange-warning":{backgroundImage:ms("orange")},".cm-lintRange-info":{backgroundImage:ms("#999")},".cm-lintRange-hint":{backgroundImage:ms("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function hS(n){return n=="error"?4:n=="warning"?3:n=="info"?2:1}function Zd(n){let e="hint",t=1;for(let i of n){let s=hS(i.severity);s>t&&(t=s,e=i.severity)}return e}class Md extends Mt{constructor(e){super(),this.diagnostics=e,this.severity=Zd(e)}toDOM(e){let t=document.createElement("div");t.className="cm-lint-marker cm-lint-marker-"+this.severity;let i=this.diagnostics,s=e.state.facet(Tr).tooltipFilter;return s&&(i=s(i,e.state)),i.length&&(t.onmouseover=()=>fS(e,t,i)),t}}function uS(n,e){let t=i=>{let s=e.getBoundingClientRect();if(!(i.clientX>s.left-10&&i.clientXs.top-10&&i.clientYe.getBoundingClientRect()}}})}),e.onmouseout=e.onmousemove=null,uS(n,e)}let{hoverTime:s}=n.state.facet(Tr),r=setTimeout(i,s);e.onmouseout=()=>{clearTimeout(r),e.onmouseout=e.onmousemove=null},e.onmousemove=()=>{clearTimeout(r),r=setTimeout(i,s)}}function dS(n,e){let t=Object.create(null);for(let s of e){let r=n.lineAt(s.from);(t[r.from]||(t[r.from]=[])).push(s)}let i=[];for(let s in t)i.push(new Md(t[s]).range(+s));return H.of(i,!0)}const pS=zu({class:"cm-gutter-lint",markers:n=>n.state.field(ha),widgetMarker:(n,e,t)=>{let i=[];return n.state.field(ha).between(t.from,t.to,(s,r,o)=>{s>t.from&&si.is(il)?i.value:t,n)},provide:n=>yr.from(n)}),mS=K.baseTheme({".cm-gutter-lint":{width:"1.4em","& .cm-gutterElement":{padding:".2em"}},".cm-lint-marker":{width:"1em",height:"1em"},".cm-lint-marker-info":{content:Cs('')},".cm-lint-marker-warning":{content:Cs('')},".cm-lint-marker-error":{content:Cs('')}}),gS=Lu(sS,{hideOn:Qd}),Ud=[gt,K.decorations.compute([gt],n=>{let{selected:e,panel:t}=n.field(gt);return!e||!t||e.from==e.to?I.none:I.set([nS.range(e.from,e.to)])}),gS,cS],Tr=Z.define({combine(n){return yt(n,{hoverTime:300,markerFilter:null,tooltipFilter:null})}});function OS(n={}){return[Tr.of(n),ha,pS,mS,Ed]}const Fd=1,Ue=Object.freeze({ready:"studio.ready",documentOpen:"document.open",documentReplace:"document.replace",documentChanged:"document.changed",documentSave:"document.save",documentSetReadOnly:"document.setReadOnly",documentResources:"document.resources",editorInsert:"editor.insert",editorFormat:"editor.format",editorSetTheme:"editor.setTheme",editorGetState:"editor.getState",diagnosticsPublish:"diagnostics.publish"});function yS(n,e={},t=null,i=null){return{protocolVersion:Fd,type:n,documentID:t,...i===null?{}:{sessionID:i},payload:e}}function AS(n){if(window.WKWebViewJavascriptBridge){n(window.WKWebViewJavascriptBridge);return}if(window.WKWVJBCallbacks){window.WKWVJBCallbacks.push(n);return}window.webkit?.messageHandlers?.iOS_Native_InjectJavascript&&(window.WKWVJBCallbacks=[n],window.webkit.messageHandlers.iOS_Native_InjectJavascript.postMessage(null))}function nn(n,e,t={},i=null,s=()=>{},r=null){if(!n){s({result:"unavailable"});return}n.callHandler(e,yS(e,t,i,r),s)}function bS(n){const e={capabilities:["jsx","format","search","completion","diagnostics"]};nn(n,Ue.ready,e)}const SS=[{id:"$storage.getString",arguments:["key"],returns:"string",documentation:"Read a package-scoped string. Missing keys return an empty string."},{id:"$storage.setString",arguments:["key","value"],returns:"boolean",documentation:"Set a package-scoped string, limited to 256 KiB of UTF-8. Check the success result."},{id:"$storage.getJSON",arguments:["key"],returns:"json",documentation:"Read a package-scoped JSON object. Missing or invalid values return an empty object."},{id:"$storage.setJSON",arguments:["key","value"],returns:"boolean",documentation:"Store a valid JSON object, limited to 256 KiB encoded. Check the success result."},{id:"$storage.compareAndSetString",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a string only when it still matches expected. A missing key matches an empty string. Conflicts return false; reread and retry a bounded number of times. Requires the shared storage container."},{id:"$storage.compareAndSetJSON",arguments:["key","expected","value"],returns:"boolean",minimumRuntimeVersion:"1.3",documentation:"Atomically replace a JSON object if its current value equals expected, independent of property order. A missing key matches an empty object. Wrong types and conflicts return false. Requires the shared storage container."},{id:"$storage.remove",arguments:["key"],returns:"boolean",documentation:"Remove a key from this package only."},{id:"$storage.keys",arguments:[],returns:"string[]",documentation:"List keys in this package's namespace."},{id:"$storage.clear",arguments:[],returns:"boolean",documentation:"Clear this package's storage. Other packages are unaffected."}].map(n=>({minimumRuntimeVersion:"1.0",...n,preview:"initialState"})),xS=[{id:"$notifications.status",group:"notifications",value:{authorization:"authorized"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.pending",group:"notifications",value:[],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"read",mock:"editable"},{id:"$notifications.schedule",group:"notifications",value:{key:"daily",status:"scheduled"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$notifications.cancel",group:"notifications",value:{key:"daily",status:"cancellationRequested"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeNotifications.swift",operation:"write",mock:"editable"},{id:"$health.dailyStatistics",group:"health",value:{metric:"steps",unit:"count",aggregation:"sum",timeZone:"UTC",items:[{date:"2026-01-01",value:6840,hasSamples:!0}]},platforms:["ios"],authorization:"healthRead",notes:"Runtime 1.6. Read-only daily HealthKit statistics on installed iPhone/iPad widgets. Declare health and minimumRuntimeVersion 1.6, review Health access in native Settings. No separate System Access toggle. Missing readings are null/hasSamples false and cannot establish read denial. No raw samples, persistence or queries in future/Live Activity presentations. Preview fixtures never access real Health data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHealth.swift",operation:"read",mock:"editable"},{id:"$calendar.create",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$calendar.update",group:"calendar",value:{id:"sample.event",calendarID:"sample.calendar",status:"applied",replayed:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data. Calendar writes need calendar and calendarWrite; updates are limited to events this installation created.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeCalendar.swift",operation:"write",mock:"editable"},{id:"$weather.forecast",group:"weather",value:{provider:"MET Norway",attribution:{text:"Weather data from MET Norway",url:"https://www.met.no/en/free-meteorological-data/Download-services"},latitude:37.33,longitude:-122.01,fetchedAt:"2026-01-01T12:00:00Z",isStale:!1,hours:[{time:"2026-01-01T12:00:00Z",temperatureC:21,windMetersPerSecond:2,precipitationMM:0,condition:"partlycloudy_day"}]},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeWeather.swift",operation:"read",mock:"editable"},{id:"$alarms.status",group:"alarms",value:{authorization:"authorized"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.pending",group:"alarms",value:[],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"read",mock:"editable"},{id:"$alarms.schedule",group:"alarms",value:{key:"focus",status:"scheduled",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.cancel",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.stop",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.pause",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$alarms.resume",group:"alarms",value:{key:"focus",status:"requested"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["key"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeAlarms.swift",operation:"write",mock:"editable"},{id:"$documents.list",group:"documents",value:[{id:"550e8400-e29b-41d4-a716-446655440000",name:"Sample.json",type:"json",bytes:17},{id:"550e8400-e29b-41d4-a716-446655440001",name:"Sample.csv",type:"csv",bytes:24}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readJSON",group:"documents",value:{goal:12,done:7},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$documents.readCSV",group:"documents",value:{headers:["day","value"],rows:[["Monday","7"],["Tuesday","9"]],truncated:!1},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["id"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeDocuments.swift",operation:"read",mock:"editable"},{id:"$contacts.selected",group:"contacts",value:[{id:"sample.contact",name:"Alex Example",organization:"Sample",phones:["+1 202 555 0100"],emails:["alex@example.com"]}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeContacts.swift",operation:"read",mock:"editable"},{id:"$maps.search",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.geocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["address"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.reverseGeocode",group:"maps",value:[{name:"Example Park",address:"Sample address",latitude:37.33,longitude:-122.01}],platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$maps.snapshot",group:"maps",value:{image:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQIHWP4z8DwHwAFgAI/ScLbtAAAAABJRU5ErkJggg==",width:256,height:256,provider:"Apple Maps"},platforms:["ios","macos"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeMaps.swift",operation:"read",mock:"editable"},{id:"$home.items",group:"home",value:[{id:"sample.light",name:"Living Room Lamp",kind:"power",value:!0,isCached:!0,metric:"power",unit:"boolean"},{id:"scene-sample",name:"Evening",kind:"scene",value:null,isCached:!0,metric:"scene",unit:"none"}],platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:[],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"read",mock:"editable"},{id:"$home.setPower",group:"home",value:{id:"sample.light",value:!0,status:"acknowledged"},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"},{id:"$home.runScene",group:"home",value:{id:"scene-sample",status:"acknowledged",replayed:!1},platforms:["ios"],authorization:"systemAccess",notes:"Runtime 1.6. Installed widgets require manifest permission, explicit native System Access, system authorization where applicable, an active installation and bounded queries. Writes require a user action; future timelines and Live Activities cannot call this API. Web and CLI fixtures never access real device data.",arguments:["options"],asynchronous:!0,minimumRuntimeVersion:"1.6",nativeSource:"Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntimeHome.swift",operation:"write",mock:"editable"}],ua="2026-01-01T00:00:00Z",Vt="2026-01-01T12:00:00Z",ho=(n,e)=>({value:n,unit:e,hasSamples:!0,start:ua,end:Vt}),ch=(n,e,t)=>Object.entries(e).map(([i,s])=>({id:`$${n}.${i}`,group:n,value:s,legacy:[t,i]})),vS=[{id:"$music.isAvailable",group:"music",value:!0},{id:"$music.authorizationStatus",group:"music",value:"authorized"},{id:"$music.current",group:"music",value:{provider:"appleMusic",state:"playing",hasItem:!0,title:"Morning Light",artist:"ScriptWidget Sessions",album:"Focus",duration:224,position:86,capturedAt:Vt}},{id:"$services.status",group:"services",value:"connected"},{id:"$services.profile",group:"services",value:{service:"github",subject:"42",username:"octocat",displayName:"Mona",publicRepositories:32,privateRepositories:8,followers:128,following:24}},...ch("device",{screen:{width:390,height:844,scale:3},language:"en",model:"iPhone",name:"My iPhone",battery:{level:.8,state:"unplugged"},systemVersion:"26.0",isdarkmode:!1,totalDiskSpace:128e9,freeDiskSpace:64e9},"device"),...ch("system",{appInfo:{name:"ScriptWidget",bundleId:"com.everettjf.scriptwidget",version:"27.1.2",build:"27012"},locale:"en_US",preferredLanguages:["en-US"],timeZone:{identifier:"UTC",abbreviation:"GMT",offsetSeconds:0},is24HourClock:!1,calendarInfo:{identifier:"gregorian",firstWeekday:1,minimumDaysInFirstWeek:1},systemUptime:3600,memory:{physical:8589934592},thermalState:"nominal",lowPowerMode:!1,brightness:.5,reduceMotionEnabled:!1,platform:"ios",hostName:"My iPhone",processName:"ScriptWidgetWidget",osVersionString:"Version 26.0",processorCount:6,activeProcessorCount:6},"system"),{id:"$photos.isAvailable",group:"photos",value:!0},{id:"$photos.authorizationStatus",group:"photos",value:"authorized"},{id:"$photos.requestAuthorization",group:"photos",value:!0},{id:"$photos.items",group:"photos",value:{status:"ready",items:[{id:"sample.photo",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiu08cKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fbPe3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDQK/QnooooGFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9uKKKK7TxwooooAKKKKACiiigAooooAKKKKACs/VNUsNGsX1HUpBFDGMkn+Q9Sewqtruvab4c099S1STYi8AfxMeyqO5NfInjDxnqfi++865Pl26H91CDwo9T6t6mhs5cTiVSXmX/ABx49v8Axdc+UmYbKM/u4vX/AGm9T+g/U6/w38fv4buRpOqMTYynr18pj3H+ye4/H1z5TRU3PHVean7S+p+gSOkiCSMhlYZBHIIPcU6vmn4YfEL+zXTw5rb/AOjscQyN/wAsyf4Sf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igAooooAKKKKACiiigAooooAKKKKACvePgx8bNT+Gl8NN1Hdc6PM2ZIurRE9Xjz39V6H2PNeD0UjSlWlSkpwdmftNo+saZr+mQ6xo0y3FtcLvjkQ5BH9COhB5B4NaVflf8IPjJrHww1LyZN1zpU7Znt88g9N8eejDuOjDg9iP038P+INH8UaRDrmhTrcWs67kdf1BHUEdCDyDUNWPrsFjo4mPZ9Uf//S+tKKKK6z8/CiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACmSSRwxtLKwVVGSTwABSTTRW8TTzsERBkseABXhHi3xfLrchsrIlLVT9C5Hc+3oPz9nGNzOpVUFdkvi/xjJrDmw08lbVTyehkI7n29B+ftwNFFbJWPNnNyd2FFFFMkKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvWvhP8W9b+F+r+bBm40+dh9otieG7bk/uuB379D2x5LRSLp1JU5KcHZo//0/rSiiius/PwooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtYWublgiIMsx6AU26ureyt3urpwkaDJY14H4q8V3GvzeTDmO1Q/Kvdvdv8O1OMbmVWqoIk8WeLZtdlNrbZS1Q8Du59T/AEFcXRRWyVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/9T60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKKKKACq15eW2n2z3d44SNBkk0y/v7XTbV7y9cJGg5J/kPU18/eJfE114hucnKW6H5I/6n1P8qqMbmVWqoLzJPFHim58QXGxcx2yH5E9fdvf+VcpRRWqVjzpScndhRRRTJCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9X60ooorrPz8KKKKACiiigAooooAKKKKACiiigAooooAKo6jqNppVo17etsRfzJ9B6mm6pqlnpFm17ettReg7k+gHrXz34h8Q3niC786c7Y1+5GOij+p9TVRjcxq1lBeY/xH4ku/EN1vk+SFD8kfYe59TXOUUVqedKTbuwooopiCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9b60oqRYZX+4pP0FWV03UX+5byH6Kf8K6z4CzKVFay6Drj/AHLKc/SNv8KsJ4V8Tv8Ac026P0hf/CgfJLsYNFdOngvxc/TTbn8Y2H8xVhPAHjN+mnTfiMfzoH7KfZnIUV3C/Dbxu/TT3/FkH82qyvws8dt/y44+skf/AMVQV7Cp/K/uPPqK9JT4S+OG62yL9ZE/oTVlfg94zbqkK/WQf0BosP6vU/lZ5bRXra/Bjxc3V7Zfq7f0U1YX4JeKD9+4tR/wJz/7JRYf1Wr/ACnjlZmravZaLZte3rYUcADqx9BXpXjnwZH8PNCfXPEeoQKv3Y4k3GSV/wC6gIH4noB1r4t1vXL3Xrw3V2cAcIg6KPQf1PeqjG5y4mTo+7Jaj9e1+91+8NzcnCDhEHRR/j6msOiitTy223dhRRRTEFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/Z",width:384,height:256},{id:"sample.photo.2",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/ayiiivVAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD/9D9rKKKK9UAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/0f2sooor1QCiiigAooooAKKKKACiiigAooooAKKKKACiq15eWun2r3t7IsUUY3MzHAApbW6tr62S8tHEkUqhlZeQQaduoFiiiikAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQB/9L9rKKKK9UAooooAKKKKACiiigAooooAKKKKACs/VdVsNFsZNS1OQRQxjJJ/kB3J7Cquva/pnhvTn1PVJNiLwAPvMeyqO5P+eK+P/GPjTU/GF9510fLt0P7qEHhR6n1Y9zXRRoOo/Iyq1VD1L3jrx9f+MLrykzDZRn93F6/7T+p/QdvU7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igAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigApGZUUu5wBySe1NkkSJDJIQqqMkngADua+f8Axv46fWGbStJYrag4Zuhk/wDsf51dOm5uyJbsT+OPHbamX0jR2xbDh5B1k9h/s/z+leV0UV6UIKKsjJu4UUUVYgooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACvoL4IfHTVfhdfjTNS3XWiztmSHq0RPWSPPf1Xo3sea+faKzq0o1IuE1oVGbi+aJ+5Gi61pXiLS4Na0SdLm1uF3xyIcgj+hHQg8g8HmtSvyU+DHxs1r4Vap5Em660i4bM9tnkHp5keeA47jow4PYj9UPDviPRfFmjQa/4fnW5tbhdyOv6gjqCDwQeQa+ZxeElQl5Hq0ayqLzP//S+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACo5ZYoI2mmYIiDLMTgADuaSeeG2ha4uGCIgyzHgACvnbxp42m1+Q2NgSlmp+hkI7n29B+J9tKVJzdkTKViXxt44k1x203TSUtFPJ6GQjuf9n0H4n284oor0oxUVZGLdwoooqgCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAr2H4QfGLXvhTrPm2+bjTZ2H2m1J4btvT+64Hfv0PbHj1FROEZxcZrQcZOLuj//T+oKKKK+zPKCiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKgubm3s7d7q6cRxxjLMegFNu7y2sLZ7y8cRxxjLMe1fN/jDxlc+JJ/IgzHaIflTux/vN7+g7VpSpObJlKxL4y8aXHiKY2lpmOzQ8L0Lkd2/oK4OiivSjFRVkYt3CiiiqAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//1PqCiiivszygooooAKKKKACiiigAooooAKKKKACiiigAooooAKqX19aabave3riOKMZJP+etN1HUbPSrN76/cRxoOSf5D1J9K+afFfiy88TXeTmO2Q/u4/6t6n+XataVJzfkTKViXxd4vu/EtzsTMdrGfkj9f9pvf+VcbRRXoxioqyMW7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/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/byiiiu09MKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fave3sgiijG5mY4AFOtbq3vbZLu0cSR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Ftry+/S36kVFFFcx+ZhRRRQBLBIYZklHVWB/KvV68ogjM0yRDqzAfnXq9dNDqfpnh/zcle+14/frf9Aooorc/RAooooAKKKKAP/U/byiiiu09MKKKKACiiigAooooAK4Dxx49sPCNr5SYmvZB+7i9P8Aaf0H6n8zWd4++Itr4XibTtOIlv2HTqsYPdvf0H4njr8qXl5dahcve3shllkO5mY5JNdVDD83vS2NYU76sn1TVL/Wb59R1KQyzSHJY/yHoB2FZ9FFeilbY6AooooAKKKKACiiigCSGaW3lWeBijoQysDggjoQa+s/h349i8U2n2G/IW/hX5h08xR/EP6j+lfJFW7G+u9MvI7+xcxzRHcrDqDWVWkqisROPMj75orhvA3jW08X6duOI7uIATR/+zL/ALJ/TpXc15couLszlatowoooqQCiiigAooooAKKKKACiiigAoor5v+OXx2svh5av4f8ADzLPrUq/VbdSOGf1b+6v4njAOlOnKpLlgioU3N8sS58bfjlp/wANrJtH0crca1MvyJ1WEHo8nv8A3V79Tx14j4Z/GOx+IsK2eq7bfWEX94g4WbA++nv/AHl7dRx0+Ab+/vdUvZdR1GVp552LySOcszHkkk0y0u7mxuY7yykaKWJgyOpwykdCCK9eeWQlS5Hv3FnPDtLMsI8LN2e6fZ/5H6wUV4f8HfixB47iXw/rDLFq6D5QcKLgDunbeO6/iOMge6yQTQnEqMp9xivmq1CdGThNH4HmeS4vLqjpYqm1br0foyKipY4JpjiJGY+wzXRWHh2aRhJffIv90dT/AIVnGLexngMpxWOkoYeDfn0Xqw8O2DSTfbpB8qcL7n/61drTI40iQRxjao4AFPrshHlVj9pyXKoZbho4eDu92+7CiiiqPWCiiigAooooA//V/byiiiu09MKKKKACiiigArxz4h/EuLQw+jaEwe8PDydVi/xb+Xf0rK+InxPFr5mheGpMy8rLOv8AD6qh9fU9u3PT50JLEsxyTXbQw9/embU6fVj5ZZZ5WmnYu7klmY5JJ6kmo6KK7jcKKKKACiiigAooooAKKKKACiiigDU0bWL/AEHUY9U019ksZ/AjuCO4Pevsjwl4qsPFulr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UUUUAFFFFABRRRQAUUUUAFFFFAH//U+uKKKK+oPoAooooAKKKKACiiigAooooAKKKKACiiigAooooAKq3t7a6daveXjhI0GST/AJ602/v7TTLR729cJGg5J/kPUmvnXxR4pu/EdzzmO3Q/u4/6n1P8q0p03M1pUnN+RJ4q8V3XiK42LmO2Q/Inr/tN7/yrkaKK7UklZHfGKirIKKKKoYUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9X64ooor6g+gCiiigAooooAKKKKACiiigAooooAKKKKACqGpalZ6TZtfXz7I1/Mn0A7k03VdVstGs2vr59qL0Hcn0A7mvnLxH4jvfEV558/yxL/AKuMdFH9T6mtadPm9DWlSc/Qk8S+JrzxHd+ZJ8kKH93H2HufU1zNFFdqSSsjvSSVkFFFFMYUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//1vriipFilf7ik/QVZXTtQf7kEh+in/CvqD6ApUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf/AApcy7iuYNFdOngvxc/TTbn8Y2H8xVhfAPjJ+mnTfiMfzpc8e4XRyFFdwvw38bv009/xZB/NqsL8LfHbf8uOPrJH/wDFUvaR7hzLuef0V6Svwl8cN1tkX6yJ/Q1ZX4P+M26pCv1kH9AaXtYdxc67nltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AAJz/wCyUvbw7hzx7njlZesaxY6JZNe3zYUcADqx9APWvSvHfg6P4daE+u+JNQgVfuxxJuMkr/3UBAz7noB1r4j13Xr7xBem7vDgDhEHRR6D+p710UIqpqtjejT9pr0JPEHiC+8Q3hubo7UXhIx0Uf4+prBoorvStojvSS0QUUUUxhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH//2Q==",width:384,height:256},{id:"sample.photo.4",image:"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAASABIAAD/4QBARXhpZgAATU0AKgAAAAgAAYdpAAQAAAABAAAAGgAAAAAAAqACAAQAAAABAAABgKADAAQAAAABAAABAAAAAAD/7QA4UGhvdG9zaG9wIDMuMAA4QklNBAQAAAAAAAA4QklNBCUAAAAAABDUHYzZjwCyBOmACZjs+EJ+/8AAEQgBAAGAAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/bAEMAAgICAgICBAICBAYEBAQGCAYGBgYICggICAgICgwKCgoKCgoMDAwMDAwMDA4ODg4ODhAQEBAQEhISEhISEhISEv/bAEMBAwMDBQQFCAQECBMNCw0TExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMTE//dAAQAGP/aAAwDAQACEQMRAD8A/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//Q/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigD//R/biiiiuc9UKKKKACiiigAooooAKKKKACiiigAooooAKKrXl5a6fave3sgiijG5mY4AFOtbq3vbZLu0cSRSAMrLyCDQO3UnooooEFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAf/9L9uKKKK5z1QooooAKKKKACiiigAooooAKKKKACs/VNUsNGsX1HUpBFDGMkn+Q9Sewqtruvab4c099S1STYi8AfxMeyqO5NfInjDxnqfi+9865PlwIf3UIPCj1Pq3qaaR0UKDqPyL3jjx5f+LrrykzDZRn93Fnr/tN6n9B+p2Phv4/fw3cjStUYmxlbr18pj3H+ye4/Ed8+U0U7HqOlFx5LaH6BI6SoJIyGVhkEcgg9xTq+afhh8Q/7MdPDmtv/AKMxxDIx/wBWT/CT/dPb0+nT6WqTyKtJ05WYUUUUGQUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFRTzw20LXFwwREGWY9AKlrxX4i6+9xd/2HbtiOLBkx/E3UD6Afr9K78twEsbWVGO3V9kcOY46ODoutLfou7DX/iLeXDtb6H+5jHHmEZZvoDwB+v0rzu5vr28YvdzPKT3Zif51Vor9KwmAoYWPLRjbz6/efnOKx9bEy5q0r+XT7i1bX17ZsHtJniI7qxH8q9E0D4i3lu62+ufvozx5gGGX6gcEfr9a8xooxeAoYqPLWjfz6/eGFx9bDS5qMreXT7j6zgnhuYVuLdg6OMqw6EVLXivw6197e7/sO4bMcuTHn+FupH0I/X617VX5rmWAlgqzoy26Puj9Gy7HRxlFVo79V2YUUUVwHcFFFFABRRRQB//T/biiiiuc9UKKKKACiiigAooooAKKKKACub8T+KdL8Kaeb7UWyx4jjH3nPoP6ntVPxh4z03whY+dc/vLhx+6hB5Y+p9FHc18h67r2peItQf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RQAUUUUAFFFFABRRRQAUUUUAFFFFABXrvwk+L2ufCzWPNt83GnTsPtNqTw3ben91wO/foe2PIqKDOpTjUi4TV0f/T+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACobi4gtIHublwkaDLMegFNu7u2sbZ7u7cRxoMsx7V87+LfF9z4in8iHMdoh+VO7H+839B2pN2NqNF1H5EvjDxjP4gmNra5jtEPC93I7t/QVw1FFZtnqwgorliFFFFIsKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooA//9T60ooorI+1CiiigAooooAKKKKACiiigAooooAKKKKACiiigAqre3trp1q95euI40GST/nrTNQ1C00u0e9vnCRoOSf5D1Jr5y8U+KrvxJdZOY7dD+7j/qfU/wAqTdjejRdR+RL4r8WXXiO52LmO1Q/Inr/tN7/yrkKKKzPVjFRVkFFFFIoKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP//V+tKKKKyPtQooooAKKKKACiiigAooooAKKKKACiiigAqhqep2ekWb318+yNPzJ9AO5NM1XVrLRbJr6/fai9B3Y9gB3NfN/iPxJe+I7zz7j5Yl/wBXGOij+p9TUt2OihQdR+RJ4m8T3niO78yT5IEP7uPsPc+prmaKKg9SMVFWQUUUUigooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKACiiigAooooAKKKKAP/W+tKKkWKV/uKT9BVlNO1CT7kEjfRT/hWR9rcpUVqpoWuP9yznP0jb/CrK+FvE7/c066P0hf8AwoFzLuYNFdMvgvxc/TTbn8Y2H8xVlfAPjJ+mnTfiMfzoF7SPc5Ciu4X4b+N36ae/4sg/masL8LfHb/8ALjj6yR//ABVIXtYfzI8/or0lPhL44brbIv1kT+hqynwf8Zt1SFfrIP6A0C9tD+ZHltFetL8GPFzdXt1+rt/RTVlfgl4oP37i1H/AnP8A7JQL6xT/AJjxysrWNZsdDsmvr5sKOAB1Y+gHrXpXjvwfF8OdBfXfEmoQKv3Yok3GSV/7qAgZ9z0A618Q69r194gvTd3hwBwiDoo9B/U96TdjrwtNVveWw/xB4hvvEV6bm6O1F4SMdFH+PqawaKKg9dJJWQUUUUhhRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFABRRRQAUUUUAFFFFAH/9k=",width:384,height:256}],unavailableCount:0,fetchedAt:Vt,source:"system",stale:!1}},{id:"$calendar.isAvailable",group:"calendar",value:!0},{id:"$calendar.authorizationStatus",group:"calendar",value:"authorized"},{id:"$calendar.requestAuthorization",group:"calendar",value:!0},{id:"$calendar.calendars",group:"calendar",value:[{id:"sample.personal",title:"Personal"}]},{id:"$calendar.events",group:"calendar",value:{status:"ready",items:[{id:"sample.event",calendarID:"sample.personal",title:"Read and recharge",start:"2026-01-01T15:00:00Z",end:"2026-01-01T15:30:00Z",allDay:!1}],fetchedAt:Vt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.isAvailable",group:"reminders",value:!0},{id:"$reminders.authorizationStatus",group:"reminders",value:"authorized"},{id:"$reminders.requestAuthorization",group:"reminders",value:!0},{id:"$reminders.lists",group:"reminders",value:[{id:"sample.reminders",title:"Personal"}]},{id:"$reminders.items",group:"reminders",value:{status:"ready",items:[{id:"sample.reminder",listID:"sample.reminders",title:"Read a chapter",due:"2026-01-01T16:00:00Z",hasTime:!0,completed:!1,completedAt:null,priority:0}],fetchedAt:Vt,source:"system",stale:!1,truncated:!1}},{id:"$reminders.create",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.update",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$reminders.setCompleted",group:"reminders",value:{id:"sample.reminder",listID:"sample.reminders",status:"applied",replayed:!1}},{id:"$health.authorizationStatus",group:"health",value:"notDisclosed"},{id:"$health.sleepSummary",group:"health",value:{start:ua,end:Vt,timeZone:"UTC",hasSamples:!0,totalSleepSeconds:27e3,inBedSeconds:30600,awakeSeconds:1800,stages:{unspecified:0,core:16200,deep:5400,rem:5400},sourceCount:1,truncated:!1,conflictSeconds:0,aggregation:"union-awake-rem-deep-core-unspecified"}},{id:"$health.activitySummary",group:"health",value:{date:"2026-01-01",timeZone:"UTC",hasSamples:!0,moveMode:"activeEnergy",move:{value:480,goal:600,unit:"kcal"},exercise:{value:26,goal:30,unit:"min"},stand:{value:9,goal:12,unit:"count"}}},{id:"$health.workouts",group:"health",value:{start:ua,end:Vt,timeZone:"UTC",hasSamples:!0,truncated:!1,items:[{id:"550e8400-e29b-41d4-a716-446655440000",activity:"running",start:"2026-01-01T09:00:00.000Z",end:"2026-01-01T09:45:00.000Z",duration:2700,energyKcal:285,distanceMeters:5200}]}},{id:"$health.isAvailable",group:"health",value:!0},{id:"$health.requestAuthorization",group:"health",value:!0,legacy:["health"]},{id:"$health.stepCountToday",group:"health",value:ho(6840,"count"),legacy:["health.stepCountToday"]},{id:"$health.activeEnergyToday",group:"health",value:ho(420,"kcal"),legacy:["health.activeEnergyToday"]},{id:"$health.heartRateLatest",group:"health",value:ho(72,"bpm"),legacy:["health.heartRateLatest"]},{id:"$location.isAvailable",group:"location",value:!0},{id:"$location.authorizationStatus",group:"location",value:"authorizedWhenInUse"},{id:"$location.isAuthorizedForWidgetUpdates",group:"location",value:!0},{id:"$location.requestAuthorization",group:"location",value:!0,legacy:["location.authorization"]},{id:"$location.current",group:"location",value:{latitude:37.3349,longitude:-122.009,altitude:0,accuracy:10,verticalAccuracy:10,speed:-1,course:-1,timestamp:Vt,accuracyAuthorization:"full",age:0,isStale:!1},legacy:["location"]}],wS={music:{platforms:["ios"],authorization:"musicRead",notes:"Runtime 1.4. Read-only Music app playback, not every audio player. Requires an installed owner, music permission and Music library approval in native Settings. current() is asynchronous and returns provider, state, hasItem, nullable title/artist/album/duration/position and capturedAt. State may be playing while details are absent (Home Sharing). Native player access is main-thread-only: synchronous hosts prepare one snapshot before JSC waits; background previews capture on the main queue. No playback/queue mutation, scans, artwork, credential or subscription inference. No live queries in future entries/Live Activities. Main system-player API is unavailable on macOS; Web supplies editable samples, never actual device access."},services:{platforms:["ios","macos"],authorization:"serviceAccount",notes:"Runtime 1.4: status(service) and profile(service) are asynchronous. Only provider: github. Unknown providers reject with service_operation. Requires an installed owner and services permission. profile additionally requires network and api.github.com in networkDomains, a native connected GitHub account and explicit owner grant. Native Settings handles credentials; scripts cannot log in or obtain tokens. profile returns service, subject, username, displayName, publicRepositories, privateRepositories, followers and following (missing values are null). No live queries in future entries or Live Activities. Eight shared data queries; native requests also share the eight concurrent/32 total network budget, while Web uses its existing preview network budget. Web uses editable best-state samples only; it never authenticates or sends these requests."},photos:{platforms:["ios","macos"],authorization:"photosRead",notes:"Requires photos permission and explicit native photo/album selection (none by default). Limited Photos authorization is supported. items({limit:1..4,offset:0..63,maxAgeSeconds:0..86400}) returns bounded, metadata-stripped JPEG thumbnails as image data URLs. Four 768px / 128KiB thumbnails at most; private snapshots expire after 24h and are rechecked against current access, selected sources and asset revisions. Cloud-only items report unavailableCount; download them in Photos first. Future timeline/Live Activity presentations read matching snapshots only. Web uses editable sample data and photosSelection IDs; no actual library access."},reminders:{platforms:["ios","macos"],authorization:"remindersRead",notes:"Requires reminders in widget.json and full system Reminders access. Reads require native Settings selected lists. create/update/setCompleted additionally require remindersWrite and a native declared action, stable requestID, durable replay receipts and an unchanged selected list. Web writes update preview-only items/receipts; receipt identities are derived from that state, with configurable API errors. Use lists() for IDs. items() selects pending due dates or completed completion dates in a positive window of at most 31 days, up to 50 items. Undated pending reminders are excluded. remindersSelection mocks the user scope without granting permission."},calendar:{platforms:["ios","macos"],authorization:"calendarRead",notes:"Requires calendar in widget.json and full system Calendar access. The user's native Settings source selection limits metadata, events and cached snapshots; scripts cannot enlarge it. Use calendars() for permitted IDs and show setup when no sources are selected. Queries are read-only, limited to 31 days and 50 items. Preview calendarSelection simulates this scope without granting package permission."},device:{platforms:["ios","macos"],authorization:"none",notes:"Device values depend on hardware. Some legacy Mac values are placeholders; inspect the API documentation before using them as measurements."},system:{platforms:["ios","macos"],authorization:"none",notes:"System metadata, not whole-device CPU, FPS or network traffic monitoring. Hardware-specific values may be unavailable."},health:{platforms:["ios"],authorization:"healthRead",notes:"Read-only HealthKit. Request access in the app. Runtime 1.4 adds sleepSummary (up to 7 days / 256 samples, union with explicit stage-conflict precedence), activitySummary (one local Gregorian day including active-energy or move-time mode and optional goals), and workouts (up to 31 days / 50 fully-contained summaries, optional kcal/meters). These require an explicit health manifest; all share the query budget and cannot run in future/Live Activity presentations. No Health readings are persisted by the API. Authorization completion does not reveal whether individual read types were granted; empty results must not be labelled permission denied. API 1.3 readings add hasSamples: false means no readable samples, never a read-denial verdict. Existing value/unit/start/end fields remain."},location:{platforms:["ios"],authorization:"locationWhenInUse",notes:"Package 2.0 requires location permission. Request system access in the app. Widgets also require isAuthorizedForWidgetUpdates. Cache is rechecked against authorization and precision, discarded after 24 hours or revocation, and reports age/isStale."}},kS=[...vS.map(n=>{const e=n.id.split(".")[1],t=n.group==="music"&&e==="current"||n.group==="services"||["calendar","reminders","photos"].includes(n.group)&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="health"&&!["isAvailable","authorizationStatus"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e),i=n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)||n.group==="location"&&["current","requestAuthorization"].includes(e)||["calendar","reminders","photos"].includes(n.group)&&["events","items"].includes(e);return{...n,...wS[n.group],minimumRuntimeVersion:["music","services","reminders","photos"].includes(n.group)||n.group==="health"&&["sleepSummary","activitySummary","workouts"].includes(e)?"1.4":["calendar"].includes(n.group)||["$health.authorizationStatus","$location.isAuthorizedForWidgetUpdates"].includes(n.id)?"1.3":"1.0",arguments:n.group==="services"?["service"]:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?["options"]:i?["options?"]:[],...n.group==="reminders"&&["create","update","setCompleted"].includes(e)?{authorization:"remindersWrite"}:{},asynchronous:t,nativeSource:`Shared/ScriptWidgetRuntime/Widget/API/ScriptWidgetRuntime${n.group[0].toUpperCase()}${n.group.slice(1)}.swift`,operation:n.group==="reminders"&&["create","update","setCompleted"].includes(e)?"write":e==="requestAuthorization"?"authorization":["isAvailable","authorizationStatus","isAuthorizedForWidgetUpdates"].includes(e)?"availability":"read",mock:"editable"}}),...xS],$e={globalProperties:{background:{type:"color",documentation:"Background color, hex value, or named color."},backgroundMaterial:{type:"enum",values:["none","ultraThin","thin","regular","thick","ultraThick"],documentation:"Runtime API 1.4. Public SwiftUI frosted material inside the widget, not Home Screen wallpaper blur or system Liquid Glass. At most four material backgrounds per tree. background supplies an opaque-composited Reduce Transparency fallback. In accented/vibrant mode local material is omitted for system rendering; none keeps the ordinary background."},color:{type:"color",documentation:"Foreground color, hex value, or named color."},font:{type:"enum",values:["largeTitle","title","title2","title3","headline","subheadline","body","callout","footnote","caption","caption2"],documentation:"Semantic text style."},fontWeight:{type:"enum",values:["ultraLight","thin","light","regular","medium","semibold","bold","heavy","black"],documentation:"Font weight."},fontDesign:{type:"enum",values:["default","rounded","serif","monospaced"],documentation:"Font design."},frame:{type:"number|string",documentation:'Square size (64 or "64"), width,height ("64,48"), or flexible frame ("max", "max,48").'},padding:{type:"number|string",documentation:"Padding amount or edge description."},corner:{type:"number",documentation:"Corner radius."},opacity:{type:"number",documentation:"Opacity from 0 through 1."},alignment:{type:"enum",values:["center","leading","trailing","top","bottom","topLeading","topTrailing","bottomLeading","bottomTrailing","firstTextBaseline","lastTextBaseline"],documentation:"Layout alignment."},clip:{type:"enum",values:["circle","rect","capsule","ellipse"],documentation:"Clip the view to a shape."},rotation:{type:"number",documentation:"Rotation in degrees."},rotation3d:{type:"string",documentation:"Static degree,x,y,z rotation with four finite numbers and a nonzero axis. Invalid values are ignored; axis magnitude is normalized. Reduce Motion removes the tilt. This does not read device motion or provide parallax."},shadow:{type:"string",documentation:"Shadow color, radius, and offset description."},animation:{type:"string",documentation:"iOS public SwiftUI scheduled clock/swing effect. Mac renders static standard-clock poses; other effects remain at rest. Signed clockCustom intervals specify a half-turn (full cycle = 2 * abs(interval)), minimum magnitude 0.25 seconds. App previews can animate; WidgetKit decides cadence and may freeze. Reduced motion/luminance freezes standard clock poses and keeps custom/swing effects at rest. Dynamic scripts are not rerun on animation ticks."},widgetAccentable:{type:"boolean",documentation:"Group this view into the accent layer in tinted and vibrant widget appearances."},linkurl:{type:"url",documentation:"Widget deep link URL."}},components:{VStack:{documentation:"Arrange children vertically.",children:!0,properties:{spacing:{type:"number"}}},HStack:{documentation:"Arrange children horizontally.",children:!0,properties:{spacing:{type:"number"}}},ZStack:{documentation:"Overlay children.",children:!0,properties:{}},VGrid:{documentation:"Vertical lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["leading","center","trailing"]}}},HGrid:{documentation:"Horizontal lazy grid.",children:!0,properties:{columns:{type:"string",required:!0},spacing:{type:"number"},alignment:{type:"enum",values:["top","center","bottom","firstTextBaseline","lastTextBaseline"]}}},Text:{documentation:"Display text content.",children:!1,properties:{text:{type:"string"}}},Date:{documentation:"Display a formatted date.",children:!1,properties:{date:{type:"date|number",required:!0},style:{type:"enum",values:["time","date","relative","offset","timer"]}}},Image:{documentation:"Display a bundled, remote, or SF Symbol image.",children:!1,properties:{systemName:{type:"string"},name:{type:"string"},id:{type:"string",deprecated:"Use name."},url:{type:"url"},src:{type:"url",deprecated:"Use url."},ratio:{type:"number"},mode:{type:"enum",values:["fit","fill"]},accentedRenderingMode:{type:"enum",values:["accented","desaturated","accentedDesaturated","fullColor"],documentation:"Control how the image is rendered in tinted and clear widget appearances."}}},Gif:{documentation:"Display a bounded package GIF using system decoding: up to 8 MiB input and 1,048,576 canvas pixels. iOS retains at most 60 downsampled frames / 4 MiB decoded pixels; more frames fall back to the first frame. Mac, Reduce Motion and reduced luminance use a static first frame. Active iOS previews use public SwiftUI timing with variable frame delays. Snapshots, inactive scenes, Mac and accessibility fallbacks use the first frame. No private clock bridge or continuous WidgetKit guarantee.",children:!1,properties:{file:{type:"string",required:!0}}},Spacer:{documentation:"Flexible layout space.",children:!1,properties:{minLength:{type:"number"}}},Rect:{documentation:"Rectangle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},RoundedRect:{documentation:"Filled rounded rectangle.",children:!1,properties:{radius:{type:"number"}}},Capsule:{documentation:"Capsule shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Ellipse:{documentation:"Ellipse shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Circle:{documentation:"Circle shape.",children:!1,properties:{trim:{type:"number|string"},stroke:{type:"string"}}},Gauge:{documentation:"Display a gauge or instrument.",children:!1,properties:{type:{type:"string"},value:{type:"number"},style:{type:"enum",values:["circular","linear"]},text:{type:"string"},current:{type:"string"},min:{type:"string"},max:{type:"string"},angle:{type:"number"},thickness:{type:"number"},needleColor:{type:"color"},label:{type:"string"},title:{type:"string"},sections:{type:"string"}}},Chart:{documentation:"Render chart data.",children:!1,availability:{ios:"16.0",macos:"26.0"},properties:{type:{type:"enum",values:["bar","bar-x","bar-y","bar-gantt","line","point","line-point","area","rect","rule-x"]},data:{type:"json",required:!0},category:{type:"boolean"},hideLegend:{type:"boolean"},hideXAxis:{type:"boolean"},hideYAxis:{type:"boolean"}}},Link:{documentation:"Open a URL when selected.",children:!0,properties:{url:{type:"url",required:!0}}},Divider:{documentation:"Horizontal or vertical separator.",children:!1,properties:{thickness:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Line:{documentation:"Fixed-length line.",children:!1,properties:{thickness:{type:"number"},length:{type:"number"},axis:{type:"enum",values:["horizontal","vertical"]}}},Icon:{documentation:"SF Symbol icon.",children:!1,properties:{systemName:{type:"string",required:!0},size:{type:"number"}}},Label:{documentation:"Text paired with an SF Symbol.",children:!1,properties:{title:{type:"string"},systemName:{type:"string",required:!0}}},Progress:{documentation:"Linear or circular progress.",children:!1,properties:{value:{type:"number",required:!0},total:{type:"number"},label:{type:"string"},style:{type:"enum",values:["linear","circular"]},trackColor:{type:"color"},thickness:{type:"number"}}},Ring:{documentation:"Circular progress ring.",children:!1,properties:{value:{type:"number",required:!0},thickness:{type:"number"},trackColor:{type:"color"}}},Badge:{documentation:"Compact status badge.",children:!1,properties:{text:{type:"string"},radius:{type:"number"}}},Chip:{documentation:"Outlined metadata chip.",children:!1,properties:{text:{type:"string"},radius:{type:"number"},borderColor:{type:"color"}}},Stat:{documentation:"Title, value, and subtitle statistic.",children:!1,properties:{title:{type:"string"},value:{type:"string",required:!0},subtitle:{type:"string"},mutedColor:{type:"color"}}},Button:{documentation:"Interactive widget button. Use actionID to share a declared Package 2.0 action with Siri, Shortcuts, and Control Widgets.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["action","onClick","actionID"],properties:{action:{type:"enum",values:["reload"],conflicts:["actionID"]},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",conflicts:["action","onClick"]}}},Toggle:{documentation:"Interactive widget toggle. A declared actionID requires a package-relative storage stateKey.",children:!0,availability:{interactiveIos:"17.0"},requiredAny:["onClick","actionID"],properties:{on:{type:"boolean",required:!0},onClick:{type:"function",conflicts:["actionID"]},actionID:{type:"action-id",requires:["stateKey"],conflicts:["onClick"]},stateKey:{type:"storage-key",requires:["actionID"]}}}},functions:{...Object.fromEntries(SS.map(n=>[n.id,n])),...Object.fromEntries(kS.map(n=>[n.id,{documentation:n.notes,minimumRuntimeVersion:n.minimumRuntimeVersion,arguments:n.arguments,returns:n.asynchronous?"Promise":typeof n.value=="object"?"json":typeof n.value}])),"$icloud.readJSON":{documentation:"Read cached JSON and revision; conflicts preserve all heads. Requires icloud permission and a native connection. Never certifies upload.",arguments:["name"],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.writeJSON":{documentation:"Save a new immutable JSON revision locally from a user action. Requires the revision from readJSON. Background exchange is eventual.",arguments:["name","value","expectedRevision"],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.resolveJSON":{documentation:"Explicitly resolve all observed conflicting heads into a new revision. Stale tokens fail; originals remain.",arguments:["name","value","expectedRevision"],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.sync":{documentation:"Exchange materialized revisions with iCloud; requires a user action. Upload completion is unknown.",arguments:[],returns:"Promise",minimumRuntimeVersion:"1.5"},"$icloud.status":{documentation:"Read native connection state. In the app, explicitly connect packages to separate stores for isolation or the same store ID to share JSON documents. Scripts cannot choose store IDs. Sync is eventual; local $storage is not migrated. Web uses preview mocks.",arguments:[],returns:"Promise",minimumRuntimeVersion:"1.5"},"$file.exists":{documentation:"Return whether a regular file is locally present inside this package, including binary assets. Missing files, directories, unsafe paths and links return false. Does not download iCloud files or read outside the package. Web preview uses workspace file presence.",arguments:["path"],returns:"boolean",minimumRuntimeVersion:"1.3"},"$file.read":{documentation:"Read package-relative UTF-8 text. Missing or unavailable files return an empty string.",arguments:["path"],returns:"string"},"$file.readJSON":{documentation:"Read a package-relative JSON object.",arguments:["path"],returns:"json"},fetch:{documentation:"Perform a network request and return its response text. Existing HTTP methods keep this string result."},"$http.getResponse":{documentation:"GET response metadata: {status, body, headers}. Headers are limited to content-type, cache-control, expires, last-modified, date and retry-after (lowercase; each at most 2048 UTF-8 bytes). Network permissions, public-host policy, redirects, body limits and timeline restrictions still apply. HTTP error statuses resolve; transport errors reject.",arguments:["url","options?"],returns:"Promise",minimumRuntimeVersion:"1.3"},importJS:{documentation:"Import a package-relative JavaScript file."},"$dataSource.request":{documentation:"Call a declared Data Source Plugin operation. Requires Package 2.0 plugins, network permission, and networkDomains declarations.",arguments:["pluginID","operationID","parameters"],returns:"Promise"},"$xml.parse":{documentation:"Parse up to 256 KiB of XML into {name, attributes, text, children}. DTDs and external entities are rejected; depth and node limits apply.",arguments:["source"],returns:"XMLNode"}}};function QS(n,e){const t=Object.entries(e.properties??{}).filter(([,s])=>s.required).map(([s,r])=>`${s}=${r.type.includes("number")||r.type==="boolean"?"{${}}":'"${}"'}`).join(" "),i=t?` ${t}`:"";return e.children?`<${n}${i}> \${} -`:`<${n}${i} />`}const ah=Object.entries($e.components).map(([n,e])=>({label:n,type:"class",detail:`ScriptWidget · ${Object.keys(e.properties??{}).length} properties`,info:e.documentation,apply:SS(n,e)}));function xS(n){const e=n.match(/<([A-Za-z][\w]*)\b([^<>]*)$/);return!e||e[2].includes(">")?null:{name:e[1],attributes:e[2]}}function vS(n,e){const t=$e.components[n];return t?Object.entries({...$e.globalProperties,...t.properties??{}}).filter(([i])=>!e.has(i)).map(([i,s])=>({label:i,type:"property",detail:s.required?`${s.type} · required`:s.type,info:s.deprecated?`Deprecated: ${s.deprecated}`:s.documentation,apply:`${i}=${s.type.includes("number")||s.type==="boolean"?"{${}}":'"${}"'}`})):[]}function wS(n){const e=n.match(/<([A-Za-z][\w]*)\b[^<>]*\b([A-Za-z][\w]*)\s*=\s*["']([^"']*)$/);if(!e)return null;const t=$e.components[e[1]]?.properties?.[e[2]]??$e.globalProperties[e[2]];return t?.values?{typed:e[3],values:t.values}:null}function kS(n){const e=n.state.doc.sliceString(Math.max(0,n.pos-1200),n.pos),t=wS(e);if(t)return{from:n.pos-t.typed.length,options:t.values.map(o=>({label:o,type:"enum"})),validFor:/^[\w-]*$/};const i=n.matchBefore(/<[A-Za-z]*$/);if(i)return{from:i.from+1,options:ah,validFor:/^[A-Za-z]*$/};const s=xS(e);if(s&&/(?:\s|^)\w*$/.test(s.attributes)){const o=n.matchBefore(/[A-Za-z][\w]*$/),a=new Set([...s.attributes.matchAll(/\b([A-Za-z][\w]*)\s*=/g)].map(l=>l[1]));return{from:o?.from??n.pos,options:vS(s.name,a),validFor:/^[A-Za-z][\w]*$/}}const r=n.matchBefore(/\$[A-Za-z]+\.[A-Za-z]*$/);if(r){const o=r.text.slice(0,r.text.indexOf(".")+1),a=Object.entries($e.functions).filter(([l])=>l.startsWith(o));return a.length?{from:r.from+o.length,options:a.map(([l,c])=>({label:l.slice(o.length),type:"function",detail:c.returns,info:c.documentation})),validFor:/^[A-Za-z]*$/}:null}return n.explicit?{from:n.pos,options:ah,validFor:/^[A-Za-z]*$/}:null}function lh(n,e){const t=[];for(let i=n.node.firstChild;i;i=i.nextSibling)i.name===e&&t.push(i);return t}function Md(n){const e=[];return Ce(n).iterate({enter(t){if(t.name!=="JSXOpenTag"&&t.name!=="JSXSelfClosingTag")return;const s=lh(t,"JSXIdentifier")[0];s&&e.push({name:n.doc.sliceString(s.from,s.to),from:s.from,to:s.to,attributes:lh(t,"JSXAttribute").map(r=>{const o=r.firstChild;return o?{name:n.doc.sliceString(o.from,o.to),from:o.from,to:o.to}:null}).filter(Boolean)})}}),e}function Ed(n){const e=[];for(const t of Md(n.state)){const i=$e.components[t.name];if(!i)continue;const s=new Set([...Object.keys($e.globalProperties),...Object.keys(i.properties??{})]),r=new Set(t.attributes.map(o=>o.name));for(const o of t.attributes){s.has(o.name)||e.push({from:o.from,to:o.to,severity:"warning",message:`“${o.name}” is not supported by <${t.name}>.`});const a=i.properties?.[o.name]??$e.globalProperties[o.name];a?.deprecated&&e.push({from:o.from,to:o.to,severity:"warning",message:`${o.name} is deprecated. ${a.deprecated}`})}for(const[o,a]of Object.entries(i.properties??{}))if(a.required&&!r.has(o)&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires the “${o}” property.`}),r.has(o)){for(const l of a.requires??[])r.has(l)||e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> “${o}” requires the “${l}” property.`});for(const l of a.conflicts??[])r.has(l)&&o cannot combine “${o}” with “${l}”.`})}i.requiredAny?.length&&!i.requiredAny.some(o=>r.has(o))&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires one of: ${i.requiredAny.map(o=>`“${o}”`).join(", ")}.`})}return e}function QS(n,e){const t=Md(n.state).find(s=>e>=s.from&&e<=s.to);if(!t)return null;const i=$e.components[t.name];return i?{pos:t.from,end:t.to,above:!0,create(){const s=document.createElement("div");s.className="studio-hover";const r=document.createElement("strong");r.textContent=`<${t.name}>`;const o=document.createElement("p");return o.textContent=i.documentation,s.append(r,o),{dom:s}}}:null}const ch={light:{background:"#FAFAFC",foreground:"#202124",gutter:"#F3F3F6",gutterText:"#8A8A93",activeLine:"#EDEEF3",selection:"#B9D7FF",caret:"#0067C0"},dark:{background:"#1E1F22",foreground:"#E8E8ED",gutter:"#191A1D",gutterText:"#777982",activeLine:"#292A2F",selection:"#315A85",caret:"#65B7FF"}};function PS(n,e){return $.theme({"&":{height:"100%",color:n.foreground,backgroundColor:n.background,fontSize:"13px"},".cm-scroller":{fontFamily:'ui-monospace, "SFMono-Regular", Menlo, Monaco, Consolas, monospace',lineHeight:"1.58",overscrollBehavior:"contain"},".cm-content":{caretColor:n.caret,padding:"12px 0 32px"},".cm-line":{padding:"0 8px"},".cm-cursor, .cm-dropCursor":{borderLeftColor:n.caret},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:n.selection},".cm-activeLine":{backgroundColor:n.activeLine},".cm-gutters":{backgroundColor:n.gutter,color:n.gutterText,border:"none",paddingLeft:"env(safe-area-inset-left)"},".cm-activeLineGutter":{backgroundColor:n.activeLine,color:n.foreground},".cm-foldPlaceholder":{backgroundColor:"transparent",border:`1px solid ${n.gutterText}`,color:n.gutterText},".cm-tooltip":{border:e?"1px solid #41434A":"1px solid #D2D3D8",backgroundColor:e?"#292A2F":"#FFFFFF",borderRadius:"8px",overflow:"hidden",boxShadow:"0 8px 28px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete ul li[aria-selected]":{backgroundColor:e?"#315A85":"#DCEBFA",color:n.foreground},".cm-panels":{backgroundColor:n.gutter,color:n.foreground},".cm-searchMatch":{backgroundColor:e?"#725C1D":"#FFE69A"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:e?"#8D6D20":"#FFD45C"}},{dark:e})}const CS=Xn.define([{tag:[O.keyword,O.controlKeyword,O.moduleKeyword,O.operatorKeyword,O.bool,O.null],color:"#FF7AB2"},{tag:[O.string,O.special(O.string)],color:"#FF8170"},{tag:[O.number,O.regexp],color:"#D9C97C"},{tag:[O.comment,O.lineComment,O.blockComment],color:"#7F8C98",fontStyle:"italic"},{tag:[O.tagName,O.typeName,O.className],color:"#5DD8FF"},{tag:O.attributeName,color:"#B281EB"},{tag:[O.propertyName,O.function(O.variableName),O.function(O.propertyName)],color:"#67B7A4"},{tag:O.definition(O.variableName),color:"#4EB0CC"},{tag:[O.variableName,O.operator,O.punctuation,O.bracket],color:"#E8E8ED"},{tag:O.invalid,color:"#FF453A"}]);function Ud(n){const e=n==="dark";return[PS(e?ch.dark:ch.light,e),JO(e?CS:i0)]}const TS=Xt.parser.configure({dialect:"jsx"}),RS=new Map(Object.keys($e.components).map(n=>[n.toLowerCase(),n])),$S=new Set(["VStack","HStack","ZStack","VGrid","HGrid"]),KS=512*1024,ZS=512,MS=32,ci=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},hi=(n,e)=>n.slice(e.from,e.to),de=n=>{throw new Error(n)},Fd=n=>{let e=!0;const t=n.replace(/&([^;\s]+);/g,(i,s)=>{const r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};if(Object.hasOwn(r,s))return r[s];if(/^#(?:[0-9]+|x[0-9a-f]+)$/i.test(s)){const o=s[1].toLowerCase()==="x"?parseInt(s.slice(2),16):Number(s.slice(1));if(o>0&&o<=1114111&&!(o>=55296&&o<=57343))return String.fromCodePoint(o)}return e=!1,i});return e?t:void 0};function co(n,e=!1){if(e)return Fd(n.slice(1,-1));const t=n.trim();if(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(t)){const i=Number(t);return Number.isFinite(i)?i:void 0}if(t==="true"||t==="false")return t==="true";if(t.startsWith('"'))try{const i=JSON.parse(t);return typeof i=="string"?i:void 0}catch{}}function vi(n){const e={formatVersion:1,source:n,nodes:[],roots:[],issue:""};if(typeof n!="string"||new TextEncoder().encode(n).length>KS)return{...e,issue:"Layout editing supports source files up to 512 KiB."};const t=TS.parse(n);let i=!1;if(t.iterate({enter:r=>{r.type.isError&&(i=!0)}}),i)return{...e,issue:"Fix the JavaScript/JSX syntax before using Layout. Your source is preserved."};function s(r,o,a){(a>MS||e.nodes.length>=ZS)&&de("Layout editing supports up to 512 layers and 32 nesting levels.");const l=ci(r),c=l[0],h=l.at(-1),u=ci(c).find(S=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(S.name)),f=u?hi(n,u):"Fragment",d=RS.get(f.toLowerCase()),p=$e.components[d],m={...$e.globalProperties,...p?.properties??{}},g=c.name==="JSXOpenTag"&&h?.name==="JSXCloseTag",y=g?ci(h).find(S=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(S.name)):null;u&&g&&(!y||hi(n,y)!==f)&&de("Opening and closing JSX tags must match before using Layout.");const b={id:String(r.from),parentID:o,tag:f,component:d??null,from:r.from,to:r.to,openingEnd:c.to,insertAt:c.to-(g?1:2),contentFrom:c.to,contentTo:g?h.from:c.to,children:[],properties:[],locked:!p,structure:!1,text:null,textEditable:!1,depth:a};let x=!1;for(const S of ci(c)){if(S.name==="JSXSpreadAttribute"&&(x=!0),S.name!=="JSXAttribute")continue;const w=ci(S),U=hi(n,w[0]),F=w[2],V=F?co(hi(n,F),F.name==="JSXAttributeValue"):!0,E=F?.name==="JSXEscape"?co(n.slice(F.from+1,F.to-1)):V,M=Object.hasOwn(m,U)?m[U]:null;b.properties.push({name:U,value:E??null,from:S.from,to:S.to,editable:!!(p&&M&&M.type!=="function"&&E!==void 0),definition:M??null})}const C=new Set(b.properties.map(S=>S.name)).size!==b.properties.length;b.locked||=x||C,b.reason=x?"Spread properties are preserved; edit this element in Code.":C?"Duplicate properties are preserved; resolve them in Code.":p?"":"Custom components and fragments are preserved; edit them in Code.",b.locked&&b.properties.forEach(S=>{S.editable=!1}),e.nodes.push(b);const k=g?l.slice(1,-1):[];for(const S of k)S.name==="JSXElement"&&b.children.push(s(S,b.id,a+1).id);if(b.structure=!b.locked&&g&&$S.has(d)&&k.every(S=>S.name==="JSXElement"||S.name==="JSXText"&&!hi(n,S).trim())&&b.children.every(S=>!e.nodes.find(w=>w.id===S).locked),!b.locked&&d==="Text"&&g&&k.length===1){const S=k[0],w=hi(n,S),U=S.name==="JSXText"&&!/[\r\n]/.test(w)?Fd(w):S.name==="JSXEscape"?co(w.slice(1,-1)):void 0;typeof U=="string"&&(b.text=U,b.textEditable=!0)}return b}try{t.iterate({enter(r){if(r.name!=="CallExpression")return;const o=ci(r.node);if(o[0]?.name!=="VariableName"||hi(n,o[0])!=="$render"||o[1]?.name!=="ArgList")return;const a=ci(o[1]).filter(l=>!["(",")"].includes(l.name));if(a.length===1&&a[0].name==="JSXElement")return e.roots.push(s(a[0],null,0).id),!1}})}catch(r){return{...e,nodes:[],roots:[],issue:r.message}}return e.roots.length||(e.issue="Layout needs a direct $render(…) or another native JSX element. Variables, loops and functions stay editable in Code."),e}function ha(n){return!n?.component||n.locked?{}:{...$e.globalProperties,...$e.components[n.component]?.properties??{}}}function ES(n,e,t){(n.source!==e||n.issue)&&de("Layout changed. Select the layer again before editing.");const i=n.nodes.find(l=>l.id===t.id);(!i||i.locked)&&de("This layer is locked. Edit its source in Code.");let s=[],r=i.from;if(t.type==="property"){const l=ha(i),c=Object.hasOwn(l,t.name)?l[t.name]:null,h=i.properties.find(d=>d.name===t.name);(!c||c.type==="function"||h&&!h.editable)&&de("Dynamic or unsupported properties must be edited in Code.");const u=new Set(i.properties.map(d=>d.name)),f=$e.components[i.component];if(t.remove?(f.requiredAny?.includes(t.name)&&!f.requiredAny.some(d=>d!==t.name&&u.has(d))&&de("Keep at least one required component property."),Object.entries(f.properties??{}).some(([d,p])=>u.has(d)&&p.requires?.includes(t.name))&&de("Another property requires this value. Edit the dependent properties together in Code.")):(c.requires?.some(d=>!u.has(d))&&de("Add the required related properties together in Code."),(c.conflicts?.some(d=>u.has(d))||Object.entries(f.properties??{}).some(([d,p])=>d!==t.name&&u.has(d)&&p.conflicts?.includes(t.name)))&&de("This property conflicts with another component property.")),t.remove)(!h||c.required)&&de("This property cannot be removed."),s=[{from:h.from,to:h.to,insert:""}];else{const d=t.value;(!["string","number","boolean"].includes(typeof d)||typeof d=="number"&&!Number.isFinite(d)||typeof d=="string"&&d.length>8192)&&de("Use a bounded string, finite number or Boolean."),c.values&&!c.values.includes(d)&&de("Choose one of the supported property values."),c.type==="boolean"&&typeof d!="boolean"&&de("This property needs true or false."),c.type==="number"&&!(typeof d=="number"||typeof d=="string"&&d.trim()&&Number.isFinite(Number(d)))&&de("This property needs a number."),typeof d=="boolean"&&c.type!=="boolean"&&de("This property does not accept a Boolean."),typeof d=="number"&&!c.type.includes("number")&&de("This property needs a string value."),t.name==="opacity"&&!(Number(d)>=0&&Number(d)<=1)&&de("Opacity must be between zero and one.");const p=`${t.name}={${JSON.stringify(d)}}`;s=h?[{from:h.from,to:h.to,insert:p}]:[{from:i.insertAt,to:i.insertAt,insert:` ${p}`}]}}else if(t.type==="text")(!i.textEditable||typeof t.value!="string"||t.value.length>8192)&&de("Dynamic text is preserved. Edit it in Code."),s=[{from:i.contentFrom,to:i.contentTo,insert:`{${JSON.stringify(t.value)}}`}];else if(t.type==="move"||t.type==="remove")if(n.nodes.find(c=>c.id===i.parentID)?.structure||de("Only literal children of a supported stack/grid can be moved or removed."),t.type==="remove")s=[{from:i.from,to:i.to,insert:""}];else{const c=n.nodes.find(p=>p.id===t.parentID);(!c?.structure||c.from>=i.from&&c.to<=i.to)&&de("Choose a supported container outside this layer.");const h=p=>{for(;p.parentID!==null;)p=n.nodes.find(m=>m.id===p.parentID);return p.id};h(i)!==h(c)&&de("Layers cannot move between render branches or JavaScript scopes.");const u=c.children.filter(p=>p!==i.id),f=t.index;(!Number.isInteger(f)||f<0||f>u.length)&&de("Invalid layer position.");const d=f===u.length?c.contentTo:n.nodes.find(p=>p.id===u[f]).from;if(d===i.from||d===i.to)return{changes:[],selectedFrom:r};s=[{from:i.from,to:i.to,insert:""},{from:d,to:d,insert:e.slice(i.from,i.to)}],r=d-(d>i.to?i.to-i.from:0)}else if(t.type==="add"){i.structure||de("Choose a supported container with literal JSX children.");const l={text:'New text',spacer:"",stack:'',icon:''};Object.hasOwn(l,t.kind)||de("Unsupported new layer."),s=[{from:i.contentTo,to:i.contentTo,insert:l[t.kind]}],r=i.contentTo}else de("Unsupported layout operation.");s.sort((l,c)=>l.from-c.from);let o=e;for(const l of[...s].reverse())o=o.slice(0,l.from)+l.insert+o.slice(l.to);return vi(o).issue&&de("This edit would leave the supported layout. Your source was not changed."),{changes:s,selectedFrom:r}}const Dd=Xt.parser.configure({dialect:"jsx"}),Ci=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},Qe=n=>{throw new Error(n)},Hi=Object.freeze({background:{type:"color"},surface:{type:"color"},foreground:{type:"color"},muted:{type:"color"},accent:{type:"color"},titleFont:{values:$e.globalProperties.font.values},bodyFont:{values:$e.globalProperties.font.values},fontDesign:{values:$e.globalProperties.fontDesign.values},corner:{type:"number",maximum:48},padding:{type:"number",maximum:48},spacing:{type:"number",maximum:32}}),ms={titleFont:"headline",bodyFont:"caption",fontDesign:"rounded",corner:20,padding:16,spacing:10},sr=Object.freeze({Meadow:Object.freeze({...ms,background:"#F2FAF5",surface:"#FFFFFF",foreground:"#193F31",muted:"#607C70",accent:"#328963"}),Paper:Object.freeze({...ms,background:"#F4F7FD",surface:"#FFFFFF",foreground:"#243454",muted:"#687795",accent:"#4777D6"}),Peach:Object.freeze({...ms,background:"#FFF5EE",surface:"#FFFFFF",foreground:"#56392C",muted:"#967461",accent:"#C86B43"}),Midnight:Object.freeze({...ms,background:"#192332",surface:"#283548",foreground:"#F1F5FC",muted:"#AABAD0",accent:"#8EB7FF"})});function Ld(n,e){Object.hasOwn(Hi,n)||Qe("Unknown theme token.");const t=Hi[n];t.type==="color"&&!(typeof e=="string"&&/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i.test(e))&&Qe(`${n} needs a six or eight digit hex color.`),t.values&&!t.values.includes(e)&&Qe(`${n} needs a supported font value.`),t.type==="number"&&!(typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=t.maximum)&&Qe(`${n} needs a number from zero to ${t.maximum}.`)}function el(n){(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==Object.keys(Hi).length)&&Qe("A theme needs exactly the documented tokens.");for(const e of Object.keys(n))Ld(e,n[e]);return n}function Xd(n){(typeof n!="string"||new TextEncoder().encode(n).length>4096)&&Qe("Theme JSON is limited to 4 KiB.");const e=JSON.parse(n);return(!e||Array.isArray(e)||Object.keys(e).sort().join()!=="formatVersion,name,tokens"||e.formatVersion!==1||typeof e.name!="string"||!e.name.trim()||/[\u0000-\u001f]/.test(e.name)||new TextEncoder().encode(e.name).length>64)&&Qe("Use a version 1 theme with a name of at most 64 bytes."),el(e.tokens),e}function US(n,e="My theme"){const t=JSON.stringify({formatVersion:1,name:e,tokens:n},null,2);return Xd(t),t}function rr(n){const e={source:n,tokens:null,ranges:{},issue:"",canInitialize:!1};try{(typeof n!="string"||new TextEncoder().encode(n).length>512*1024)&&Qe("Theme editing supports files up to 512 KiB.");const t=Dd.parse(n),i=[],s=[];if(t.iterate({enter(l){l.type.isError&&Qe("Fix JavaScript syntax before editing the theme."),["VariableDefinition","VariableName"].includes(l.name)&&n.slice(l.from,l.to).includes("\\")&&Qe("Escaped identifiers stay in Code."),n.slice(l.from,l.to)==="widgetTheme"&&["VariableDefinition","VariableName"].includes(l.name)&&(l.name==="VariableDefinition"?i:s).push(l.node)}}),!i.length&&!s.length){const l=vi(n);e.canInitialize=!l.issue&&l.roots.length===1&&!l.nodes[0].locked;let c=!1;for(const h of Ci(t.topNode)){const u=h.firstChild;l.nodes[0]&&h.name==="ExpressionStatement"&&u?.name==="CallExpression"&&n.slice(u.firstChild.from,u.firstChild.to)==="$render"&&u.froml.nodes[0].to&&(c=!0)}return e.canInitialize&&=c,e}i.length!==1&&Qe("Keep one top-level const widgetTheme object. Other bindings stay in Code.");const r=i[0].parent,o=Ci(r);(r.name!=="VariableDeclaration"||r.parent?.name!=="Script"||o[0]?.name!=="const"||o[1]?.from!==i[0].from||o[2]?.name!=="Equals"||o[3]?.name!=="ObjectExpression"||o.slice(4).some(l=>l.name!==";"))&&Qe("Theme editing needs a single top-level const widgetTheme = { … } declaration.");const a={};for(const l of Ci(o[3])){if(["{","}",","].includes(l.name))continue;const c=Ci(l),h=c[0]?n.slice(c[0].from,c[0].to):"",u=c[0]?.name==="String"&&h.startsWith('"')?JSON.parse(h):h;(l.name!=="Property"||c.length!==3||!["PropertyDefinition","String"].includes(c[0].name)||c[1].name!==":"||!["String","Number"].includes(c[2].name)||Object.hasOwn(a,u))&&Qe("Theme tokens must be unique literal properties. Computed or dynamic values stay in Code.");let f;try{f=JSON.parse(n.slice(c[2].from,c[2].to))}catch{Qe("Theme values use JSON strings or numbers. Edit this declaration in Code.")}Ld(u,f),a[u]=f,e.ranges[u]={from:c[2].from,to:c[2].to}}el(a);for(const l of s){const c=l.parent,h=Ci(c),u=h[2]?n.slice(h[2].from,h[2].to):"";(c.name!=="MemberExpression"||h[0].from!==l.from||h[1]?.name!=="."||h[2]?.name!=="PropertyName"||!Object.hasOwn(Hi,u))&&Qe("Theme references must read widgetTheme.token. Other uses stay in Code."),c.parent?.name==="MemberExpression"&&Qe("Mutable theme references stay in Code.");for(let f=c.parent;f;f=f.parent)(["UpdateExpression","PostfixExpression"].includes(f.name)||f.name==="UnaryExpression"&&/^(?:delete|\+\+|--)/.test(n.slice(f.from,c.from).trim())||f.name==="AssignmentExpression"&&f.firstChild.from<=c.from&&f.firstChild.to>=c.to||f.name==="ForOfSpec"||f.name==="ForInSpec")&&Qe("Mutable theme references stay in Code.")}e.tokens=a}catch(t){e.issue=t.message}return e}function ho(n,e,t){return(n.source!==e||n.issue||!n.tokens)&&Qe("Theme changed or is unsupported. Reopen Theme before editing."),el(t),{changes:Object.keys(Hi).filter(s=>t[s]!==n.tokens[s]).map(s=>({...n.ranges[s],insert:JSON.stringify(t[s])})).sort((s,r)=>s.from-r.from)}}function FS(n,e="Meadow"){(!rr(n).canInitialize||!Object.hasOwn(sr,e))&&Qe("Start with a literal top-level layout without an existing widgetTheme binding.");const i=vi(n),s=i.nodes[0],r=[];function o(c,h,u,f=!1){const d=c.properties.find(m=>m.name===h);if(c.locked||d&&!d.editable||!d&&!f)return;const p=`${h}={widgetTheme.${u}}`;r.push(d?{from:d.from,to:d.to,insert:p}:{from:c.insertAt,to:c.insertAt,insert:` ${p}`})}for(const c of["background","corner","padding"])o(s,c,c,!0);s.structure&&o(s,"spacing","spacing",!0);for(const c of i.nodes)if(c.component==="Text"){const h=c.properties.find(f=>f.name==="font")?.value,u=["headline","largeTitle","title","title2","title3"].includes(h);o(c,"font",u?"titleFont":"bodyFont",!0),o(c,"color",u?"foreground":"muted",!0),o(c,"fontDesign","fontDesign",!0)}else c.component==="Icon"&&o(c,"color","accent",!0);let a=0;for(const c of Ci(Dd.parse(n).topNode))if(!(c.name==="LineComment"||c.name==="BlockComment"))if(c.name==="ExpressionStatement"&&c.firstChild?.name==="String")a=c.to;else break;r.push({from:a,to:a,insert:` -const widgetTheme = ${JSON.stringify(sr[e],null,2)}; -`}),r.sort((c,h)=>c.from-h.from);let l=n;for(const c of[...r].reverse())l=l.slice(0,c.from)+c.insert+l.slice(c.to);return(!rr(l).tokens||vi(l).issue)&&Qe("This layout cannot be themed automatically. Your source was preserved."),{changes:r}}function Bd(n){if(!Array.isArray(n)||n.length>4096)return[];const e=new Map,t=new Set;for(const i of n){if(typeof i!="string"||new TextEncoder().encode(i).length>1024||/[\\\u0000-\u001f\u007f-\u009f]/.test(i))continue;const s=i.split("/");if(s.length!==2||s[0]!=="image"||!s[1]||new TextEncoder().encode(s[1]).length>255||s[1]!==s[1].trim()||s[1].includes("..")||!/\.(png|jpe?g|webp)$/i.test(s[1]))continue;const r=i.normalize("NFC").toLowerCase();e.has(r)&&e.get(r)!==i&&t.add(r),e.set(r,i)}return[...e].filter(([i])=>!t.has(i)).map(([,i])=>i).sort().slice(0,256)}const tl=z.define(),or=Te.define({create:()=>[],update(n,e){for(const t of e.effects)t.is(tl)&&(n=Bd(t.value));return n}});function il(n,e){n.state.field(or,!1)!==void 0&&n.dispatch({effects:tl.of(e)})}const Id=Object.freeze({bloom:Object.freeze({name:"Bloom mark",description:"A small four-petal flower",kind:"icon"}),leaf:Object.freeze({name:"Leaf mark",description:"A tilted leaf and stem",kind:"icon"}),pebble:Object.freeze({name:"Pebble friend",description:"A quiet, round-eared companion",kind:"pet"})}),uo=`/* +`:`<${n}${i} />`}const hh=Object.entries($e.components).map(([n,e])=>({label:n,type:"class",detail:`ScriptWidget · ${Object.keys(e.properties??{}).length} properties`,info:e.documentation,apply:QS(n,e)}));function PS(n){const e=n.match(/<([A-Za-z][\w]*)\b([^<>]*)$/);return!e||e[2].includes(">")?null:{name:e[1],attributes:e[2]}}function CS(n,e){const t=$e.components[n];return t?Object.entries({...$e.globalProperties,...t.properties??{}}).filter(([i])=>!e.has(i)).map(([i,s])=>({label:i,type:"property",detail:s.required?`${s.type} · required`:s.type,info:s.deprecated?`Deprecated: ${s.deprecated}`:s.documentation,apply:`${i}=${s.type.includes("number")||s.type==="boolean"?"{${}}":'"${}"'}`})):[]}function TS(n){const e=n.match(/<([A-Za-z][\w]*)\b[^<>]*\b([A-Za-z][\w]*)\s*=\s*["']([^"']*)$/);if(!e)return null;const t=$e.components[e[1]]?.properties?.[e[2]]??$e.globalProperties[e[2]];return t?.values?{typed:e[3],values:t.values}:null}function RS(n){const e=n.state.doc.sliceString(Math.max(0,n.pos-1200),n.pos),t=TS(e);if(t)return{from:n.pos-t.typed.length,options:t.values.map(o=>({label:o,type:"enum"})),validFor:/^[\w-]*$/};const i=n.matchBefore(/<[A-Za-z]*$/);if(i)return{from:i.from+1,options:hh,validFor:/^[A-Za-z]*$/};const s=PS(e);if(s&&/(?:\s|^)\w*$/.test(s.attributes)){const o=n.matchBefore(/[A-Za-z][\w]*$/),a=new Set([...s.attributes.matchAll(/\b([A-Za-z][\w]*)\s*=/g)].map(l=>l[1]));return{from:o?.from??n.pos,options:CS(s.name,a),validFor:/^[A-Za-z][\w]*$/}}const r=n.matchBefore(/\$[A-Za-z]+\.[A-Za-z]*$/);if(r){const o=r.text.slice(0,r.text.indexOf(".")+1),a=Object.entries($e.functions).filter(([l])=>l.startsWith(o));return a.length?{from:r.from+o.length,options:a.map(([l,c])=>({label:l.slice(o.length),type:"function",detail:c.returns,info:c.documentation})),validFor:/^[A-Za-z]*$/}:null}return n.explicit?{from:n.pos,options:hh,validFor:/^[A-Za-z]*$/}:null}function uh(n,e){const t=[];for(let i=n.node.firstChild;i;i=i.nextSibling)i.name===e&&t.push(i);return t}function Dd(n){const e=[];return Ce(n).iterate({enter(t){if(t.name!=="JSXOpenTag"&&t.name!=="JSXSelfClosingTag")return;const s=uh(t,"JSXIdentifier")[0];s&&e.push({name:n.doc.sliceString(s.from,s.to),from:s.from,to:s.to,attributes:uh(t,"JSXAttribute").map(r=>{const o=r.firstChild;return o?{name:n.doc.sliceString(o.from,o.to),from:o.from,to:o.to}:null}).filter(Boolean)})}}),e}function Ld(n){const e=[];for(const t of Dd(n.state)){const i=$e.components[t.name];if(!i)continue;const s=new Set([...Object.keys($e.globalProperties),...Object.keys(i.properties??{})]),r=new Set(t.attributes.map(o=>o.name));for(const o of t.attributes){s.has(o.name)||e.push({from:o.from,to:o.to,severity:"warning",message:`“${o.name}” is not supported by <${t.name}>.`});const a=i.properties?.[o.name]??$e.globalProperties[o.name];a?.deprecated&&e.push({from:o.from,to:o.to,severity:"warning",message:`${o.name} is deprecated. ${a.deprecated}`})}for(const[o,a]of Object.entries(i.properties??{}))if(a.required&&!r.has(o)&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires the “${o}” property.`}),r.has(o)){for(const l of a.requires??[])r.has(l)||e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> “${o}” requires the “${l}” property.`});for(const l of a.conflicts??[])r.has(l)&&o cannot combine “${o}” with “${l}”.`})}i.requiredAny?.length&&!i.requiredAny.some(o=>r.has(o))&&e.push({from:t.from,to:t.to,severity:"error",message:`<${t.name}> requires one of: ${i.requiredAny.map(o=>`“${o}”`).join(", ")}.`})}return e}function $S(n,e){const t=Dd(n.state).find(s=>e>=s.from&&e<=s.to);if(!t)return null;const i=$e.components[t.name];return i?{pos:t.from,end:t.to,above:!0,create(){const s=document.createElement("div");s.className="studio-hover";const r=document.createElement("strong");r.textContent=`<${t.name}>`;const o=document.createElement("p");return o.textContent=i.documentation,s.append(r,o),{dom:s}}}:null}const fh={light:{background:"#FAFAFC",foreground:"#202124",gutter:"#F3F3F6",gutterText:"#8A8A93",activeLine:"#EDEEF3",selection:"#B9D7FF",caret:"#0067C0"},dark:{background:"#1E1F22",foreground:"#E8E8ED",gutter:"#191A1D",gutterText:"#777982",activeLine:"#292A2F",selection:"#315A85",caret:"#65B7FF"}};function KS(n,e){return K.theme({"&":{height:"100%",color:n.foreground,backgroundColor:n.background,fontSize:"13px"},".cm-scroller":{fontFamily:'ui-monospace, "SFMono-Regular", Menlo, Monaco, Consolas, monospace',lineHeight:"1.58",overscrollBehavior:"contain"},".cm-content":{caretColor:n.caret,padding:"12px 0 32px"},".cm-line":{padding:"0 8px"},".cm-cursor, .cm-dropCursor":{borderLeftColor:n.caret},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, ::selection":{backgroundColor:n.selection},".cm-activeLine":{backgroundColor:n.activeLine},".cm-gutters":{backgroundColor:n.gutter,color:n.gutterText,border:"none",paddingLeft:"env(safe-area-inset-left)"},".cm-activeLineGutter":{backgroundColor:n.activeLine,color:n.foreground},".cm-foldPlaceholder":{backgroundColor:"transparent",border:`1px solid ${n.gutterText}`,color:n.gutterText},".cm-tooltip":{border:e?"1px solid #41434A":"1px solid #D2D3D8",backgroundColor:e?"#292A2F":"#FFFFFF",borderRadius:"8px",overflow:"hidden",boxShadow:"0 8px 28px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete ul li[aria-selected]":{backgroundColor:e?"#315A85":"#DCEBFA",color:n.foreground},".cm-panels":{backgroundColor:n.gutter,color:n.foreground},".cm-searchMatch":{backgroundColor:e?"#725C1D":"#FFE69A"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:e?"#8D6D20":"#FFD45C"}},{dark:e})}const ZS=Bn.define([{tag:[O.keyword,O.controlKeyword,O.moduleKeyword,O.operatorKeyword,O.bool,O.null],color:"#FF7AB2"},{tag:[O.string,O.special(O.string)],color:"#FF8170"},{tag:[O.number,O.regexp],color:"#D9C97C"},{tag:[O.comment,O.lineComment,O.blockComment],color:"#7F8C98",fontStyle:"italic"},{tag:[O.tagName,O.typeName,O.className],color:"#5DD8FF"},{tag:O.attributeName,color:"#B281EB"},{tag:[O.propertyName,O.function(O.variableName),O.function(O.propertyName)],color:"#67B7A4"},{tag:O.definition(O.variableName),color:"#4EB0CC"},{tag:[O.variableName,O.operator,O.punctuation,O.bracket],color:"#E8E8ED"},{tag:O.invalid,color:"#FF453A"}]);function Xd(n){const e=n==="dark";return[KS(e?fh.dark:fh.light,e),s0(e?ZS:a0)]}const MS=Bt.parser.configure({dialect:"jsx"}),ES=new Map(Object.keys($e.components).map(n=>[n.toLowerCase(),n])),US=new Set(["VStack","HStack","ZStack","VGrid","HGrid"]),FS=512*1024,DS=512,LS=32,hi=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},Ft=(n,e)=>n.slice(e.from,e.to),de=n=>{throw new Error(n)},fa=n=>{let e=!0;const t=n.replace(/&([^;\s]+);/g,(i,s)=>{const r={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" "};if(Object.hasOwn(r,s))return r[s];if(/^#(?:[0-9]+|x[0-9a-f]+)$/i.test(s)){const o=s[1].toLowerCase()==="x"?parseInt(s.slice(2),16):Number(s.slice(1));if(o>0&&o<=1114111&&!(o>=55296&&o<=57343))return String.fromCodePoint(o)}return e=!1,i});return e?t:void 0},Bd=(n,e)=>n.lastIndexOf(` +`,e-1)+1,XS=(n,e)=>{const t=n.indexOf(` +`,e);return t<0?n.length:t},Mn=n=>!/\S/.test(n);function Id(n,e,t){const i=Bd(n,e),s=XS(n,t);return!Mn(n.slice(i,e))||!Mn(n.slice(t,s))?null:{start:i,end:Math.min(s+1,n.length),indent:n.slice(i,e)}}const gs=(n,e,t)=>e===null?n:n.split(` +`).map((i,s)=>s&&i.startsWith(e)?t+i.slice(e.length):i).join(` +`);function uo(n,e=!1){if(e)return fa(n.slice(1,-1));const t=n.trim();if(/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(t)){const i=Number(t);return Number.isFinite(i)?i:void 0}if(t==="true"||t==="false")return t==="true";if(t.startsWith('"'))try{const i=JSON.parse(t);return typeof i=="string"?i:void 0}catch{}}function vi(n){const e={formatVersion:1,source:n,nodes:[],roots:[],issue:""};if(typeof n!="string"||new TextEncoder().encode(n).length>FS)return{...e,issue:"Layout editing supports source files up to 512 KiB."};const t=new Set,i=n.replace(/\{\s*(?:\/\*[\s\S]*?\*\/\s*)+\}/g,(a,l)=>(t.add(l),`{0${a.slice(2,-1).replace(/[^\r\n]/g," ")}}`)),s=MS.parse(i);let r=!1;if(s.iterate({enter:a=>{a.type.isError&&(r=!0)}}),r)return{...e,issue:"Fix the JavaScript/JSX syntax before using Layout. Your source is preserved."};function o(a,l,c){(c>LS||e.nodes.length>=DS)&&de("Layout editing supports up to 512 layers and 32 nesting levels.");const h=hi(a),u=h[0],f=h.at(-1),d=hi(u).find(T=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(T.name)),p=d?Ft(n,d):"Fragment",m=ES.get(p.toLowerCase()),g=$e.components[m],y={...$e.globalProperties,...g?.properties??{}},x=u.name==="JSXOpenTag"&&f?.name==="JSXCloseTag",b=x?hi(f).find(T=>["JSXBuiltin","JSXIdentifier","JSXNamespacedName","JSXMemberExpression"].includes(T.name)):null;d&&x&&(!b||Ft(n,b)!==p)&&de("Opening and closing JSX tags must match before using Layout.");const C={id:String(a.from),parentID:l,tag:p,component:m??null,from:a.from,to:a.to,openingEnd:u.to,insertAt:u.to-(x?1:2),contentFrom:u.to,contentTo:x?f.from:u.to,children:[],properties:[],locked:!g,structure:!1,text:null,textEditable:!1,depth:c,outerFrom:a.from,textFrom:0,textTo:0};let Q=!1;for(const T of hi(u)){if(T.name==="JSXSpreadAttribute"&&(Q=!0),T.name!=="JSXAttribute")continue;const v=hi(T),M=Ft(n,v[0]),k=v[2],z=k?uo(Ft(n,k),k.name==="JSXAttributeValue"):!0,re=k?.name==="JSXEscape"?uo(n.slice(k.from+1,k.to-1)):z,N=Object.hasOwn(y,M)?y[M]:null;C.properties.push({name:M,value:re??null,from:T.from,to:T.to,editable:!!(g&&N&&N.type!=="function"&&re!==void 0),definition:N??null})}const P=new Set(C.properties.map(T=>T.name)).size!==C.properties.length;C.locked||=Q||P,C.reason=Q?"Spread properties are preserved; edit this element in Code.":P?"Duplicate properties are preserved; resolve them in Code.":g?"":"Custom components and fragments are preserved; edit them in Code.",C.locked&&C.properties.forEach(T=>{T.editable=!1}),e.nodes.push(C);const w=x?h.slice(1,-1):[],L=T=>T.name==="JSXEscape"&&t.has(T.from),D=w.filter(T=>!L(T));let W=null;for(const T of w){if(L(T)){W??=T.from;continue}const v=Ft(n,T);if(T.name==="JSXText"&&Mn(v)){W!==null&&v.split(` +`).length>2&&(W=null);continue}if(T.name==="JSXElement"){const M=o(T,C.id,c+1);M.outerFrom=W??M.from,C.children.push(M.id)}W=null}C.structure=!C.locked&&x&&US.has(m)&&D.every(T=>T.name==="JSXElement"||T.name==="JSXText"&&!Ft(n,T).trim())&&C.children.every(T=>!e.nodes.find(v=>v.id===T).locked);const F=w.length!==D.length,U=F?D.filter(T=>!(T.name==="JSXText"&&Mn(Ft(n,T)))):D;if(!C.locked&&m==="Text"&&x&&U.length===1){const T=U[0],v=Ft(n,T),M=/[\r\n]/.test(v)&&!/[\r\n]/.test(v.trim())?v.trim():null,k=T.name==="JSXText"&&M?fa(M):T.name==="JSXText"&&!/[\r\n]/.test(v)?fa(v):T.name==="JSXEscape"?uo(v.slice(1,-1)):void 0;if(typeof k=="string"){C.text=k,C.textEditable=!0;const z=T.name==="JSXText"?[v.length-v.trimStart().length,v.length-v.trimEnd().length]:[0,0];[C.textFrom,C.textTo]=F?[T.from+z[0],T.to-z[1]]:[C.contentFrom,C.contentTo]}}return C}try{s.iterate({enter(a){if(a.name!=="CallExpression")return;const l=hi(a.node);if(l[0]?.name!=="VariableName"||Ft(n,l[0])!=="$render"||l[1]?.name!=="ArgList")return;const c=hi(l[1]).filter(h=>!["(",")",",","LineComment","BlockComment"].includes(h.name));if(c.length===1&&c[0].name==="JSXElement")return e.roots.push(o(c[0],null,0).id),!1}})}catch(a){return{...e,nodes:[],roots:[],issue:a.message}}return e.roots.length||(e.issue="Layout needs a direct $render(…) or another native JSX element. Variables, loops and functions stay editable in Code."),e}function da(n){return!n?.component||n.locked?{}:{...$e.globalProperties,...$e.components[n.component]?.properties??{}}}function dh(n,e,t,i,s,r,o,a){const l=y=>n.nodes.find(x=>x.id===y),c=s===i.length,h=c?t.contentTo:l(i[s]).outerFrom,u=Bd(e,h),f=e.slice(u,h);if(!Mn(f)||u===0)return{change:{from:h,to:h,insert:r},offset:o};const d=r.slice(0,o);if(!c)return{change:{from:h,to:h,insert:`${gs(r,a,f)} +${f}`},offset:gs(d,a,f).length};const p=i.length?l(i[0]):null,m=p?Id(e,p.outerFrom,p.to):null,g=m?m.indent:`${f} `;return{change:{from:u,to:u,insert:`${g}${gs(r,a,g)} +`},offset:g.length+gs(d,a,g).length}}function BS(n,e,t){(n.source!==e||n.issue)&&de("Layout changed. Select the layer again before editing.");const i=n.nodes.find(l=>l.id===t.id);(!i||i.locked)&&de("This layer is locked. Edit its source in Code.");let s=[],r=i.from;if(t.type==="property"){const l=da(i),c=Object.hasOwn(l,t.name)?l[t.name]:null,h=i.properties.find(d=>d.name===t.name);(!c||c.type==="function"||h&&!h.editable)&&de("Dynamic or unsupported properties must be edited in Code.");const u=new Set(i.properties.map(d=>d.name)),f=$e.components[i.component];if(t.remove?(f.requiredAny?.includes(t.name)&&!f.requiredAny.some(d=>d!==t.name&&u.has(d))&&de("Keep at least one required component property."),Object.entries(f.properties??{}).some(([d,p])=>u.has(d)&&p.requires?.includes(t.name))&&de("Another property requires this value. Edit the dependent properties together in Code.")):(c.requires?.some(d=>!u.has(d))&&de("Add the required related properties together in Code."),(c.conflicts?.some(d=>u.has(d))||Object.entries(f.properties??{}).some(([d,p])=>d!==t.name&&u.has(d)&&p.conflicts?.includes(t.name)))&&de("This property conflicts with another component property.")),t.remove)(!h||c.required)&&de("This property cannot be removed."),s=[{from:h.from,to:h.to,insert:""}];else{const d=t.value;(!["string","number","boolean"].includes(typeof d)||typeof d=="number"&&!Number.isFinite(d)||typeof d=="string"&&d.length>8192)&&de("Use a bounded string, finite number or Boolean."),c.values&&!c.values.includes(d)&&de("Choose one of the supported property values."),c.type==="boolean"&&typeof d!="boolean"&&de("This property needs true or false."),c.type==="number"&&!(typeof d=="number"||typeof d=="string"&&d.trim()&&Number.isFinite(Number(d)))&&de("This property needs a number."),typeof d=="boolean"&&c.type!=="boolean"&&de("This property does not accept a Boolean."),typeof d=="number"&&!c.type.includes("number")&&de("This property needs a string value."),t.name==="opacity"&&!(Number(d)>=0&&Number(d)<=1)&&de("Opacity must be between zero and one.");const p=`${t.name}={${JSON.stringify(d)}}`;s=h?[{from:h.from,to:h.to,insert:p}]:[{from:i.insertAt,to:i.insertAt,insert:` ${p}`}]}}else if(t.type==="text")(!i.textEditable||typeof t.value!="string"||t.value.length>8192)&&de("Dynamic text is preserved. Edit it in Code."),s=[{from:i.textFrom,to:i.textTo,insert:`{${JSON.stringify(t.value)}}`}];else if(t.type==="move"||t.type==="remove"){const l=n.nodes.find(u=>u.id===i.parentID);l?.structure||de("Only literal children of a supported stack/grid can be moved or removed.");const c=Id(e,i.outerFrom,i.to),h=c?{from:c.start,to:c.end,insert:""}:{from:i.outerFrom,to:i.to,insert:""};if(t.type==="remove")s=[h];else{const u=n.nodes.find(g=>g.id===t.parentID);(!u?.structure||u.from>=i.from&&u.to<=i.to)&&de("Choose a supported container outside this layer.");const f=g=>{for(;g.parentID!==null;)g=n.nodes.find(y=>y.id===g.parentID);return g.id};f(i)!==f(u)&&de("Layers cannot move between render branches or JavaScript scopes.");const d=u.children.filter(g=>g!==i.id),p=t.index;if((!Number.isInteger(p)||p<0||p>d.length)&&de("Invalid layer position."),u.id===l.id&&u.children.indexOf(i.id)===p)return{changes:[],selectedFrom:r};const m=dh(n,e,u,d,p,e.slice(i.outerFrom,i.to),i.from-i.outerFrom,c?c.indent:null);s=[h,m.change],r=m.change.from-(m.change.from>=h.to?h.to-h.from:0)+m.offset}}else if(t.type==="add"){i.structure||de("Choose a supported container with literal JSX children.");const l={text:'New text',spacer:"",stack:'',icon:''};Object.hasOwn(l,t.kind)||de("Unsupported new layer.");const c=dh(n,e,i,i.children,i.children.length,l[t.kind],0,null);s=[c.change],r=c.change.from+c.offset}else de("Unsupported layout operation.");s.sort((l,c)=>l.from-c.from);let o=e;for(const l of[...s].reverse())o=o.slice(0,l.from)+l.insert+o.slice(l.to);return vi(o).issue&&de("This edit would leave the supported layout. Your source was not changed."),{changes:s,selectedFrom:r}}const Wd=Bt.parser.configure({dialect:"jsx"}),Ci=n=>{const e=[];for(let t=n.firstChild;t;t=t.nextSibling)e.push(t);return e},Qe=n=>{throw new Error(n)},Hi=Object.freeze({background:{type:"color"},surface:{type:"color"},foreground:{type:"color"},muted:{type:"color"},accent:{type:"color"},titleFont:{values:$e.globalProperties.font.values},bodyFont:{values:$e.globalProperties.font.values},fontDesign:{values:$e.globalProperties.fontDesign.values},corner:{type:"number",maximum:48},padding:{type:"number",maximum:48},spacing:{type:"number",maximum:32}}),Os={titleFont:"headline",bodyFont:"caption",fontDesign:"rounded",corner:20,padding:16,spacing:10},or=Object.freeze({Meadow:Object.freeze({...Os,background:"#F2FAF5",surface:"#FFFFFF",foreground:"#193F31",muted:"#607C70",accent:"#328963"}),Paper:Object.freeze({...Os,background:"#F4F7FD",surface:"#FFFFFF",foreground:"#243454",muted:"#687795",accent:"#4777D6"}),Peach:Object.freeze({...Os,background:"#FFF5EE",surface:"#FFFFFF",foreground:"#56392C",muted:"#967461",accent:"#C86B43"}),Midnight:Object.freeze({...Os,background:"#192332",surface:"#283548",foreground:"#F1F5FC",muted:"#AABAD0",accent:"#8EB7FF"})});function qd(n,e){Object.hasOwn(Hi,n)||Qe("Unknown theme token.");const t=Hi[n];t.type==="color"&&!(typeof e=="string"&&/^#[0-9a-f]{6}(?:[0-9a-f]{2})?$/i.test(e))&&Qe(`${n} needs a six or eight digit hex color.`),t.values&&!t.values.includes(e)&&Qe(`${n} needs a supported font value.`),t.type==="number"&&!(typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=t.maximum)&&Qe(`${n} needs a number from zero to ${t.maximum}.`)}function nl(n){(!n||typeof n!="object"||Array.isArray(n)||Object.keys(n).length!==Object.keys(Hi).length)&&Qe("A theme needs exactly the documented tokens.");for(const e of Object.keys(n))qd(e,n[e]);return n}function zd(n){(typeof n!="string"||new TextEncoder().encode(n).length>4096)&&Qe("Theme JSON is limited to 4 KiB.");const e=JSON.parse(n);return(!e||Array.isArray(e)||Object.keys(e).sort().join()!=="formatVersion,name,tokens"||e.formatVersion!==1||typeof e.name!="string"||!e.name.trim()||/[\u0000-\u001f]/.test(e.name)||new TextEncoder().encode(e.name).length>64)&&Qe("Use a version 1 theme with a name of at most 64 bytes."),nl(e.tokens),e}function IS(n,e="My theme"){const t=JSON.stringify({formatVersion:1,name:e,tokens:n},null,2);return zd(t),t}function ar(n){const e={source:n,tokens:null,ranges:{},issue:"",canInitialize:!1};try{(typeof n!="string"||new TextEncoder().encode(n).length>512*1024)&&Qe("Theme editing supports files up to 512 KiB.");const t=Wd.parse(n),i=[],s=[];if(t.iterate({enter(l){l.type.isError&&Qe("Fix JavaScript syntax before editing the theme."),["VariableDefinition","VariableName"].includes(l.name)&&n.slice(l.from,l.to).includes("\\")&&Qe("Escaped identifiers stay in Code."),n.slice(l.from,l.to)==="widgetTheme"&&["VariableDefinition","VariableName"].includes(l.name)&&(l.name==="VariableDefinition"?i:s).push(l.node)}}),!i.length&&!s.length){const l=vi(n);e.canInitialize=!l.issue&&l.roots.length===1&&!l.nodes[0].locked;let c=!1;for(const h of Ci(t.topNode)){const u=h.firstChild;l.nodes[0]&&h.name==="ExpressionStatement"&&u?.name==="CallExpression"&&n.slice(u.firstChild.from,u.firstChild.to)==="$render"&&u.froml.nodes[0].to&&(c=!0)}return e.canInitialize&&=c,e}i.length!==1&&Qe("Keep one top-level const widgetTheme object. Other bindings stay in Code.");const r=i[0].parent,o=Ci(r);(r.name!=="VariableDeclaration"||r.parent?.name!=="Script"||o[0]?.name!=="const"||o[1]?.from!==i[0].from||o[2]?.name!=="Equals"||o[3]?.name!=="ObjectExpression"||o.slice(4).some(l=>l.name!==";"))&&Qe("Theme editing needs a single top-level const widgetTheme = { … } declaration.");const a={};for(const l of Ci(o[3])){if(["{","}",","].includes(l.name))continue;const c=Ci(l),h=c[0]?n.slice(c[0].from,c[0].to):"",u=c[0]?.name==="String"&&h.startsWith('"')?JSON.parse(h):h;(l.name!=="Property"||c.length!==3||!["PropertyDefinition","String"].includes(c[0].name)||c[1].name!==":"||!["String","Number"].includes(c[2].name)||Object.hasOwn(a,u))&&Qe("Theme tokens must be unique literal properties. Computed or dynamic values stay in Code.");let f;try{f=JSON.parse(n.slice(c[2].from,c[2].to))}catch{Qe("Theme values use JSON strings or numbers. Edit this declaration in Code.")}qd(u,f),a[u]=f,e.ranges[u]={from:c[2].from,to:c[2].to}}nl(a);for(const l of s){const c=l.parent,h=Ci(c),u=h[2]?n.slice(h[2].from,h[2].to):"";(c.name!=="MemberExpression"||h[0].from!==l.from||h[1]?.name!=="."||h[2]?.name!=="PropertyName"||!Object.hasOwn(Hi,u))&&Qe("Theme references must read widgetTheme.token. Other uses stay in Code."),c.parent?.name==="MemberExpression"&&Qe("Mutable theme references stay in Code.");for(let f=c.parent;f;f=f.parent)(["UpdateExpression","PostfixExpression"].includes(f.name)||f.name==="UnaryExpression"&&/^(?:delete|\+\+|--)/.test(n.slice(f.from,c.from).trim())||f.name==="AssignmentExpression"&&f.firstChild.from<=c.from&&f.firstChild.to>=c.to||f.name==="ForOfSpec"||f.name==="ForInSpec")&&Qe("Mutable theme references stay in Code.")}e.tokens=a}catch(t){e.issue=t.message}return e}function fo(n,e,t){return(n.source!==e||n.issue||!n.tokens)&&Qe("Theme changed or is unsupported. Reopen Theme before editing."),nl(t),{changes:Object.keys(Hi).filter(s=>t[s]!==n.tokens[s]).map(s=>({...n.ranges[s],insert:JSON.stringify(t[s])})).sort((s,r)=>s.from-r.from)}}function WS(n,e="Meadow"){(!ar(n).canInitialize||!Object.hasOwn(or,e))&&Qe("Start with a literal top-level layout without an existing widgetTheme binding.");const i=vi(n),s=i.nodes[0],r=[];function o(c,h,u,f=!1){const d=c.properties.find(m=>m.name===h);if(c.locked||d&&!d.editable||!d&&!f)return;const p=`${h}={widgetTheme.${u}}`;r.push(d?{from:d.from,to:d.to,insert:p}:{from:c.insertAt,to:c.insertAt,insert:` ${p}`})}for(const c of["background","corner","padding"])o(s,c,c,!0);s.structure&&o(s,"spacing","spacing",!0);for(const c of i.nodes)if(c.component==="Text"){const h=c.properties.find(f=>f.name==="font")?.value,u=["headline","largeTitle","title","title2","title3"].includes(h);o(c,"font",u?"titleFont":"bodyFont",!0),o(c,"color",u?"foreground":"muted",!0),o(c,"fontDesign","fontDesign",!0)}else c.component==="Icon"&&o(c,"color","accent",!0);let a=0;for(const c of Ci(Wd.parse(n).topNode))if(!(c.name==="LineComment"||c.name==="BlockComment"))if(c.name==="ExpressionStatement"&&c.firstChild?.name==="String")a=c.to;else break;r.push({from:a,to:a,insert:` +const widgetTheme = ${JSON.stringify(or[e],null,2)}; +`}),r.sort((c,h)=>c.from-h.from);let l=n;for(const c of[...r].reverse())l=l.slice(0,c.from)+c.insert+l.slice(c.to);return(!ar(l).tokens||vi(l).issue)&&Qe("This layout cannot be themed automatically. Your source was preserved."),{changes:r}}function Vd(n){if(!Array.isArray(n)||n.length>4096)return[];const e=new Map,t=new Set;for(const i of n){if(typeof i!="string"||new TextEncoder().encode(i).length>1024||/[\\\u0000-\u001f\u007f-\u009f]/.test(i))continue;const s=i.split("/");if(s.length!==2||s[0]!=="image"||!s[1]||new TextEncoder().encode(s[1]).length>255||s[1]!==s[1].trim()||s[1].includes("..")||!/\.(png|jpe?g|webp)$/i.test(s[1]))continue;const r=i.normalize("NFC").toLowerCase();e.has(r)&&e.get(r)!==i&&t.add(r),e.set(r,i)}return[...e].filter(([i])=>!t.has(i)).map(([,i])=>i).sort().slice(0,256)}const sl=Y.define(),lr=Te.define({create:()=>[],update(n,e){for(const t of e.effects)t.is(sl)&&(n=Vd(t.value));return n}});function rl(n,e){n.state.field(lr,!1)!==void 0&&n.dispatch({effects:sl.of(e)})}const jd=Object.freeze({bloom:Object.freeze({name:"Bloom mark",description:"A small four-petal flower",kind:"icon"}),leaf:Object.freeze({name:"Leaf mark",description:"A tilted leaf and stem",kind:"icon"}),pebble:Object.freeze({name:"Pebble friend",description:"A quiet, round-eared companion",kind:"pet"})}),po=`/* ScriptWidget original geometric assets 1: Bloom mark, Leaf mark, Pebble friend. Source: https://github.com/everettjf/scriptwidget (Editor/editorfe/src/visualAssets.js) SPDX-License-Identifier: MIT @@ -49,8 +56,8 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -`;function DS(n,e){const t=i=>e?`{widgetTheme.${i}}`:JSON.stringify(sr.Meadow[i]);if(n==="bloom")return``;if(n==="leaf")return``;if(n==="pebble")return``;throw new Error("Choose an original asset from the catalog.")}function LS(n,e,{id:t,kind:i,path:s},r=[]){if(n.source!==e||n.issue)throw new Error("Layout changed. Select the container again.");const o=n.nodes.find(f=>f.id===t);if(!o?.structure)throw new Error("Select a stack/grid with literal JSX children in Layout or Assets.");let a;if(i==="photo"){if(!Bd(r).includes(s))throw new Error("This image is no longer in the package resource list. Refresh images.");a=``}else{if(!Object.hasOwn(Id,i))throw new Error("Choose an original asset from the catalog.");a=DS(i,!!rr(e).tokens)}const l=[{from:o.contentTo,to:o.contentTo,insert:a}];let c=o.contentTo;if(i!=="photo"&&!e.includes(uo)){const f=e.startsWith("#!")?e.indexOf(` -`)+1:0;l.push({from:f,to:f,insert:uo}),c+=uo.length}l.sort((f,d)=>f.from-d.from);let h=e;for(const f of[...l].reverse())h=h.slice(0,f.from)+f.insert+h.slice(f.to);if(vi(h).issue)throw new Error("This asset would exceed the supported layout limits. Your source was preserved.");return{changes:l,selectedFrom:c}}const XS=n=>["string","number","number|string","date|number","boolean","enum","color","url","action-id","storage-key"].includes(n.type);function X(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function BS(n,e){const t=X("section","sw-layout"),i=X("div","sw-layout-header"),s=X("div","sw-layout-body");t.setAttribute("aria-label","Visual layout editor");let r=!1,o="layout",a=null,l=null,c="",h=null,u=!1,f=0;const d=String(Math.random()),p=(Q,D)=>P=>{if(u||!t.contains(Q)){P.preventDefault();return}return D(P)},m=(Q,D,P)=>Q.addEventListener(D,p(Q,P)),g=(Q,D,P=!1)=>{const j=X("button","sw-layout-button",Q);return j.type="button",j.disabled=P,m(j,"click",D),j},y=g("Layout",()=>{r=o==="layout"?!r:!0,o="layout",Y(),n.requestMeasure()});y.classList.add("sw-layout-toggle"),y.setAttribute("aria-expanded","false");const b=X("span","sw-layout-hint","Select layers and edit literal JSX"),x=g("Undo",()=>La(n)),C=g("Redo",()=>zs(n)),k=g("Theme",()=>{r=o==="theme"?!r:!0,o="theme",Y(),n.requestMeasure()});k.setAttribute("aria-expanded","false");const S=g("Assets",()=>{r=o==="assets"?!r:!0,o="assets",Y(),n.requestMeasure()});S.setAttribute("aria-expanded","false"),i.append(y,k,S,b,x,C),t.append(i,s),s.hidden=x.hidden=C.hidden=!0;const w=X("p","sw-layout-error");w.setAttribute("role","alert"),w.hidden=!0,t.append(w);function U(){a=vi(n.state.doc.toString());const Q=X("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(Q),Q.append(X("div","sw-layout-title","Widget assets")),Q.append(X("p","sw-layout-notice","Insert editable original JSX or a package image. Originals follow connected theme colors; pet artwork is static. Import photos with the app's existing image tools or Web Studio's Add image.")),a.issue){Q.append(X("p","sw-layout-notice",a.issue));return}const D=a.nodes.filter(I=>I.structure),P=X("select");P.setAttribute("aria-label","Asset destination");for(const I of D){const H=X("option","",`${I.tag} · line ${n.state.doc.lineAt(I.from).number}`);H.value=I.id,P.append(H)}D.some(I=>I.id===l)?P.value=l:l=P.value,m(P,"change",()=>{l=P.value}),Q.append(P);const j=n.state.readOnly||!D.length;D.length||Q.append(X("p","sw-layout-notice","Add a stack/grid with literal JSX children in Code to insert assets."));function ae(I,H){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const ce=LS(a,n.state.doc.toString(),{id:P.value,kind:I,path:H},n.state.field(or));l=P.value,w.hidden=!0,n.dispatch({changes:ce.changes,selection:{anchor:ce.selectedFrom},annotations:ws.of("full"),userEvent:"input.asset",scrollIntoView:!0})}catch(ce){w.textContent=ce.message,w.hidden=!1}}for(const[I,H]of Object.entries(Id)){const ce=X("div","sw-layout-actions");ce.append(g(`Insert ${H.name}`,()=>ae(I),j),X("span","",H.description)),Q.append(ce)}Q.append(X("div","sw-layout-title","Package images"));const J=n.state.field(or),ee=X("select");ee.setAttribute("aria-label","Package image");for(const I of J){const H=X("option","",I);H.value=I,ee.append(H)}ee.disabled=!J.length,Q.append(ee,g("Insert package image",()=>ae("photo",ee.value),j||!J.length)),J.length||Q.append(X("p","sw-layout-notice","No supported images in image/. Add a PNG, JPEG or WebP to the package, then refresh or reopen the editor.")),e.refreshResources&&Q.append(g("Refresh images",async()=>{const I=++f,H=n.state.doc,ce=()=>!u&&I===f&&n.state.doc===H;try{const W=await e.refreshResources();ce()&&(w.hidden=!0,il(n,W))}catch{ce()&&(w.textContent="Images could not be refreshed. Reopen this document and try again.",w.hidden=!1)}})),Q.append(X("p","sw-layout-notice","Bloom mark, Leaf mark and Pebble friend: original ScriptWidget geometry, MIT licensed. Package photos retain their own rights. See the Studio assets documentation."))}function F(Q,D){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const P=n.state.doc.toString();if(P!==D)throw new Error("Source changed. Reopen Theme before editing.");const j=Q(P);w.hidden=!0,j.changes.length&&n.dispatch({changes:j.changes,annotations:ws.of("full"),userEvent:"input.theme"})}catch(P){w.textContent=P.message,w.hidden=!1}}function V(){const Q=n.state.doc.toString(),D=rr(Q),P=n.state.readOnly,j=X("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(j),j.append(X("div","sw-layout-title","Widget theme")),j.append(X("p","sw-layout-notice","Saved as ordinary JavaScript with your widget. Dynamic values stay in Code. Applying a theme changes the connected colors, fonts and spacing.")),D.issue){j.append(X("p","sw-layout-notice",D.issue));return}if(!D.tokens){j.append(g("Connect layout to Meadow theme",()=>F(ee=>FS(ee),Q),P||!D.canInitialize)),D.canInitialize||j.append(X("p","sw-layout-notice","Use a literal top-level $render layout, or define the documented widgetTheme object in Code."));return}const ae=X("div","sw-layout-actions");for(const[ee,I]of Object.entries(sr))ae.append(g(ee,()=>F(H=>ho(D,H,I),Q),P));j.append(ae);for(const[ee,I]of Object.entries(Hi)){const H=X("form","sw-layout-form"),ce=X("label","",ee),W=X(I.values?"select":"input");if(I.values)for(const re of I.values){const Me=X("option","",re);Me.value=re,W.append(Me)}I.type==="number"&&(W.type="number",W.min="0",W.max=String(I.maximum),W.step="any"),W.value=String(D.tokens[ee]),W.setAttribute("aria-label",`Theme ${ee}`),W.disabled=P;const te=g(`Apply ${ee}`,()=>{},P);te.type="submit",H.append(ce,W,te),m(H,"submit",re=>{re.preventDefault();const Me=I.type==="number"?W.value.trim()?Number(W.value):NaN:W.value;F(Oe=>ho(D,Oe,{...D.tokens,[ee]:Me}),Q)}),j.append(H)}const J=X("textarea");J.rows=5,J.setAttribute("aria-label","Reusable theme JSON"),J.value=US(D.tokens),j.append(X("label","","Copy this JSON to reuse a theme, or paste a version 1 theme and import it."),J,g("Import theme JSON",()=>F(ee=>ho(D,ee,Xd(J.value).tokens),Q),P))}function E(Q,D=a?.source){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");if(D!==n.state.doc.toString())throw new Error("Source changed during this operation. Select the layer again.");const P=ES(a,n.state.doc.toString(),Q);if(w.hidden=!0,!P.changes.length)return;n.dispatch({changes:P.changes,selection:{anchor:P.selectedFrom},annotations:ws.of("full"),userEvent:"input.layout",scrollIntoView:!0})}catch(P){w.textContent=P.message,w.hidden=!1}}function M(Q){u||(l=Q.id,c="",n.dispatch({selection:{anchor:Q.from,head:Q.to},scrollIntoView:!0,userEvent:"select.layout"}),Y())}function Y(){if(y.setAttribute("aria-expanded",String(r&&o==="layout")),k.setAttribute("aria-expanded",String(r&&o==="theme")),S.setAttribute("aria-expanded",String(r&&o==="assets")),s.hidden=!r,x.hidden=C.hidden=!r,b.hidden=r,x.disabled=n.state.readOnly||vc(n.state)===0,C.disabled=n.state.readOnly||wc(n.state)===0,!r)return;if(o==="assets"){U();return}if(o==="theme"){V();return}if(a=vi(n.state.doc.toString()),s.replaceChildren(),a.issue){s.append(X("p","sw-layout-notice",a.issue));return}const Q=n.state.selection.main.from,D=a.nodes.filter(W=>W.from<=Q&&QW.id===l&&W.from<=Q&&Q<=W.to)??D??a.nodes[0];l=P.id;const j=X("div","sw-layout-layers");j.setAttribute("role","tree"),j.setAttribute("aria-label","Layout layers");const ae=n.state.readOnly,J=W=>{const te=W.text??W.properties.find(re=>re.name==="text"&&re.editable&&typeof re.value=="string")?.value;return`<${W.tag}>${te?` · ${te.slice(0,32)}`:""}${W.locked?" · locked":""}`};for(const[W,te]of a.nodes.entries()){const re=a.nodes.find(ie=>ie.id===te.parentID),Me=!ae&&!te.locked&&re?.structure,Oe=g(J(te),()=>M(te));Oe.classList.add("sw-layout-layer"),Oe.dataset.layerId=te.id,Oe.style.paddingInlineStart=`${8+te.depth*14}px`,Oe.setAttribute("role","treeitem"),Oe.setAttribute("aria-level",String(te.depth+1)),Oe.setAttribute("aria-selected",String(te.id===P.id)),Oe.tabIndex=te.id===P.id?0:-1,Oe.draggable=!!Me,m(Oe,"keydown",ie=>{let ve;ie.key==="ArrowUp"&&(ve=a.nodes[Math.max(0,W-1)]),ie.key==="ArrowDown"&&(ve=a.nodes[Math.min(a.nodes.length-1,W+1)]),ie.key==="ArrowLeft"&&(ve=re),ie.key==="ArrowRight"&&(ve=a.nodes.find(Ie=>Ie.id===te.children[0])),ie.key==="Home"&&(ve=a.nodes[0]),ie.key==="End"&&(ve=a.nodes.at(-1)),ve&&(ie.preventDefault(),ie.stopPropagation(),M(ve),ee().find(Ie=>Ie.dataset.layerId===ve.id)?.focus())}),m(Oe,"dragstart",ie=>{if(!Me){ie.preventDefault();return}h={id:te.id,source:a.source},ie.dataTransfer.setData("application/x-scriptwidget-layer",d),ie.dataTransfer.effectAllowed="move"}),m(Oe,"dragover",ie=>{h&&re?.structure&&te.id!==h.id&&(ie.preventDefault(),ie.dataTransfer.dropEffect="move")}),m(Oe,"drop",ie=>{if(!h||ie.dataTransfer.getData("application/x-scriptwidget-layer")!==d||!re?.structure)return;ie.preventDefault();const ve=h;h=null,E({type:"move",id:ve.id,parentID:re.id,index:re.children.filter(Ie=>Ie!==ve.id).indexOf(te.id)},ve.source)}),m(Oe,"dragend",()=>{h=null}),j.append(Oe)}function ee(){return[...t.querySelectorAll(".sw-layout-layer")]}const I=X("div","sw-layout-inspector"),H=X("div","sw-layout-title",`<${P.tag}>`);if(I.append(H),(ae||P.locked)&&I.append(X("p","sw-layout-notice",ae?"This document is read only.":P.reason)),!ae&&!P.locked){let Oe=function(){c=re.value;const oe=ha(P)[c],Ae=P.properties.find(tt=>tt.name===c);if(Me.replaceChildren(),te.onsubmit=tt=>tt.preventDefault(),Ae&&!Ae.editable){Me.append(X("span","sw-layout-notice","Dynamic value: edit it in Code. Connected widgetTheme tokens can be changed in Theme."));return}const le=X(oe.values||oe.type==="boolean"?"select":"input");le.setAttribute("aria-label","Layout property value");for(const tt of oe.values??(oe.type==="boolean"?[!0,!1]:[])){const ai=X("option","",String(tt));ai.value=String(tt),le.append(ai)}le.value=Ae?String(Ae.value):oe.values?.[0]??(oe.type==="boolean"?"true":"");const We=g("Apply",()=>{});We.type="submit",Me.append(le,We,g("Remove",()=>E({type:"property",id:P.id,name:c,remove:!0}),!Ae||oe.required)),te.onsubmit=p(te,tt=>{tt.preventDefault();const ai=oe.type==="boolean"?le.value==="true":oe.type==="number"?le.value.trim()?Number(le.value):NaN:le.value;E({type:"property",id:P.id,name:c,value:ai})})};if(P.textEditable){const oe=X("form","sw-layout-form"),Ae=X("label","","Text"),le=X("input");le.value=P.text,le.setAttribute("aria-label","Layer text");const We=g("Apply text",()=>{});We.type="submit",oe.append(Ae,le,We),m(oe,"submit",tt=>{tt.preventDefault(),E({type:"text",id:P.id,value:le.value})}),I.append(oe)}const W=Object.entries(ha(P)).filter(([,oe])=>XS(oe)),te=X("form","sw-layout-form"),re=X("select");re.setAttribute("aria-label","Layout property");for(const[oe]of W){const Ae=X("option","",oe);Ae.value=oe,re.append(Ae)}W.some(([oe])=>oe===c)||(c=P.structure?"alignment":"color"),re.value=c,re.value||(re.selectedIndex=0,c=re.value);const Me=X("div","sw-layout-property");te.append(re,Me),m(re,"change",Oe),Oe(),I.append(te);const ie=a.nodes.find(oe=>oe.id===P.parentID),ve=ie?.children.indexOf(P.id)??-1,Ie=X("div","sw-layout-actions");if(Ie.append(g("Move up",()=>E({type:"move",id:P.id,parentID:ie.id,index:ve-1}),!ie?.structure||ve<=0),g("Move down",()=>E({type:"move",id:P.id,parentID:ie.id,index:ve+1}),!ie?.structure||ve>=ie.children.length-1),g("Delete layer",()=>E({type:"remove",id:P.id}),!ie?.structure)),I.append(Ie),ie?.structure){const oe=a.nodes.filter(le=>le.structure&&!(le.from>=P.from&&le.to<=P.to)),Ae=X("select");Ae.setAttribute("aria-label","Move layer into container");for(const le of oe){const We=X("option","",`${le.tag} · line ${n.state.doc.lineAt(le.from).number}`);We.value=le.id,Ae.append(We)}I.append(Ae,g("Move inside",()=>{const le=a.nodes.find(We=>We.id===Ae.value);E({type:"move",id:P.id,parentID:le.id,index:le.children.filter(We=>We!==P.id).length})},!oe.length))}if(P.structure){const oe=X("div","sw-layout-actions");for(const[Ae,le]of[["text","Add text"],["stack","Add stack"],["spacer","Add spacer"],["icon","Add icon"]])oe.append(g(le,()=>E({type:"add",id:P.id,kind:Ae})));I.append(oe)}}const ce=P.properties.filter(W=>!W.editable).map(W=>W.name);ce.length&&I.append(X("p","sw-layout-notice",`Preserved in Code: ${ce.join(", ")}`)),!P.structure&&P.children.length&&I.append(X("p","sw-layout-notice","This child structure stays in Code. Reordering is available on literal stack/grid children.")),s.append(j,I)}return{dom:t,top:!0,update(Q){if(!r)return;const D=n.state.selection.main.from,P=a?.nodes.filter(ae=>ae.from<=D&&Dae.effects.some(J=>J.is(tl)));(Q.docChanged||j||Q.startState.readOnly!==n.state.readOnly||Q.selectionSet&&P!==l)&&(Q.docChanged&&o!=="assets"&&(l=null),Y()),x.disabled=n.state.readOnly||vc(n.state)===0,C.disabled=n.state.readOnly||wc(n.state)===0},destroy(){u=!0}}}const IS=$.baseTheme({".sw-layout":{fontFamily:"system-ui, sans-serif",fontSize:"12px",backgroundColor:"#f6f7fa",color:"#272a34",borderBottom:"1px solid #dce0e9"},"&dark .sw-layout":{backgroundColor:"#252830",color:"#eceef5",borderColor:"#414552"},".sw-layout-header":{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",padding:"6px 10px"},".sw-layout-toggle":{fontWeight:"600"},".sw-layout-hint":{opacity:"0.65",fontSize:"11px"},".sw-layout-button":{fontFamily:"inherit",fontSize:"11px",color:"inherit",backgroundColor:"transparent",border:"1px solid #a0a5b655",borderRadius:"6px",padding:"4px 8px",cursor:"pointer",whiteSpace:"nowrap"},".sw-layout-button:disabled":{opacity:"0.4",cursor:"default"},".sw-layout-body":{display:"grid",gridTemplateColumns:"minmax(120px, 1fr) minmax(180px, 1.6fr)",maxHeight:"280px",overflow:"auto",borderTop:"1px solid #a0a5b633"},".sw-layout-body[hidden]":{display:"none"},".sw-layout-layers":{padding:"6px 2px",overflow:"auto",borderRight:"1px solid #a0a5b633"},".sw-layout-layer":{display:"block",border:0,borderRadius:"4px",width:"100%",textAlign:"left",overflow:"hidden",textOverflow:"ellipsis",margin:"1px 0",paddingBlock:"6px"},'.sw-layout-layer[aria-selected="true"]':{backgroundColor:"#4085f52b",color:"inherit"},".sw-layout-inspector":{padding:"8px 10px",display:"flex",alignItems:"start",flexDirection:"column",gap:"8px",minWidth:0},".sw-theme-inspector":{gridColumn:"1 / -1"},".sw-theme-inspector textarea":{boxSizing:"border-box",width:"100%",fontFamily:"monospace",backgroundColor:"transparent",color:"inherit",border:"1px solid #a0a5b666",borderRadius:"5px"},".sw-layout-title":{fontWeight:"600"},".sw-layout-form":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"5px",width:"100%"},".sw-layout-property,.sw-layout-actions":{display:"flex",flexWrap:"wrap",gap:"5px",alignItems:"center"},".sw-layout input,.sw-layout select":{fontFamily:"inherit",fontSize:"12px",minWidth:0,maxWidth:"100%",padding:"4px 6px",border:"1px solid #a0a5b666",borderRadius:"5px",backgroundColor:"transparent",color:"inherit"},".sw-layout-notice":{margin:"8px",lineHeight:"1.5",fontSize:"11px",opacity:"0.7"},".sw-layout-body > .sw-layout-notice":{gridColumn:"1 / -1"},".sw-layout-error":{margin:"0 10px 6px",color:"#b32636",fontSize:"12px"},"&dark .sw-layout-error":{color:"#ff99a4"},".sw-layout button:focus-visible,.sw-layout input:focus-visible,.sw-layout select:focus-visible":{outline:"2px solid #4085f5",outlineOffset:"1px"},"@media (max-width: 480px)":{".sw-layout-body":{gridTemplateColumns:"minmax(90px, 1fr) minmax(150px, 1.6fr)"},".sw-layout-hint":{display:"none"}}});function WS(n={}){return[IS,or,Vi.of(e=>BS(e,n))]}const Wd="scriptwidget.studio.document-state.v1.";function qd(n,e,t){if(!n||!e)return!1;try{return n.setItem(`${Wd}${e}`,JSON.stringify({anchor:Number(t.anchor)||0,head:Number(t.head)||0,scrollTop:Number(t.scrollTop)||0})),!0}catch{return!1}}function qS(n,e,t){if(!n||!e)return null;try{const i=JSON.parse(n.getItem(`${Wd}${e}`));if(!i||typeof i!="object")return null;const s=r=>Math.max(0,Math.min(Number(r)||0,t));return{anchor:s(i.anchor),head:s(i.head),scrollTop:Math.max(0,Number(i.scrollTop)||0)}}catch{return null}}const zS="scriptwidget.web-studio.draft.v1:";function nl(n){return`${zS}${n}`}function VS(n,e){if(!e)return null;try{const t=JSON.parse(n.getItem(nl(e))||"null");return t&&typeof t.content=="string"&&typeof t.baseRevision=="string"?t:null}catch{return null}}function hh(n,e,t,i,s=Date.now()){if(!e||typeof i!="string")return null;const r={documentID:e,content:t,baseRevision:i,updatedAt:s};return n.setItem(nl(e),JSON.stringify(r)),r}function fo(n,e){e&&n.removeItem(nl(e))}function jS(n,e,t,i){const s=VS(n,e);return!s||s.content===t?null:{...s,serverContent:t,serverRevision:i,isStale:s.baseRevision!==i}}function YS(){return{connection:"connecting",save:"idle",preview:"idle",conflict:null}}function NS(n,e){switch(e.type){case"CONNECTED":return{...n,connection:"connected"};case"OFFLINE":return{...n,connection:"offline",save:n.save==="saving"?"draft":n.save};case"DISCONNECTED":return{...n,connection:"disconnected"};case"EDITED":return{...n,save:"draft",conflict:null};case"SAVING":return{...n,save:"saving"};case"SAVED":return{...n,save:"saved",preview:e.preview||"requested",conflict:null};case"SAVE_FAILED":return{...n,save:"error"};case"CONFLICT":return{...n,save:"conflict",conflict:e.conflict};default:return n}}class HS{constructor(e){this.send=e,this.epoch=0,this.context=null,this.inFlight=null,this.needsFlush=!1}open({documentID:e,packageID:t,path:i,revision:s,content:r}){return this.epoch+=1,this.context={documentID:e,packageID:t,path:i,revision:s,content:r,generation:0,savedGeneration:0},this.needsFlush=!1,this.snapshot()}edit(e){return this.context?(this.context.content=e,this.context.generation+=1,this.snapshot()):null}rebase(e){return this.context&&(this.context.revision=e),this.snapshot()}get isDirty(){return!!(this.context&&this.context.generation!==this.context.savedGeneration)}snapshot(){return this.context?{...this.context,dirty:this.isDirty}:null}async flush(){if(!this.context||!this.isDirty)return{skipped:!0,snapshot:this.snapshot()};if(this.inFlight)return this.needsFlush=!0,this.inFlight.then(()=>this.isDirty?this.flush():{skipped:!0,snapshot:this.snapshot()});const e=this.epoch,t={...this.context};this.needsFlush=!1,this.inFlight=this.send({documentID:t.documentID,packageID:t.packageID,path:t.path,content:t.content,baseRevision:t.revision}).then(s=>this.epoch!==e||this.context?.documentID!==t.documentID?{ignored:!0,result:s,snapshot:this.snapshot()}:(this.context.revision=s.revision,this.context.savedGeneration=t.generation,{result:s,snapshot:this.snapshot()})).finally(()=>{this.inFlight=null});const i=await this.inFlight;return this.needsFlush&&this.isDirty?this.flush():i}}function uh(n){return["draft","saving","error","conflict"].includes(n)}class GS extends Error{constructor(e,t,i={}){super(e),this.name="StudioAPIError",this.status=t,this.body=i}}class _S{constructor({fetchImpl:e=globalThis.fetch,token:t=()=>"",onUnauthorized:i=()=>{}}={}){if(typeof e!="function")throw new TypeError("A fetch implementation is required");this.fetchImpl=e,this.token=t,this.onUnauthorized=i}async request(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t)),s=await i.json().catch(()=>({}));return this.validate(i,e,s),s}async requestBlob(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t));if(!i.ok){const s=await i.json().catch(()=>({}));this.validate(i,e,s)}return i.blob()}authorizedOptions(e){return{...e,headers:{"Content-Type":"application/json","X-Studio-Token":this.token(),...e.headers||{}}}}validate(e,t,i){if(!e.ok){const s=new GS(i.message||`Request failed (${e.status})`,e.status,i);throw e.status===401&&t!=="/api/v1/pair"&&this.onUnauthorized(s),s}}}const sl=/^https?:$/.test(window.location.protocol)&&!window.ScriptWidgetAndroid,JS=document.querySelector(sl?"#editor":"#native-editor"),rl=new Gi,ar=new Gi;let Wt=null,me=null,Et=null,at=0,wi=0,ua=!1,Mn=null,fh=null;const dh=document.querySelector("#save-status");let zd=null;function En(n,e="idle"){dh.textContent=n,dh.dataset.state=e}function e1(){window.clearTimeout(fh),fh=window.setTimeout(()=>{const n=q.state.selection.main;qd(window.localStorage,me,{anchor:n.anchor,head:n.head,scrollTop:q.scrollDOM.scrollTop})},180)}function Vd(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function ol(){window.clearTimeout(Mn),En("Saving…","saving"),Mn=window.setTimeout(()=>{const n=q.state.doc.toString(),e=at,t=me,i=Et,s=wi;nn(Wt,Ue.documentSave,{content:n,version:e},t,(r={})=>{sl||t!==me||i!==Et||s!==wi||e!==at||En(r.result==="ok"||r.result==="unavailable"?"Saved":"Save failed",r.result==="failed"?"error":"saved")},i)},700)}function t1(n){if((n.selectionSet||n.viewportChanged||n.docChanged)&&e1(),!n.docChanged||ua)return;at+=1,zd?.documentChanged();const e=[];n.changes.iterChanges((t,i,s,r,o)=>{e.push({from:t,to:i,insert:o.toString(),newFrom:s,newTo:r})}),nn(Wt,Ue.documentChanged,{changes:e,version:at},me,void 0,Et),ol()}const jd=[nO(),oO(),xg(),w0(),WS({refreshResources:()=>new Promise((n,e)=>{const t=me,i=wi,s=Et,r=window.setTimeout(()=>e(new Error("Resource refresh timed out")),5e3);nn(Wt,Ue.documentResources,{},t,(o={})=>{window.clearTimeout(r),t!==me||i!==wi||o.result!=="ok"||o.documentID!==t||!Array.isArray(o.resources)?e(new Error("Document resources are unavailable")):n(o.resources)},s)})}),HO(),hg(),gg(),_.allowMultipleSelections.of(!0),UO(),c0(),uA(),xA({override:[kS],activateOnTyping:!0}),Mg(),Fg(),Cg(),Qb(),fS(),iS(Ed,{delay:350}),Eu(QS),yb({jsx:!0}),mr.of([Py,...mA,...Qy,...jb,...Z0,...VO,...nd]),rl.of(_.readOnly.of(!1)),ar.of(Ud(Vd())),$.updateListener.of(t1),$.contentAttributes.of({autocapitalize:"off",autocomplete:"off",spellcheck:"false"})],q=new $({state:_.create({doc:"",extensions:jd}),parent:JS});function _t(n,e=me,t=0,i=!1){window.clearTimeout(Mn),wi+=1;const s=q.state.selection.main;qd(window.localStorage,me,{anchor:s.anchor,head:s.head,scrollTop:q.scrollDOM.scrollTop}),ua=!0;const r=e!==me;me=e,at=t;const o=qS(window.localStorage,me,(n??"").length),a=o?{anchor:o.anchor,head:o.head}:{anchor:0};if(r){const l=ar.get(q.state),c=q.state.readOnly;let h=_.create({doc:n??"",extensions:jd,selection:a});h=h.update({effects:[ar.reconfigure(l),rl.reconfigure(_.readOnly.of(c))]}).state,q.setState(h)}else q.dispatch({changes:{from:0,to:q.state.doc.length,insert:n??""},selection:a,scrollIntoView:!0});o&&window.requestAnimationFrame(()=>{q.scrollDOM.scrollTop=o.scrollTop}),ua=!1,i&&nn(Wt,Ue.documentChanged,{content:q.state.doc.toString(),version:at},me,void 0,Et),En("Saved","saved")}function ph(n){if(q.state.readOnly)return!1;const e=q.state.selection.main;return q.dispatch({changes:{from:e.from,to:e.to,insert:n},selection:{anchor:e.from+n.length},userEvent:"input"}),q.focus(),!0}async function lr(){if(q.state.readOnly)return!1;const n=q.state.doc.toString(),e=wi,t=at,i=()=>!q.state.readOnly&&e===wi&&t===at&&n===q.state.doc.toString();try{const[{format:s},{default:r},{default:o}]=await Promise.all([Cr(()=>import("./standalone-Cayz_KD-.js"),[],import.meta.url),Cr(()=>import("./babel-BktJt1uC.js"),[],import.meta.url),Cr(()=>import("./estree-DFfjoHvx.js"),[],import.meta.url)]),a=await s(n,{parser:"babel",plugins:[r,o],semi:!0,singleQuote:!0,trailingComma:"es5"});return i()?(_t(a,me,at+1,!0),ol(),!0):!1}catch(s){return i()&&nn(Wt,"diagnostics.publish",{message:String(s),severity:"error"},me,void 0,Et),!1}}function Xi(n){q.dispatch({effects:rl.reconfigure(_.readOnly.of(!!n))})}function cr(n){const e=n==="dark"||n==="light"?n:Vd();document.documentElement.dataset.theme=e,q.dispatch({effects:ar.reconfigure(Ud(e))})}function i1(n=[]){const e=n.map(t=>({from:Math.max(0,Math.min(t.from??0,q.state.doc.length)),to:Math.max(0,Math.min(t.to??t.from??0,q.state.doc.length)),severity:t.severity??"error",message:t.message??"Unknown error"}));q.dispatch(vd(q.state,e))}function rt(n,e){Wt.registerHandler(n,async(t={},i=()=>{})=>{try{if(Et!==null&&n!==Ue.documentOpen&&n!==Ue.editorSetTheme&&(t.documentID!==me||t.sessionID!==Et))throw new Error("The editor session changed.");i({result:"ok",...await e(t)})}catch(s){i({result:"failed",message:String(s)})}})}pS(n=>{Wt=n,rt(Ue.documentOpen,({payload:e={},documentID:t,sessionID:i=null})=>(Et=i,_t(e.content,t,e.version??0),il(q,e.resources??[]),Xi(e.readOnly),e.dirty&&(En("Restored unsaved edits","editing"),e.readOnly||ol()),{protocolVersion:Zd})),rt(Ue.documentReplace,({payload:e={},documentID:t})=>{if(q.state.readOnly||e.expectedContent!==void 0&&e.expectedContent!==q.state.doc.toString())throw new Error("The file changed or is read only.");return _t(e.content,t,e.version??at,!0),{}}),rt(Ue.documentSetReadOnly,({payload:e={}})=>(Xi(e.readOnly),{readOnly:!!e.readOnly})),rt(Ue.editorInsert,({payload:e={}})=>({inserted:ph(e.content??"")})),rt(Ue.editorFormat,async()=>({formatted:await lr()})),rt(Ue.editorSetTheme,({payload:e={}})=>(cr(e.theme),{})),rt(Ue.editorGetState,()=>({content:q.state.doc.toString(),version:at,documentID:me,sessionID:Et,selection:{from:q.state.selection.main.from,to:q.state.selection.main.to}})),rt(Ue.diagnosticsPublish,({payload:e={}})=>(i1(e.items),{})),rt("editor_setValue",({value:e})=>(_t(e),{})),rt("editor_insertValue",({value:e})=>({inserted:ph(e??"")})),rt("editor_getValue",()=>({value:q.state.doc.toString()})),rt("editor_setReadonly",({readonly:e})=>(Xi(e),{readonly:!!e})),rt("editor_formatCode",async()=>({formatted:await lr()})),mS(Wt)});sl&&(document.querySelector("#native-editor").hidden=!0,document.querySelector("#web-studio").hidden=!1,n1());async function n1(){const n=document.querySelector("#pair-dialog"),e=document.querySelector("#pair-form"),t=document.querySelector("#pair-error"),i=document.querySelector("#package-select"),s=document.querySelector("#file-select"),r=document.querySelector("#connection-status"),o=document.querySelector("#disconnect-button"),a=document.querySelector("#studio-grid"),l=document.querySelector(".editor-column"),c=document.querySelector("#recovery-banner"),h=document.querySelector("#conflict-banner"),u=document.querySelector("#command-dialog"),f=document.querySelector("#command-search"),d=document.querySelector("#command-list"),p=document.querySelector("#compare-dialog");let m=window.sessionStorage.getItem("scriptwidget.web-studio.token")||"",g=[],y=null,b=null,x=null,C=0,k=null,S="",w="",U=null,F=YS(),V="",E="",M=null;function Y(v="Session ended. Enter the new code shown on your device."){m="",window.sessionStorage.removeItem("scriptwidget.web-studio.token"),o.hidden=!0,Q({type:"DISCONNECTED"}),r.textContent=v,Xi(!0),n.open||n.showModal()}function Q(v){F=NS(F,v);const Z={connecting:"Connecting",connected:"Connected",offline:"Offline",disconnected:"Disconnected"},L={idle:"Ready",draft:"Draft saved locally",saving:"Saving…",saved:"Saved",error:"Save failed",conflict:"Conflict"};r.dataset.state=F.connection,document.querySelector("#status-connection").textContent=Z[F.connection]||F.connection,En(L[F.save]||F.save,F.save),document.querySelector("#dirty-indicator").hidden=!["draft","saving","error","conflict"].includes(F.save),document.querySelector("#status-preview").textContent=F.preview==="requested"?"Preview requested":"Preview idle",document.querySelector("#preview-detail").textContent=F.preview==="requested"?"Requested on device":"Not requested"}const D=new _S({token:()=>m,onUnauthorized:()=>Y()}),P=(v,Z)=>D.request(v,Z);M=new HS(({packageID:v,path:Z,content:L,baseRevision:ne})=>P("/api/v1/document",{method:"PUT",body:JSON.stringify({package:v,path:Z,content:L,baseRevision:ne})}));async function j(v){m=(await P("/api/v1/pair",{method:"POST",body:JSON.stringify({code:v})})).token,window.sessionStorage.setItem("scriptwidget.web-studio.token",m),o.hidden=!1,Q({type:"CONNECTED"}),ae()}function ae(){window.clearInterval(y),y=window.setInterval(async()=>{if(m)try{const v=await P("/api/v1/session");if(!navigator.onLine)return;W(v),Q({type:"CONNECTED"})}catch(v){v.status!==401&&(r.textContent=`Interrupted · ${v.message}`,Q({type:"OFFLINE"}))}},5e3)}async function J(){if(g=(await P("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(Z=>new Option(Z.name,Z.id))),!g.length){r.textContent="No editable widgets",Xi(!0);return}await ee()}async function ee(){const v=g.find(ne=>ne.id===i.value),Z=v?.files||[];s.replaceChildren(...Z.map(ne=>new Option(ne,ne)));const L=Z.includes(v?.entry)?v.entry:Z[0];L&&(s.value=L),await H()}async function I(v=""){g=(await P("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(ge=>new Option(ge.name,ge.id))),V&&(i.value=V);const L=g.find(ge=>ge.id===i.value),ne=L?.files||[];s.replaceChildren(...ne.map(ge=>new Option(ge,ge))),s.value=ne.includes(v)?v:ne.includes(E)?E:L?.entry||ne[0]}async function H(){if(!i.value||!s.value)return;const v=new URLSearchParams({package:i.value,path:s.value}),Z=await P(`/api/v1/document?${v}`),L=`${i.value}/${s.value}`;V=i.value,E=s.value,S=Z.revision,w=Z.content,U=null,h.hidden=!0,_t(Z.content,L,0),il(q,g.find(ge=>ge.id===V)?.files??[]),M.open({documentID:L,packageID:V,path:E,revision:Z.revision,content:Z.content}),Xi(!!Z.readOnly),ce(Z);const ne=jS(window.localStorage,L,Z.content,Z.revision);c.hidden=!ne,c._draft=ne,document.querySelector("#recovery-message").textContent=ne?.isStale?"The device version also changed. Review before saving.":"Restore it or keep the device version.",r.textContent="Connected",Q({type:"CONNECTED"}),o.hidden=!1,Oe(),ae(),Me()}function ce(v){document.querySelector("#breadcrumb-package").textContent=v.packageName||i.value,document.querySelector("#breadcrumb-file").textContent=s.value,document.querySelector("#editor-tab-name").textContent=s.value,document.querySelector("#revision-detail").textContent=S?S.slice(0,8):"—",document.querySelector("#access-detail").textContent=v.readOnly?"Read only":"Editable"}function W(v){v.device&&(document.querySelector("#device-name").textContent=v.device.name||v.device.model,document.querySelector("#device-system").textContent=`${v.device.model} · ${v.device.system}`),v.preview?.package&&(document.querySelector("#preview-target").textContent=v.preview.package),v.preview?.snapshotSequence&&te()}async function te(){try{const v=await D.requestBlob("/api/v1/preview"),Z=URL.createObjectURL(v),L=document.querySelector("#device-preview"),ne=k;k=Z,L.onload=()=>{ne&&URL.revokeObjectURL(ne)},L.src=Z,L.hidden=!1,document.querySelector("#preview-detail").textContent="Rendered on device"}catch{}}function re(v){const Z=document.querySelector("#console-list"),L=document.createElement("li");for(L.className=v.level||"info",L.textContent=v.message||"",Z.append(L);Z.children.length>200;)Z.firstChild.remove();Z.scrollTop=Z.scrollHeight}function Me(){window.clearTimeout(x);const v=async()=>{if(m)try{const Z=await P(`/api/v1/events?after=${C}`);C=Z.nextSequence??C;for(const L of Z.events||[])L.type==="console"&&re(L.payload||{}),L.type==="preview.snapshot"&&te(),L.type==="preview.requested"&&(document.querySelector("#status-preview").textContent="Preview requested",document.querySelector("#preview-detail").textContent="Requested on device"),L.type==="files.changed"&&L.payload?.package===V&&I(E).catch(Ie);Q({type:"CONNECTED"})}catch(Z){Z.status!==401&&Q({type:"OFFLINE"})}finally{m&&(x=window.setTimeout(v,1e3))}};v()}function Oe(){const v=Ed(q);document.querySelector("#problems-list").replaceChildren(...v.map(L=>{const ne=q.state.doc.lineAt(L.from),ge=document.createElement("li");ge.className=`problem-item ${L.severity}`;const it=document.createElement("button");return it.type="button",it.innerHTML=`${L.severity==="error"?"●":"▲"}Ln ${ne.number}`,it.children[1].textContent=L.message,it.addEventListener("click",()=>{q.dispatch({selection:{anchor:L.from},scrollIntoView:!0}),q.focus()}),ge.append(it),ge})),document.querySelector("#problems-count").textContent=String(v.length),document.querySelector("#status-problem-count").textContent=String(v.length),document.querySelector("#problems-summary").textContent=v.length?`${v.filter(L=>L.severity==="error").length} errors, ${v.filter(L=>L.severity!=="error").length} warnings`:"No problems detected"}async function ie(v,Z,L=null){M.snapshot()?.content!==v&&M.edit(v),L&&M.rebase(L),Q({type:"SAVING"});try{const ne=await M.flush();if(ne.ignored){Z({result:"ok",ignored:!0});return}if(ne.skipped){Q({type:"SAVED"}),Z({result:"ok",skipped:!0});return}const ge=ne.result||{},it=M.snapshot();S=it?.revision||S,w=it?.content||v,fo(window.localStorage,me),U=null,h.hidden=!0,document.querySelector("#revision-detail").textContent=S?.slice(0,8)||"—",Q({type:"SAVED",preview:ge.preview?.state}),Z({result:"ok",...ge})}catch(ne){ne.status===409?(U=ne.body,h.hidden=!1,Q({type:"CONFLICT",conflict:U})):Q({type:"SAVE_FAILED"}),Z({result:"failed",message:ne.message})}}Wt={registerHandler(){},callHandler(v,Z,L=()=>{}){if(v===Ue.documentSave)ie(Z.payload.content,L);else if(v===Ue.documentResources){const ne=me,ge=V;P("/api/v1/packages").then(it=>{if(ne!==me||Z.documentID!==me||ge!==V){L({result:"failed"});return}L({result:"ok",documentID:ne,resources:(it.packages??[]).find(zn=>zn.id===ge)?.files??[]})}).catch(()=>L({result:"failed"}))}else L({result:"ok"})}},zd={documentChanged(){const v=q.state.doc.toString();M.edit(v),hh(window.localStorage,me,v,M.snapshot()?.revision||S),Q({type:"EDITED"}),window.clearTimeout(b),b=window.setTimeout(Oe,380)}};async function ve(v,Z){if(!uh(F.save)){await v();return}try{if(window.clearTimeout(Mn),await ie(q.state.doc.toString(),()=>{}),!M.isDirty&&F.save!=="conflict"){await v();return}}catch{}window.confirm("This document has changes that are not saved on the device. A browser draft is available. Switch anyway?")?await v():Z()}i.addEventListener("change",()=>{const v=i.value;i.value=V,ve(async()=>{i.value=v,await ee()},()=>{i.value=V}).catch(Ie)}),s.addEventListener("change",()=>{const v=s.value;s.value=E,ve(async()=>{s.value=v,await H()},()=>{s.value=E}).catch(Ie)});function Ie(v){r.textContent=v.message||String(v),Q({type:"SAVE_FAILED"})}e.addEventListener("submit",async v=>{v.preventDefault(),t.textContent="";try{await j(document.querySelector("#pair-code").value),n.close(),await J()}catch(Z){t.textContent=Z.message}}),o.addEventListener("click",async()=>{try{await P("/api/v1/session",{method:"DELETE"})}catch{}Y("Disconnected. Start a new session with the code on your device.")}),document.querySelector("#new-file").addEventListener("click",async()=>{const v=window.prompt("New package-relative text file","source/helper.js")?.trim();if(v)try{await P("/api/v1/document",{method:"POST",body:JSON.stringify({package:V,path:v})}),await I(v),await H()}catch(Z){Ie(Z)}}),document.querySelector("#delete-file").addEventListener("click",async()=>{const v=g.find(Z=>Z.id===V);if(!E||E===v?.entry){window.alert("The widget entry file cannot be deleted.");return}if(window.confirm(`Delete ${E}? This cannot be undone.`))try{const Z=new URLSearchParams({package:V,path:E});await P(`/api/v1/document?${Z}`,{method:"DELETE"}),E="",await I(),await H()}catch(Z){Ie(Z)}}),document.querySelector("#clear-console").addEventListener("click",()=>document.querySelector("#console-list").replaceChildren()),document.querySelector("#restore-draft").addEventListener("click",()=>{const v=c._draft;v&&(_t(v.content,v.documentID,at+1),c.hidden=!0,hh(window.localStorage,me,v.content,S),Q({type:"EDITED"}),Oe())}),document.querySelector("#discard-draft").addEventListener("click",()=>{fo(window.localStorage,me),c.hidden=!0}),document.querySelector("#reload-server").addEventListener("click",()=>{U&&(fo(window.localStorage,me),S=U.currentRevision,w=U.currentContent,_t(w,me,at+1),M.open({documentID:me,packageID:V,path:E,revision:S,content:w}),U=null,h.hidden=!0,Q({type:"SAVED"}),Oe())}),document.querySelector("#keep-local").addEventListener("click",()=>{U&&ie(q.state.doc.toString(),()=>{},U.currentRevision)}),document.querySelector("#compare-conflict").addEventListener("click",()=>{document.querySelector("#compare-local").textContent=q.state.doc.toString(),document.querySelector("#compare-server").textContent=U?.currentContent||w,p.showModal()}),p.querySelector("button").addEventListener("click",()=>p.close());function oe(){const v=l.classList.toggle("problems-collapsed");document.querySelector("#problems-toggle").setAttribute("aria-expanded",String(!v))}function Ae(v){a.classList.toggle(`show-${v}`)}document.querySelector("#problems-toggle").addEventListener("click",oe),document.querySelector("#status-problems").addEventListener("click",()=>{l.classList.remove("problems-collapsed")}),document.querySelector("#explorer-button").addEventListener("click",()=>Ae("explorer")),document.querySelector("#inspector-button").addEventListener("click",()=>Ae("inspector")),document.querySelectorAll("[data-close-panel]").forEach(v=>v.addEventListener("click",()=>a.classList.remove(`show-${v.dataset.closePanel}`)));const le=[{name:"Save Document",keys:"⌘S",run:()=>{window.clearTimeout(Mn),ie(q.state.doc.toString(),()=>{})}},{name:"Format Document",keys:"⇧⌥F",run:lr},{name:"Toggle Problems",keys:"⌘J",run:oe},{name:"Toggle Explorer",keys:"⌘⇧E",run:()=>Ae("explorer")},{name:"Toggle Inspector",keys:"",run:()=>Ae("inspector")},{name:"Use Light Theme",keys:"",run:()=>cr("light")},{name:"Use Dark Theme",keys:"",run:()=>cr("dark")}];function We(v=""){const Z=le.filter(L=>L.name.toLowerCase().includes(v.toLowerCase()));d.replaceChildren(...Z.map(L=>{const ne=document.createElement("li"),ge=document.createElement("button");ge.type="button",ge.className="command";const it=document.createElement("span");it.textContent=L.name;const zn=document.createElement("kbd");return zn.textContent=L.keys,ge.append(it,zn),ge.addEventListener("click",()=>{u.close(),L.run()}),ne.append(ge),ne}))}function tt(){We(),u.showModal(),f.value="",f.focus()}document.querySelector("#command-button").addEventListener("click",tt),f.addEventListener("input",()=>We(f.value)),document.addEventListener("keydown",v=>{const Z=v.metaKey||v.ctrlKey;Z&&v.shiftKey&&v.key.toLowerCase()==="p"?(v.preventDefault(),tt()):Z&&v.key.toLowerCase()==="s"?(v.preventDefault(),le[0].run()):Z&&v.key.toLowerCase()==="j"?(v.preventDefault(),oe()):Z&&v.shiftKey&&v.key.toLowerCase()==="e"?(v.preventDefault(),Ae("explorer")):v.shiftKey&&v.altKey&&v.key.toLowerCase()==="f"&&(v.preventDefault(),lr())}),q.dom.addEventListener("keyup",ai),q.dom.addEventListener("mouseup",ai);function ai(){const v=q.state.selection.main.head,Z=q.state.doc.lineAt(v);document.querySelector("#cursor-position").textContent=`Ln ${Z.number}, Col ${v-Z.from+1}`}window.addEventListener("offline",()=>{r.textContent="Computer is offline",Q({type:"OFFLINE"})}),window.addEventListener("online",()=>{m&&P("/api/v1/session").then(v=>(W(v),Q({type:"CONNECTED"}),J())).catch(Ie)}),window.addEventListener("beforeunload",v=>{uh(F.save)&&(v.preventDefault(),v.returnValue="")});try{await J()}catch{Y("Pair with the code shown on your device.")}}window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener("change",()=>cr("system"));window.webkit||_t(`// ScriptWidget Studio +`;function qS(n,e){const t=i=>e?`{widgetTheme.${i}}`:JSON.stringify(or.Meadow[i]);if(n==="bloom")return``;if(n==="leaf")return``;if(n==="pebble")return``;throw new Error("Choose an original asset from the catalog.")}function zS(n,e,{id:t,kind:i,path:s},r=[]){if(n.source!==e||n.issue)throw new Error("Layout changed. Select the container again.");const o=n.nodes.find(f=>f.id===t);if(!o?.structure)throw new Error("Select a stack/grid with literal JSX children in Layout or Assets.");let a;if(i==="photo"){if(!Vd(r).includes(s))throw new Error("This image is no longer in the package resource list. Refresh images.");a=``}else{if(!Object.hasOwn(jd,i))throw new Error("Choose an original asset from the catalog.");a=qS(i,!!ar(e).tokens)}const l=[{from:o.contentTo,to:o.contentTo,insert:a}];let c=o.contentTo;if(i!=="photo"&&!e.includes(po)){const f=e.startsWith("#!")?e.indexOf(` +`)+1:0;l.push({from:f,to:f,insert:po}),c+=po.length}l.sort((f,d)=>f.from-d.from);let h=e;for(const f of[...l].reverse())h=h.slice(0,f.from)+f.insert+h.slice(f.to);if(vi(h).issue)throw new Error("This asset would exceed the supported layout limits. Your source was preserved.");return{changes:l,selectedFrom:c}}const VS=n=>["string","number","number|string","date|number","boolean","enum","color","url","action-id","storage-key"].includes(n.type);function B(n,e,t){const i=document.createElement(n);return e&&(i.className=e),t!==void 0&&(i.textContent=t),i}function jS(n,e){const t=B("section","sw-layout"),i=B("div","sw-layout-header"),s=B("div","sw-layout-body");t.setAttribute("aria-label","Visual layout editor");let r=!1,o="layout",a=null,l=null,c="",h=null,u=!1,f=0;const d=String(Math.random()),p=(v,M)=>k=>{if(u||!t.contains(v)){k.preventDefault();return}return M(k)},m=(v,M,k)=>v.addEventListener(M,p(v,k)),g=(v,M,k=!1)=>{const z=B("button","sw-layout-button",v);return z.type="button",z.disabled=k,m(z,"click",M),z},y=g("Layout",()=>{r=o==="layout"?!r:!0,o="layout",T(),n.requestMeasure()});y.classList.add("sw-layout-toggle"),y.setAttribute("aria-expanded","false");const x=B("span","sw-layout-hint","Select layers and edit literal JSX"),b=g("Undo",()=>Ia(n)),C=g("Redo",()=>js(n)),Q=g("Theme",()=>{r=o==="theme"?!r:!0,o="theme",T(),n.requestMeasure()});Q.setAttribute("aria-expanded","false");const P=g("Assets",()=>{r=o==="assets"?!r:!0,o="assets",T(),n.requestMeasure()});P.setAttribute("aria-expanded","false"),i.append(y,Q,P,x,b,C),t.append(i,s),s.hidden=b.hidden=C.hidden=!0;const w=B("p","sw-layout-error");w.setAttribute("role","alert"),w.hidden=!0,t.append(w);function L(){a=vi(n.state.doc.toString());const v=B("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(v),v.append(B("div","sw-layout-title","Widget assets")),v.append(B("p","sw-layout-notice","Insert editable original JSX or a package image. Originals follow connected theme colors; pet artwork is static. Import photos with the app's existing image tools or Web Studio's Add image.")),a.issue){v.append(B("p","sw-layout-notice",a.issue));return}const M=a.nodes.filter(q=>q.structure),k=B("select");k.setAttribute("aria-label","Asset destination");for(const q of M){const G=B("option","",`${q.tag} · line ${n.state.doc.lineAt(q.from).number}`);G.value=q.id,k.append(G)}M.some(q=>q.id===l)?k.value=l:l=k.value,m(k,"change",()=>{l=k.value}),v.append(k);const z=n.state.readOnly||!M.length;M.length||v.append(B("p","sw-layout-notice","Add a stack/grid with literal JSX children in Code to insert assets."));function re(q,G){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const ce=zS(a,n.state.doc.toString(),{id:k.value,kind:q,path:G},n.state.field(lr));l=k.value,w.hidden=!0,n.dispatch({changes:ce.changes,selection:{anchor:ce.selectedFrom},annotations:Qs.of("full"),userEvent:"input.asset",scrollIntoView:!0})}catch(ce){w.textContent=ce.message,w.hidden=!1}}for(const[q,G]of Object.entries(jd)){const ce=B("div","sw-layout-actions");ce.append(g(`Insert ${G.name}`,()=>re(q),z),B("span","",G.description)),v.append(ce)}v.append(B("div","sw-layout-title","Package images"));const N=n.state.field(lr),ee=B("select");ee.setAttribute("aria-label","Package image");for(const q of N){const G=B("option","",q);G.value=q,ee.append(G)}ee.disabled=!N.length,v.append(ee,g("Insert package image",()=>re("photo",ee.value),z||!N.length)),N.length||v.append(B("p","sw-layout-notice","No supported images in image/. Add a PNG, JPEG or WebP to the package, then refresh or reopen the editor.")),e.refreshResources&&v.append(g("Refresh images",async()=>{const q=++f,G=n.state.doc,ce=()=>!u&&q===f&&n.state.doc===G;try{const V=await e.refreshResources();ce()&&(w.hidden=!0,rl(n,V))}catch{ce()&&(w.textContent="Images could not be refreshed. Reopen this document and try again.",w.hidden=!1)}})),v.append(B("p","sw-layout-notice","Bloom mark, Leaf mark and Pebble friend: original ScriptWidget geometry, MIT licensed. Package photos retain their own rights. See the Studio assets documentation."))}function D(v,M){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");const k=n.state.doc.toString();if(k!==M)throw new Error("Source changed. Reopen Theme before editing.");const z=v(k);w.hidden=!0,z.changes.length&&n.dispatch({changes:z.changes,annotations:Qs.of("full"),userEvent:"input.theme"})}catch(k){w.textContent=k.message,w.hidden=!1}}function W(){const v=n.state.doc.toString(),M=ar(v),k=n.state.readOnly,z=B("div","sw-layout-inspector sw-theme-inspector");if(s.replaceChildren(z),z.append(B("div","sw-layout-title","Widget theme")),z.append(B("p","sw-layout-notice","Saved as ordinary JavaScript with your widget. Dynamic values stay in Code. Applying a theme changes the connected colors, fonts and spacing.")),M.issue){z.append(B("p","sw-layout-notice",M.issue));return}if(!M.tokens){z.append(g("Connect layout to Meadow theme",()=>D(ee=>WS(ee),v),k||!M.canInitialize)),M.canInitialize||z.append(B("p","sw-layout-notice","Use a literal top-level $render layout, or define the documented widgetTheme object in Code."));return}const re=B("div","sw-layout-actions");for(const[ee,q]of Object.entries(or))re.append(g(ee,()=>D(G=>fo(M,G,q),v),k));z.append(re);for(const[ee,q]of Object.entries(Hi)){const G=B("form","sw-layout-form"),ce=B("label","",ee),V=B(q.values?"select":"input");if(q.values)for(const oe of q.values){const Me=B("option","",oe);Me.value=oe,V.append(Me)}q.type==="number"&&(V.type="number",V.min="0",V.max=String(q.maximum),V.step="any"),V.value=String(M.tokens[ee]),V.setAttribute("aria-label",`Theme ${ee}`),V.disabled=k;const te=g(`Apply ${ee}`,()=>{},k);te.type="submit",G.append(ce,V,te),m(G,"submit",oe=>{oe.preventDefault();const Me=q.type==="number"?V.value.trim()?Number(V.value):NaN:V.value;D(Oe=>fo(M,Oe,{...M.tokens,[ee]:Me}),v)}),z.append(G)}const N=B("textarea");N.rows=5,N.setAttribute("aria-label","Reusable theme JSON"),N.value=IS(M.tokens),z.append(B("label","","Copy this JSON to reuse a theme, or paste a version 1 theme and import it."),N,g("Import theme JSON",()=>D(ee=>fo(M,ee,zd(N.value).tokens),v),k))}function F(v,M=a?.source){if(!u)try{if(n.state.readOnly)throw new Error("This document is read only.");if(M!==n.state.doc.toString())throw new Error("Source changed during this operation. Select the layer again.");const k=BS(a,n.state.doc.toString(),v);if(w.hidden=!0,!k.changes.length)return;n.dispatch({changes:k.changes,selection:{anchor:k.selectedFrom},annotations:Qs.of("full"),userEvent:"input.layout",scrollIntoView:!0})}catch(k){w.textContent=k.message,w.hidden=!1}}function U(v){u||(l=v.id,c="",n.dispatch({selection:{anchor:v.from,head:v.to},scrollIntoView:!0,userEvent:"select.layout"}),T())}function T(){if(y.setAttribute("aria-expanded",String(r&&o==="layout")),Q.setAttribute("aria-expanded",String(r&&o==="theme")),P.setAttribute("aria-expanded",String(r&&o==="assets")),s.hidden=!r,b.hidden=C.hidden=!r,x.hidden=r,b.disabled=n.state.readOnly||Qc(n.state)===0,C.disabled=n.state.readOnly||Pc(n.state)===0,!r)return;if(o==="assets"){L();return}if(o==="theme"){W();return}if(a=vi(n.state.doc.toString()),s.replaceChildren(),a.issue){s.append(B("p","sw-layout-notice",a.issue));return}const v=n.state.selection.main.from,M=a.nodes.filter(V=>V.from<=v&&vV.id===l&&V.from<=v&&v<=V.to)??M??a.nodes[0];l=k.id;const z=B("div","sw-layout-layers");z.setAttribute("role","tree"),z.setAttribute("aria-label","Layout layers");const re=n.state.readOnly,N=V=>{const te=V.text??V.properties.find(oe=>oe.name==="text"&&oe.editable&&typeof oe.value=="string")?.value;return`<${V.tag}>${te?` · ${te.slice(0,32)}`:""}${V.locked?" · locked":""}`};for(const[V,te]of a.nodes.entries()){const oe=a.nodes.find(ie=>ie.id===te.parentID),Me=!re&&!te.locked&&oe?.structure,Oe=g(N(te),()=>U(te));Oe.classList.add("sw-layout-layer"),Oe.dataset.layerId=te.id,Oe.style.paddingInlineStart=`${8+te.depth*14}px`,Oe.setAttribute("role","treeitem"),Oe.setAttribute("aria-level",String(te.depth+1)),Oe.setAttribute("aria-selected",String(te.id===k.id)),Oe.tabIndex=te.id===k.id?0:-1,Oe.draggable=!!Me,m(Oe,"keydown",ie=>{let ve;ie.key==="ArrowUp"&&(ve=a.nodes[Math.max(0,V-1)]),ie.key==="ArrowDown"&&(ve=a.nodes[Math.min(a.nodes.length-1,V+1)]),ie.key==="ArrowLeft"&&(ve=oe),ie.key==="ArrowRight"&&(ve=a.nodes.find(Ie=>Ie.id===te.children[0])),ie.key==="Home"&&(ve=a.nodes[0]),ie.key==="End"&&(ve=a.nodes.at(-1)),ve&&(ie.preventDefault(),ie.stopPropagation(),U(ve),ee().find(Ie=>Ie.dataset.layerId===ve.id)?.focus())}),m(Oe,"dragstart",ie=>{if(!Me){ie.preventDefault();return}h={id:te.id,source:a.source},ie.dataTransfer.setData("application/x-scriptwidget-layer",d),ie.dataTransfer.effectAllowed="move"}),m(Oe,"dragover",ie=>{h&&oe?.structure&&te.id!==h.id&&(ie.preventDefault(),ie.dataTransfer.dropEffect="move")}),m(Oe,"drop",ie=>{if(!h||ie.dataTransfer.getData("application/x-scriptwidget-layer")!==d||!oe?.structure)return;ie.preventDefault();const ve=h;h=null,F({type:"move",id:ve.id,parentID:oe.id,index:oe.children.filter(Ie=>Ie!==ve.id).indexOf(te.id)},ve.source)}),m(Oe,"dragend",()=>{h=null}),z.append(Oe)}function ee(){return[...t.querySelectorAll(".sw-layout-layer")]}const q=B("div","sw-layout-inspector"),G=B("div","sw-layout-title",`<${k.tag}>`);if(q.append(G),(re||k.locked)&&q.append(B("p","sw-layout-notice",re?"This document is read only.":k.reason)),!re&&!k.locked){let Oe=function(){c=oe.value;const ae=da(k)[c],Ae=k.properties.find(tt=>tt.name===c);if(Me.replaceChildren(),te.onsubmit=tt=>tt.preventDefault(),Ae&&!Ae.editable){Me.append(B("span","sw-layout-notice","Dynamic value: edit it in Code. Connected widgetTheme tokens can be changed in Theme."));return}const le=B(ae.values||ae.type==="boolean"?"select":"input");le.setAttribute("aria-label","Layout property value");for(const tt of ae.values??(ae.type==="boolean"?[!0,!1]:[])){const li=B("option","",String(tt));li.value=String(tt),le.append(li)}le.value=Ae?String(Ae.value):ae.values?.[0]??(ae.type==="boolean"?"true":"");const We=g("Apply",()=>{});We.type="submit",Me.append(le,We,g("Remove",()=>F({type:"property",id:k.id,name:c,remove:!0}),!Ae||ae.required)),te.onsubmit=p(te,tt=>{tt.preventDefault();const li=ae.type==="boolean"?le.value==="true":ae.type==="number"?le.value.trim()?Number(le.value):NaN:le.value;F({type:"property",id:k.id,name:c,value:li})})};if(k.textEditable){const ae=B("form","sw-layout-form"),Ae=B("label","","Text"),le=B("input");le.value=k.text,le.setAttribute("aria-label","Layer text");const We=g("Apply text",()=>{});We.type="submit",ae.append(Ae,le,We),m(ae,"submit",tt=>{tt.preventDefault(),F({type:"text",id:k.id,value:le.value})}),q.append(ae)}const V=Object.entries(da(k)).filter(([,ae])=>VS(ae)),te=B("form","sw-layout-form"),oe=B("select");oe.setAttribute("aria-label","Layout property");for(const[ae]of V){const Ae=B("option","",ae);Ae.value=ae,oe.append(Ae)}V.some(([ae])=>ae===c)||(c=k.structure?"alignment":"color"),oe.value=c,oe.value||(oe.selectedIndex=0,c=oe.value);const Me=B("div","sw-layout-property");te.append(oe,Me),m(oe,"change",Oe),Oe(),q.append(te);const ie=a.nodes.find(ae=>ae.id===k.parentID),ve=ie?.children.indexOf(k.id)??-1,Ie=B("div","sw-layout-actions");if(Ie.append(g("Move up",()=>F({type:"move",id:k.id,parentID:ie.id,index:ve-1}),!ie?.structure||ve<=0),g("Move down",()=>F({type:"move",id:k.id,parentID:ie.id,index:ve+1}),!ie?.structure||ve>=ie.children.length-1),g("Delete layer",()=>F({type:"remove",id:k.id}),!ie?.structure)),q.append(Ie),ie?.structure){const ae=a.nodes.filter(le=>le.structure&&!(le.from>=k.from&&le.to<=k.to)),Ae=B("select");Ae.setAttribute("aria-label","Move layer into container");for(const le of ae){const We=B("option","",`${le.tag} · line ${n.state.doc.lineAt(le.from).number}`);We.value=le.id,Ae.append(We)}q.append(Ae,g("Move inside",()=>{const le=a.nodes.find(We=>We.id===Ae.value);F({type:"move",id:k.id,parentID:le.id,index:le.children.filter(We=>We!==k.id).length})},!ae.length))}if(k.structure){const ae=B("div","sw-layout-actions");for(const[Ae,le]of[["text","Add text"],["stack","Add stack"],["spacer","Add spacer"],["icon","Add icon"]])ae.append(g(le,()=>F({type:"add",id:k.id,kind:Ae})));q.append(ae)}}const ce=k.properties.filter(V=>!V.editable).map(V=>V.name);ce.length&&q.append(B("p","sw-layout-notice",`Preserved in Code: ${ce.join(", ")}`)),!k.structure&&k.children.length&&q.append(B("p","sw-layout-notice","This child structure stays in Code. Reordering is available on literal stack/grid children.")),s.append(z,q)}return{dom:t,top:!0,update(v){if(!r)return;const M=n.state.selection.main.from,k=a?.nodes.filter(re=>re.from<=M&&Mre.effects.some(N=>N.is(sl)));(v.docChanged||z||v.startState.readOnly!==n.state.readOnly||v.selectionSet&&k!==l)&&(v.docChanged&&o!=="assets"&&(l=null),T()),b.disabled=n.state.readOnly||Qc(n.state)===0,C.disabled=n.state.readOnly||Pc(n.state)===0},destroy(){u=!0}}}const YS=K.baseTheme({".sw-layout":{fontFamily:"system-ui, sans-serif",fontSize:"12px",backgroundColor:"#f6f7fa",color:"#272a34",borderBottom:"1px solid #dce0e9"},"&dark .sw-layout":{backgroundColor:"#252830",color:"#eceef5",borderColor:"#414552"},".sw-layout-header":{display:"flex",alignItems:"center",flexWrap:"wrap",gap:"8px",padding:"6px 10px"},".sw-layout-toggle":{fontWeight:"600"},".sw-layout-hint":{opacity:"0.65",fontSize:"11px"},".sw-layout-button":{fontFamily:"inherit",fontSize:"11px",color:"inherit",backgroundColor:"transparent",border:"1px solid #a0a5b655",borderRadius:"6px",padding:"4px 8px",cursor:"pointer",whiteSpace:"nowrap"},".sw-layout-button:disabled":{opacity:"0.4",cursor:"default"},".sw-layout-body":{display:"grid",gridTemplateColumns:"minmax(120px, 1fr) minmax(180px, 1.6fr)",maxHeight:"280px",overflow:"auto",borderTop:"1px solid #a0a5b633"},".sw-layout-body[hidden]":{display:"none"},".sw-layout-layers":{padding:"6px 2px",overflow:"auto",borderRight:"1px solid #a0a5b633"},".sw-layout-layer":{display:"block",border:0,borderRadius:"4px",width:"100%",textAlign:"left",overflow:"hidden",textOverflow:"ellipsis",margin:"1px 0",paddingBlock:"6px"},'.sw-layout-layer[aria-selected="true"]':{backgroundColor:"#4085f52b",color:"inherit"},".sw-layout-inspector":{padding:"8px 10px",display:"flex",alignItems:"start",flexDirection:"column",gap:"8px",minWidth:0},".sw-theme-inspector":{gridColumn:"1 / -1"},".sw-theme-inspector textarea":{boxSizing:"border-box",width:"100%",fontFamily:"monospace",backgroundColor:"transparent",color:"inherit",border:"1px solid #a0a5b666",borderRadius:"5px"},".sw-layout-title":{fontWeight:"600"},".sw-layout-form":{display:"flex",flexWrap:"wrap",alignItems:"center",gap:"5px",width:"100%"},".sw-layout-property,.sw-layout-actions":{display:"flex",flexWrap:"wrap",gap:"5px",alignItems:"center"},".sw-layout input,.sw-layout select":{fontFamily:"inherit",fontSize:"12px",minWidth:0,maxWidth:"100%",padding:"4px 6px",border:"1px solid #a0a5b666",borderRadius:"5px",backgroundColor:"transparent",color:"inherit"},".sw-layout-notice":{margin:"8px",lineHeight:"1.5",fontSize:"11px",opacity:"0.7"},".sw-layout-body > .sw-layout-notice":{gridColumn:"1 / -1"},".sw-layout-error":{margin:"0 10px 6px",color:"#b32636",fontSize:"12px"},"&dark .sw-layout-error":{color:"#ff99a4"},".sw-layout button:focus-visible,.sw-layout input:focus-visible,.sw-layout select:focus-visible":{outline:"2px solid #4085f5",outlineOffset:"1px"},"@media (max-width: 480px)":{".sw-layout-body":{gridTemplateColumns:"minmax(90px, 1fr) minmax(150px, 1.6fr)"},".sw-layout-hint":{display:"none"}}});function NS(n={}){return[YS,lr,Vi.of(e=>jS(e,n))]}const Yd="scriptwidget.studio.document-state.v1.";function Nd(n,e,t){if(!n||!e)return!1;try{return n.setItem(`${Yd}${e}`,JSON.stringify({anchor:Number(t.anchor)||0,head:Number(t.head)||0,scrollTop:Number(t.scrollTop)||0})),!0}catch{return!1}}function HS(n,e,t){if(!n||!e)return null;try{const i=JSON.parse(n.getItem(`${Yd}${e}`));if(!i||typeof i!="object")return null;const s=r=>Math.max(0,Math.min(Number(r)||0,t));return{anchor:s(i.anchor),head:s(i.head),scrollTop:Math.max(0,Number(i.scrollTop)||0)}}catch{return null}}const GS="scriptwidget.web-studio.draft.v1:";function ol(n){return`${GS}${n}`}function _S(n,e){if(!e)return null;try{const t=JSON.parse(n.getItem(ol(e))||"null");return t&&typeof t.content=="string"&&typeof t.baseRevision=="string"?t:null}catch{return null}}function ph(n,e,t,i,s=Date.now()){if(!e||typeof i!="string")return null;const r={documentID:e,content:t,baseRevision:i,updatedAt:s};return n.setItem(ol(e),JSON.stringify(r)),r}function mo(n,e){e&&n.removeItem(ol(e))}function JS(n,e,t,i){const s=_S(n,e);return!s||s.content===t?null:{...s,serverContent:t,serverRevision:i,isStale:s.baseRevision!==i}}function e1(){return{connection:"connecting",save:"idle",preview:"idle",conflict:null}}function t1(n,e){switch(e.type){case"CONNECTED":return{...n,connection:"connected"};case"OFFLINE":return{...n,connection:"offline",save:n.save==="saving"?"draft":n.save};case"DISCONNECTED":return{...n,connection:"disconnected"};case"EDITED":return{...n,save:"draft",conflict:null};case"SAVING":return{...n,save:"saving"};case"SAVED":return{...n,save:"saved",preview:e.preview||"requested",conflict:null};case"SAVE_FAILED":return{...n,save:"error"};case"CONFLICT":return{...n,save:"conflict",conflict:e.conflict};default:return n}}class i1{constructor(e){this.send=e,this.epoch=0,this.context=null,this.inFlight=null,this.needsFlush=!1}open({documentID:e,packageID:t,path:i,revision:s,content:r}){return this.epoch+=1,this.context={documentID:e,packageID:t,path:i,revision:s,content:r,generation:0,savedGeneration:0},this.needsFlush=!1,this.snapshot()}edit(e){return this.context?(this.context.content=e,this.context.generation+=1,this.snapshot()):null}rebase(e){return this.context&&(this.context.revision=e),this.snapshot()}get isDirty(){return!!(this.context&&this.context.generation!==this.context.savedGeneration)}snapshot(){return this.context?{...this.context,dirty:this.isDirty}:null}async flush(){if(!this.context||!this.isDirty)return{skipped:!0,snapshot:this.snapshot()};if(this.inFlight)return this.needsFlush=!0,this.inFlight.then(()=>this.isDirty?this.flush():{skipped:!0,snapshot:this.snapshot()});const e=this.epoch,t={...this.context};this.needsFlush=!1,this.inFlight=this.send({documentID:t.documentID,packageID:t.packageID,path:t.path,content:t.content,baseRevision:t.revision}).then(s=>this.epoch!==e||this.context?.documentID!==t.documentID?{ignored:!0,result:s,snapshot:this.snapshot()}:(this.context.revision=s.revision,this.context.savedGeneration=t.generation,{result:s,snapshot:this.snapshot()})).finally(()=>{this.inFlight=null});const i=await this.inFlight;return this.needsFlush&&this.isDirty?this.flush():i}}function mh(n){return["draft","saving","error","conflict"].includes(n)}class n1 extends Error{constructor(e,t,i={}){super(e),this.name="StudioAPIError",this.status=t,this.body=i}}class s1{constructor({fetchImpl:e=globalThis.fetch,token:t=()=>"",onUnauthorized:i=()=>{}}={}){if(typeof e!="function")throw new TypeError("A fetch implementation is required");this.fetchImpl=e,this.token=t,this.onUnauthorized=i}async request(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t)),s=await i.json().catch(()=>({}));return this.validate(i,e,s),s}async requestBlob(e,t={}){const i=await this.fetchImpl(e,this.authorizedOptions(t));if(!i.ok){const s=await i.json().catch(()=>({}));this.validate(i,e,s)}return i.blob()}authorizedOptions(e){return{...e,headers:{"Content-Type":"application/json","X-Studio-Token":this.token(),...e.headers||{}}}}validate(e,t,i){if(!e.ok){const s=new n1(i.message||`Request failed (${e.status})`,e.status,i);throw e.status===401&&t!=="/api/v1/pair"&&this.onUnauthorized(s),s}}}const al=/^https?:$/.test(window.location.protocol)&&!window.ScriptWidgetAndroid,r1=document.querySelector(al?"#editor":"#native-editor"),ll=new Gi,cr=new Gi;let qt=null,me=null,Et=null,at=0,wi=0,pa=!1,En=null,gh=null;const Oh=document.querySelector("#save-status");let Hd=null;function Un(n,e="idle"){Oh.textContent=n,Oh.dataset.state=e}function o1(){window.clearTimeout(gh),gh=window.setTimeout(()=>{const n=j.state.selection.main;Nd(window.localStorage,me,{anchor:n.anchor,head:n.head,scrollTop:j.scrollDOM.scrollTop})},180)}function Gd(){return window.matchMedia?.("(prefers-color-scheme: dark)").matches?"dark":"light"}function cl(){window.clearTimeout(En),Un("Saving…","saving"),En=window.setTimeout(()=>{const n=j.state.doc.toString(),e=at,t=me,i=Et,s=wi;nn(qt,Ue.documentSave,{content:n,version:e},t,(r={})=>{al||t!==me||i!==Et||s!==wi||e!==at||Un(r.result==="ok"||r.result==="unavailable"?"Saved":"Save failed",r.result==="failed"?"error":"saved")},i)},700)}function a1(n){if((n.selectionSet||n.viewportChanged||n.docChanged)&&o1(),!n.docChanged||pa)return;at+=1,Hd?.documentChanged();const e=[];n.changes.iterChanges((t,i,s,r,o)=>{e.push({from:t,to:i,insert:o.toString(),newFrom:s,newTo:r})}),nn(qt,Ue.documentChanged,{changes:e,version:at},me,void 0,Et),cl()}const _d=[lO(),uO(),Pg(),T0(),NS({refreshResources:()=>new Promise((n,e)=>{const t=me,i=wi,s=Et,r=window.setTimeout(()=>e(new Error("Resource refresh timed out")),5e3);nn(qt,Ue.documentResources,{},t,(o={})=>{window.clearTimeout(r),t!==me||i!==wi||o.result!=="ok"||o.documentID!==t||!Array.isArray(o.resources)?e(new Error("Document resources are unavailable")):n(o.resources)},s)})}),t0(),mg(),Sg(),J.allowMultipleSelections.of(!0),BO(),p0(),gA(),PA({override:[RS],activateOnTyping:!0}),Lg(),Ig(),Zg(),$b(),OS(),aS(Ld,{delay:350}),Lu($S),vb({jsx:!0}),Or.of([Ky,...bA,...$y,..._b,...D0,...GO,...ad]),ll.of(J.readOnly.of(!1)),cr.of(Xd(Gd())),K.updateListener.of(a1),K.contentAttributes.of({autocapitalize:"off",autocomplete:"off",spellcheck:"false"})],j=new K({state:J.create({doc:"",extensions:_d}),parent:r1});function Jt(n,e=me,t=0,i=!1){window.clearTimeout(En),wi+=1;const s=j.state.selection.main;Nd(window.localStorage,me,{anchor:s.anchor,head:s.head,scrollTop:j.scrollDOM.scrollTop}),pa=!0;const r=e!==me;me=e,at=t;const o=HS(window.localStorage,me,(n??"").length),a=o?{anchor:o.anchor,head:o.head}:{anchor:0};if(r){const l=cr.get(j.state),c=j.state.readOnly;let h=J.create({doc:n??"",extensions:_d,selection:a});h=h.update({effects:[cr.reconfigure(l),ll.reconfigure(J.readOnly.of(c))]}).state,j.setState(h)}else j.dispatch({changes:{from:0,to:j.state.doc.length,insert:n??""},selection:a,scrollIntoView:!0});o&&window.requestAnimationFrame(()=>{j.scrollDOM.scrollTop=o.scrollTop}),pa=!1,i&&nn(qt,Ue.documentChanged,{content:j.state.doc.toString(),version:at},me,void 0,Et),Un("Saved","saved")}function yh(n){if(j.state.readOnly)return!1;const e=j.state.selection.main;return j.dispatch({changes:{from:e.from,to:e.to,insert:n},selection:{anchor:e.from+n.length},userEvent:"input"}),j.focus(),!0}async function hr(){if(j.state.readOnly)return!1;const n=j.state.doc.toString(),e=wi,t=at,i=()=>!j.state.readOnly&&e===wi&&t===at&&n===j.state.doc.toString();try{const[{format:s},{default:r},{default:o}]=await Promise.all([Rr(()=>import("./standalone-Cayz_KD-.js"),[],import.meta.url),Rr(()=>import("./babel-BktJt1uC.js"),[],import.meta.url),Rr(()=>import("./estree-DFfjoHvx.js"),[],import.meta.url)]),a=await s(n,{parser:"babel",plugins:[r,o],semi:!0,singleQuote:!0,trailingComma:"es5"});return i()?(Jt(a,me,at+1,!0),cl(),!0):!1}catch(s){return i()&&nn(qt,"diagnostics.publish",{message:String(s),severity:"error"},me,void 0,Et),!1}}function Xi(n){j.dispatch({effects:ll.reconfigure(J.readOnly.of(!!n))})}function ur(n){const e=n==="dark"||n==="light"?n:Gd();document.documentElement.dataset.theme=e,j.dispatch({effects:cr.reconfigure(Xd(e))})}function l1(n=[]){const e=n.map(t=>({from:Math.max(0,Math.min(t.from??0,j.state.doc.length)),to:Math.max(0,Math.min(t.to??t.from??0,j.state.doc.length)),severity:t.severity??"error",message:t.message??"Unknown error"}));j.dispatch(Pd(j.state,e))}function rt(n,e){qt.registerHandler(n,async(t={},i=()=>{})=>{try{if(Et!==null&&n!==Ue.documentOpen&&n!==Ue.editorSetTheme&&(t.documentID!==me||t.sessionID!==Et))throw new Error("The editor session changed.");i({result:"ok",...await e(t)})}catch(s){i({result:"failed",message:String(s)})}})}AS(n=>{qt=n,rt(Ue.documentOpen,({payload:e={},documentID:t,sessionID:i=null})=>(Et=i,Jt(e.content,t,e.version??0),rl(j,e.resources??[]),Xi(e.readOnly),e.dirty&&(Un("Restored unsaved edits","editing"),e.readOnly||cl()),{protocolVersion:Fd})),rt(Ue.documentReplace,({payload:e={},documentID:t})=>{if(j.state.readOnly||e.expectedContent!==void 0&&e.expectedContent!==j.state.doc.toString())throw new Error("The file changed or is read only.");return Jt(e.content,t,e.version??at,!0),{}}),rt(Ue.documentSetReadOnly,({payload:e={}})=>(Xi(e.readOnly),{readOnly:!!e.readOnly})),rt(Ue.editorInsert,({payload:e={}})=>({inserted:yh(e.content??"")})),rt(Ue.editorFormat,async()=>({formatted:await hr()})),rt(Ue.editorSetTheme,({payload:e={}})=>(ur(e.theme),{})),rt(Ue.editorGetState,()=>({content:j.state.doc.toString(),version:at,documentID:me,sessionID:Et,selection:{from:j.state.selection.main.from,to:j.state.selection.main.to}})),rt(Ue.diagnosticsPublish,({payload:e={}})=>(l1(e.items),{})),rt("editor_setValue",({value:e})=>(Jt(e),{})),rt("editor_insertValue",({value:e})=>({inserted:yh(e??"")})),rt("editor_getValue",()=>({value:j.state.doc.toString()})),rt("editor_setReadonly",({readonly:e})=>(Xi(e),{readonly:!!e})),rt("editor_formatCode",async()=>({formatted:await hr()})),bS(qt)});al&&(document.querySelector("#native-editor").hidden=!0,document.querySelector("#web-studio").hidden=!1,c1());async function c1(){const n=document.querySelector("#pair-dialog"),e=document.querySelector("#pair-form"),t=document.querySelector("#pair-error"),i=document.querySelector("#package-select"),s=document.querySelector("#file-select"),r=document.querySelector("#connection-status"),o=document.querySelector("#disconnect-button"),a=document.querySelector("#studio-grid"),l=document.querySelector(".editor-column"),c=document.querySelector("#recovery-banner"),h=document.querySelector("#conflict-banner"),u=document.querySelector("#command-dialog"),f=document.querySelector("#command-search"),d=document.querySelector("#command-list"),p=document.querySelector("#compare-dialog");let m=window.sessionStorage.getItem("scriptwidget.web-studio.token")||"",g=[],y=null,x=null,b=null,C=0,Q=null,P="",w="",L=null,D=e1(),W="",F="",U=null;function T(S="Session ended. Enter the new code shown on your device."){m="",window.sessionStorage.removeItem("scriptwidget.web-studio.token"),o.hidden=!0,v({type:"DISCONNECTED"}),r.textContent=S,Xi(!0),n.open||n.showModal()}function v(S){D=t1(D,S);const E={connecting:"Connecting",connected:"Connected",offline:"Offline",disconnected:"Disconnected"},X={idle:"Ready",draft:"Draft saved locally",saving:"Saving…",saved:"Saved",error:"Save failed",conflict:"Conflict"};r.dataset.state=D.connection,document.querySelector("#status-connection").textContent=E[D.connection]||D.connection,Un(X[D.save]||D.save,D.save),document.querySelector("#dirty-indicator").hidden=!["draft","saving","error","conflict"].includes(D.save),document.querySelector("#status-preview").textContent=D.preview==="requested"?"Preview requested":"Preview idle",document.querySelector("#preview-detail").textContent=D.preview==="requested"?"Requested on device":"Not requested"}const M=new s1({token:()=>m,onUnauthorized:()=>T()}),k=(S,E)=>M.request(S,E);U=new i1(({packageID:S,path:E,content:X,baseRevision:ne})=>k("/api/v1/document",{method:"PUT",body:JSON.stringify({package:S,path:E,content:X,baseRevision:ne})}));async function z(S){m=(await k("/api/v1/pair",{method:"POST",body:JSON.stringify({code:S})})).token,window.sessionStorage.setItem("scriptwidget.web-studio.token",m),o.hidden=!1,v({type:"CONNECTED"}),re()}function re(){window.clearInterval(y),y=window.setInterval(async()=>{if(m)try{const S=await k("/api/v1/session");if(!navigator.onLine)return;V(S),v({type:"CONNECTED"})}catch(S){S.status!==401&&(r.textContent=`Interrupted · ${S.message}`,v({type:"OFFLINE"}))}},5e3)}async function N(){if(g=(await k("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(E=>new Option(E.name,E.id))),!g.length){r.textContent="No editable widgets",Xi(!0);return}await ee()}async function ee(){const S=g.find(ne=>ne.id===i.value),E=S?.files||[];s.replaceChildren(...E.map(ne=>new Option(ne,ne)));const X=E.includes(S?.entry)?S.entry:E[0];X&&(s.value=X),await G()}async function q(S=""){g=(await k("/api/v1/packages")).packages||[],i.replaceChildren(...g.map(ge=>new Option(ge.name,ge.id))),W&&(i.value=W);const X=g.find(ge=>ge.id===i.value),ne=X?.files||[];s.replaceChildren(...ne.map(ge=>new Option(ge,ge))),s.value=ne.includes(S)?S:ne.includes(F)?F:X?.entry||ne[0]}async function G(){if(!i.value||!s.value)return;const S=new URLSearchParams({package:i.value,path:s.value}),E=await k(`/api/v1/document?${S}`),X=`${i.value}/${s.value}`;W=i.value,F=s.value,P=E.revision,w=E.content,L=null,h.hidden=!0,Jt(E.content,X,0),rl(j,g.find(ge=>ge.id===W)?.files??[]),U.open({documentID:X,packageID:W,path:F,revision:E.revision,content:E.content}),Xi(!!E.readOnly),ce(E);const ne=JS(window.localStorage,X,E.content,E.revision);c.hidden=!ne,c._draft=ne,document.querySelector("#recovery-message").textContent=ne?.isStale?"The device version also changed. Review before saving.":"Restore it or keep the device version.",r.textContent="Connected",v({type:"CONNECTED"}),o.hidden=!1,Oe(),re(),Me()}function ce(S){document.querySelector("#breadcrumb-package").textContent=S.packageName||i.value,document.querySelector("#breadcrumb-file").textContent=s.value,document.querySelector("#editor-tab-name").textContent=s.value,document.querySelector("#revision-detail").textContent=P?P.slice(0,8):"—",document.querySelector("#access-detail").textContent=S.readOnly?"Read only":"Editable"}function V(S){S.device&&(document.querySelector("#device-name").textContent=S.device.name||S.device.model,document.querySelector("#device-system").textContent=`${S.device.model} · ${S.device.system}`),S.preview?.package&&(document.querySelector("#preview-target").textContent=S.preview.package),S.preview?.snapshotSequence&&te()}async function te(){try{const S=await M.requestBlob("/api/v1/preview"),E=URL.createObjectURL(S),X=document.querySelector("#device-preview"),ne=Q;Q=E,X.onload=()=>{ne&&URL.revokeObjectURL(ne)},X.src=E,X.hidden=!1,document.querySelector("#preview-detail").textContent="Rendered on device"}catch{}}function oe(S){const E=document.querySelector("#console-list"),X=document.createElement("li");for(X.className=S.level||"info",X.textContent=S.message||"",E.append(X);E.children.length>200;)E.firstChild.remove();E.scrollTop=E.scrollHeight}function Me(){window.clearTimeout(b);const S=async()=>{if(m)try{const E=await k(`/api/v1/events?after=${C}`);C=E.nextSequence??C;for(const X of E.events||[])X.type==="console"&&oe(X.payload||{}),X.type==="preview.snapshot"&&te(),X.type==="preview.requested"&&(document.querySelector("#status-preview").textContent="Preview requested",document.querySelector("#preview-detail").textContent="Requested on device"),X.type==="files.changed"&&X.payload?.package===W&&q(F).catch(Ie);v({type:"CONNECTED"})}catch(E){E.status!==401&&v({type:"OFFLINE"})}finally{m&&(b=window.setTimeout(S,1e3))}};S()}function Oe(){const S=Ld(j);document.querySelector("#problems-list").replaceChildren(...S.map(X=>{const ne=j.state.doc.lineAt(X.from),ge=document.createElement("li");ge.className=`problem-item ${X.severity}`;const it=document.createElement("button");return it.type="button",it.innerHTML=`${X.severity==="error"?"●":"▲"}Ln ${ne.number}`,it.children[1].textContent=X.message,it.addEventListener("click",()=>{j.dispatch({selection:{anchor:X.from},scrollIntoView:!0}),j.focus()}),ge.append(it),ge})),document.querySelector("#problems-count").textContent=String(S.length),document.querySelector("#status-problem-count").textContent=String(S.length),document.querySelector("#problems-summary").textContent=S.length?`${S.filter(X=>X.severity==="error").length} errors, ${S.filter(X=>X.severity!=="error").length} warnings`:"No problems detected"}async function ie(S,E,X=null){U.snapshot()?.content!==S&&U.edit(S),X&&U.rebase(X),v({type:"SAVING"});try{const ne=await U.flush();if(ne.ignored){E({result:"ok",ignored:!0});return}if(ne.skipped){v({type:"SAVED"}),E({result:"ok",skipped:!0});return}const ge=ne.result||{},it=U.snapshot();P=it?.revision||P,w=it?.content||S,mo(window.localStorage,me),L=null,h.hidden=!0,document.querySelector("#revision-detail").textContent=P?.slice(0,8)||"—",v({type:"SAVED",preview:ge.preview?.state}),E({result:"ok",...ge})}catch(ne){ne.status===409?(L=ne.body,h.hidden=!1,v({type:"CONFLICT",conflict:L})):v({type:"SAVE_FAILED"}),E({result:"failed",message:ne.message})}}qt={registerHandler(){},callHandler(S,E,X=()=>{}){if(S===Ue.documentSave)ie(E.payload.content,X);else if(S===Ue.documentResources){const ne=me,ge=W;k("/api/v1/packages").then(it=>{if(ne!==me||E.documentID!==me||ge!==W){X({result:"failed"});return}X({result:"ok",documentID:ne,resources:(it.packages??[]).find(Vn=>Vn.id===ge)?.files??[]})}).catch(()=>X({result:"failed"}))}else X({result:"ok"})}},Hd={documentChanged(){const S=j.state.doc.toString();U.edit(S),ph(window.localStorage,me,S,U.snapshot()?.revision||P),v({type:"EDITED"}),window.clearTimeout(x),x=window.setTimeout(Oe,380)}};async function ve(S,E){if(!mh(D.save)){await S();return}try{if(window.clearTimeout(En),await ie(j.state.doc.toString(),()=>{}),!U.isDirty&&D.save!=="conflict"){await S();return}}catch{}window.confirm("This document has changes that are not saved on the device. A browser draft is available. Switch anyway?")?await S():E()}i.addEventListener("change",()=>{const S=i.value;i.value=W,ve(async()=>{i.value=S,await ee()},()=>{i.value=W}).catch(Ie)}),s.addEventListener("change",()=>{const S=s.value;s.value=F,ve(async()=>{s.value=S,await G()},()=>{s.value=F}).catch(Ie)});function Ie(S){r.textContent=S.message||String(S),v({type:"SAVE_FAILED"})}e.addEventListener("submit",async S=>{S.preventDefault(),t.textContent="";try{await z(document.querySelector("#pair-code").value),n.close(),await N()}catch(E){t.textContent=E.message}}),o.addEventListener("click",async()=>{try{await k("/api/v1/session",{method:"DELETE"})}catch{}T("Disconnected. Start a new session with the code on your device.")}),document.querySelector("#new-file").addEventListener("click",async()=>{const S=window.prompt("New package-relative text file","source/helper.js")?.trim();if(S)try{await k("/api/v1/document",{method:"POST",body:JSON.stringify({package:W,path:S})}),await q(S),await G()}catch(E){Ie(E)}}),document.querySelector("#delete-file").addEventListener("click",async()=>{const S=g.find(E=>E.id===W);if(!F||F===S?.entry){window.alert("The widget entry file cannot be deleted.");return}if(window.confirm(`Delete ${F}? This cannot be undone.`))try{const E=new URLSearchParams({package:W,path:F});await k(`/api/v1/document?${E}`,{method:"DELETE"}),F="",await q(),await G()}catch(E){Ie(E)}}),document.querySelector("#clear-console").addEventListener("click",()=>document.querySelector("#console-list").replaceChildren()),document.querySelector("#restore-draft").addEventListener("click",()=>{const S=c._draft;S&&(Jt(S.content,S.documentID,at+1),c.hidden=!0,ph(window.localStorage,me,S.content,P),v({type:"EDITED"}),Oe())}),document.querySelector("#discard-draft").addEventListener("click",()=>{mo(window.localStorage,me),c.hidden=!0}),document.querySelector("#reload-server").addEventListener("click",()=>{L&&(mo(window.localStorage,me),P=L.currentRevision,w=L.currentContent,Jt(w,me,at+1),U.open({documentID:me,packageID:W,path:F,revision:P,content:w}),L=null,h.hidden=!0,v({type:"SAVED"}),Oe())}),document.querySelector("#keep-local").addEventListener("click",()=>{L&&ie(j.state.doc.toString(),()=>{},L.currentRevision)}),document.querySelector("#compare-conflict").addEventListener("click",()=>{document.querySelector("#compare-local").textContent=j.state.doc.toString(),document.querySelector("#compare-server").textContent=L?.currentContent||w,p.showModal()}),p.querySelector("button").addEventListener("click",()=>p.close());function ae(){const S=l.classList.toggle("problems-collapsed");document.querySelector("#problems-toggle").setAttribute("aria-expanded",String(!S))}function Ae(S){a.classList.toggle(`show-${S}`)}document.querySelector("#problems-toggle").addEventListener("click",ae),document.querySelector("#status-problems").addEventListener("click",()=>{l.classList.remove("problems-collapsed")}),document.querySelector("#explorer-button").addEventListener("click",()=>Ae("explorer")),document.querySelector("#inspector-button").addEventListener("click",()=>Ae("inspector")),document.querySelectorAll("[data-close-panel]").forEach(S=>S.addEventListener("click",()=>a.classList.remove(`show-${S.dataset.closePanel}`)));const le=[{name:"Save Document",keys:"⌘S",run:()=>{window.clearTimeout(En),ie(j.state.doc.toString(),()=>{})}},{name:"Format Document",keys:"⇧⌥F",run:hr},{name:"Toggle Problems",keys:"⌘J",run:ae},{name:"Toggle Explorer",keys:"⌘⇧E",run:()=>Ae("explorer")},{name:"Toggle Inspector",keys:"",run:()=>Ae("inspector")},{name:"Use Light Theme",keys:"",run:()=>ur("light")},{name:"Use Dark Theme",keys:"",run:()=>ur("dark")}];function We(S=""){const E=le.filter(X=>X.name.toLowerCase().includes(S.toLowerCase()));d.replaceChildren(...E.map(X=>{const ne=document.createElement("li"),ge=document.createElement("button");ge.type="button",ge.className="command";const it=document.createElement("span");it.textContent=X.name;const Vn=document.createElement("kbd");return Vn.textContent=X.keys,ge.append(it,Vn),ge.addEventListener("click",()=>{u.close(),X.run()}),ne.append(ge),ne}))}function tt(){We(),u.showModal(),f.value="",f.focus()}document.querySelector("#command-button").addEventListener("click",tt),f.addEventListener("input",()=>We(f.value)),document.addEventListener("keydown",S=>{const E=S.metaKey||S.ctrlKey;E&&S.shiftKey&&S.key.toLowerCase()==="p"?(S.preventDefault(),tt()):E&&S.key.toLowerCase()==="s"?(S.preventDefault(),le[0].run()):E&&S.key.toLowerCase()==="j"?(S.preventDefault(),ae()):E&&S.shiftKey&&S.key.toLowerCase()==="e"?(S.preventDefault(),Ae("explorer")):S.shiftKey&&S.altKey&&S.key.toLowerCase()==="f"&&(S.preventDefault(),hr())}),j.dom.addEventListener("keyup",li),j.dom.addEventListener("mouseup",li);function li(){const S=j.state.selection.main.head,E=j.state.doc.lineAt(S);document.querySelector("#cursor-position").textContent=`Ln ${E.number}, Col ${S-E.from+1}`}window.addEventListener("offline",()=>{r.textContent="Computer is offline",v({type:"OFFLINE"})}),window.addEventListener("online",()=>{m&&k("/api/v1/session").then(S=>(V(S),v({type:"CONNECTED"}),N())).catch(Ie)}),window.addEventListener("beforeunload",S=>{mh(D.save)&&(S.preventDefault(),S.returnValue="")});try{await N()}catch{T("Pair with the code shown on your device.")}}window.matchMedia?.("(prefers-color-scheme: dark)").addEventListener("change",()=>ur("system"));window.webkit||Jt(`// ScriptWidget Studio const widget = ( diff --git a/macOS/ScriptWidgetMac/StudioEditor.bundle/index.html b/macOS/ScriptWidgetMac/StudioEditor.bundle/index.html index 8ce4827a..e6b4066a 100644 --- a/macOS/ScriptWidgetMac/StudioEditor.bundle/index.html +++ b/macOS/ScriptWidgetMac/StudioEditor.bundle/index.html @@ -5,7 +5,7 @@ ScriptWidget Web Studio - +