// ==UserScript== // @name RuleDesk Web // @namespace https://github.com/kazekaze93/ruledesk-web // @version 0.62.0 // @description Collections, playlists, favorites, artist updates, and page tweaks for rule34.xxx // @downloadURL https://raw.githubusercontent.com/KazeKaze93/RuleDesk/main/dist/ruledesk-web.user.js // @updateURL https://raw.githubusercontent.com/KazeKaze93/RuleDesk/main/dist/ruledesk-web.user.js // @match https://rule34.xxx/* // @grant GM_download // @grant GM_getValue // @grant GM_info // @grant GM_setValue // @run-at document-start // ==/UserScript== !function(){function e(e,t){return(t||"")+" (SystemJS Error#"+e+" https://github.com/systemjs/systemjs/blob/main/docs/errors.md#"+e+")"}function t(e,t){if(-1!==e.indexOf("\\")&&(e=e.replace(j,"/")),"/"===e[0]&&"/"===e[1])return t.slice(0,t.indexOf(":")+1)+e;if("."===e[0]&&("/"===e[1]||"."===e[1]&&("/"===e[2]||2===e.length&&(e+="/"))||1===e.length&&(e+="/"))||"/"===e[0]){var n,r=t.slice(0,t.indexOf(":")+1);if(n="/"===t[r.length+1]?"file:"!==r?(n=t.slice(r.length+2)).slice(n.indexOf("/")+1):t.slice(8):t.slice(r.length+("/"===t[r.length])),"/"===e[0])return t.slice(0,t.length-n.length-1)+e;for(var i=n.slice(0,n.lastIndexOf("/")+1)+e,o=[],s=-1,u=0;un.length&&"/"!==r[r.length-1]))return r+e.slice(n.length);u("W2",n,r,"should have a trailing '/'")}}function u(t,n,r,i){console.warn(e(t,"Package target "+i+", resolving target '"+r+"' for "+n))}function c(e,t,n){for(var r=e.scopes,i=n&&o(n,r);i;){var u=s(t,r[i]);if(u)return u;i=o(i.slice(0,i.lastIndexOf("/")),r)}return s(t,e.imports)||-1!==t.indexOf(":")&&t}function a(){this[M]={}}function f(e){return e.id}function l(e,t,n,r){if(e.onload(n,t.id,t.d&&t.d.map(f),!!r),n)throw n}function d(t,n,r,i){var o=t[M][n];if(o)return o;var s=[],u=Object.create(null);P&&Object.defineProperty(u,P,{value:"Module"});var c=Promise.resolve().then((function(){return t.instantiate(n,r,i)})).then((function(r){if(!r)throw Error(e(2,"Module "+n+" did not instantiate"));var i=r[1]((function(e,t){o.h=!0;var n=!1;if("string"==typeof e)e in u&&u[e]===t||(u[e]=t,n=!0);else{for(var r in e)t=e[r],r in u&&u[r]===t||(u[r]=t,n=!0);e&&e.__esModule&&(u.__esModule=e.__esModule)}if(n)for(var i=0;i-1){var n=document.createEvent("Event");n.initEvent("error",!1,!1),t.dispatchEvent(n)}return Promise.reject(e)}))}else if("systemjs-importmap"===t.type){t.sp=!0;var r=t.src?(System.fetch||fetch)(t.src,{integrity:t.integrity,priority:t.fetchPriority,passThrough:!0}).then((function(e){if(!e.ok)throw Error("Invalid status code: "+e.status);return e.text()})).catch((function(n){return n.message=e("W4","Error fetching systemjs-import map "+t.src)+"\n"+n.message,console.warn(n),"function"==typeof t.onerror&&t.onerror(),"{}"})):t.innerHTML;W=W.then((function(){return r})).then((function(n){!function(t,n,r){var o={};try{o=JSON.parse(n)}catch(s){console.warn(Error(e("W5","systemjs-importmap contains invalid JSON")+"\n\n"+n+"\n"))}i(o,r,t)}(N,n,t.src||g)}))}}))}var g,y="undefined"!=typeof Symbol,b="undefined"!=typeof self,S="undefined"!=typeof document,w=b?self:global;if(S){var O=document.querySelector("base[href]");O&&(g=O.href)}if(!g&&"undefined"!=typeof location){var E=(g=location.href.split("#")[0].split("?")[0]).lastIndexOf("/");-1!==E&&(g=g.slice(0,E+1))}var x,j=/\\/g,P=y&&Symbol.toStringTag,M=y?Symbol():"@",I=a.prototype;I.import=function(e,t,n){var r=this;return t&&"object"==typeof t&&(n=t,t=void 0),Promise.resolve(r.prepareImport()).then((function(){return r.resolve(e,t,n)})).then((function(e){var t=d(r,e,void 0,n);return t.C||p(r,t)}))},I.createContext=function(e){var t=this;return{url:e,resolve:function(n,r){return Promise.resolve(t.resolve(n,r||e))}}},I.onload=function(){},I.register=function(e,t,n){x=[e,t,n]},I.getRegister=function(){var e=x;return x=void 0,e};var L=Object.freeze(Object.create(null));w.System=new a;var C,R,W=Promise.resolve(),N={imports:{},scopes:{},depcache:{},integrity:{}},T=S;if(I.prepareImport=function(e){return(T||e)&&(m(),T=!1),W},I.getImportMap=function(){return JSON.parse(JSON.stringify(N))},S&&(m(),window.addEventListener("DOMContentLoaded",m)),I.addImportMap=function(e,t){i(e,t||g,N)},S){window.addEventListener("error",(function(e){J=e.filename,_=e.error}));var A=location.origin}I.createScript=function(e){var t=document.createElement("script");t.async=!0,e.indexOf(A+"/")&&(t.crossOrigin="anonymous");var n=N.integrity[e];return n&&(t.integrity=n),t.src=e,t};var J,_,k={},U=I.register;I.register=function(e,t){if(S&&"loading"===document.readyState&&"string"!=typeof e){var n=document.querySelectorAll("script[src]"),r=n[n.length-1];if(r){C=e;var i=this;R=setTimeout((function(){k[r.src]=[e,t],i.import(r.src)}))}}else C=void 0;return U.call(this,e,t)},I.instantiate=function(t,n){var r=k[t];if(r)return delete k[t],r;var i=this;return Promise.resolve(I.createScript(t)).then((function(r){return new Promise((function(o,s){r.addEventListener("error",(function(){s(Error(e(3,"Error loading "+t+(n?" from "+n:""))))})),r.addEventListener("load",(function(){if(document.head.removeChild(r),J===t)s(_);else{var e=i.getRegister(t);e&&e[0]===C&&clearTimeout(R),o(e)}})),document.head.appendChild(r)}))}))},I.shouldFetch=function(){return!1},"undefined"!=typeof fetch&&(I.fetch=fetch);var $=I.instantiate,B=/^(text|application)\/(x-)?javascript(;|$)/;I.instantiate=function(t,n,r){var i=this;return this.shouldFetch(t,n,r)?this.fetch(t,{credentials:"same-origin",integrity:N.integrity[t],meta:r}).then((function(r){if(!r.ok)throw Error(e(7,r.status+" "+r.statusText+", loading "+t+(n?" from "+n:"")));var o=r.headers.get("content-type");if(!o||!B.test(o))throw Error(e(4,'Unknown Content-Type "'+o+'", loading '+t+(n?" from "+n:"")));return r.text().then((function(e){return e.indexOf("//# sourceURL=")<0&&(e+="\n//# sourceURL="+t),(0,eval)(e),i.getRegister(t)}))})):$.apply(this,arguments)},I.resolve=function(n,r){return c(N,t(n,r=r||g)||n,r)||function(t,n){throw Error(e(8,"Unable to resolve bare specifier '"+t+(n?"' from "+n:"'")))}(n,r)};var F=I.instantiate;I.instantiate=function(e,t,n){var r=N.depcache[e];if(r)for(var i=0;i`. */ var RDW_COLLECTION_DETAIL_KIND = "collection"; var RDW_COLLECTION_QUEUE_HASH_PREFIX = "#rdw-c="; /** * Mark on a results URL opened from a dynamic collection's card * (`/index.php?...#rdw-dc=`). Needed only for a collection whose * query narrows nothing: its bar must not show on the plain post list. */ var RDW_DYNAMIC_MARK_HASH_PREFIX = "#rdw-dc="; var RDW_HASH_COLLECTIONS = exports("a1",`${RDW_HASH_PREFIX}${RDW_ROUTE_COLLECTIONS}`); var RDW_HASH_FOLLOWING = exports("a3",`${RDW_HASH_PREFIX}${RDW_ROUTE_FOLLOWING}`); var RDW_HASH_SETTINGS = exports("a7",`${RDW_HASH_PREFIX}${RDW_ROUTE_SETTINGS}`); var RDW_HASH_STATS = exports("a5",`${RDW_HASH_PREFIX}${RDW_ROUTE_STATS}`); /** * Key in `settings.features` for showing Statistics in the site menu. * It is a plain switch, not a page tweak with a module. */ var STATS_MENU_SETTING_ID = exports("ci","stats-menu"); var STATS_MENU_SETTING_LABEL = exports("ba","Statistics in site menu"); var STATS_MENU_SWITCH_ID = exports("bb","rdw-stats-menu"); var RDW_OWN_PAGE_CLASS = exports("N","rdw-own-page"); var RDW_PAGE_ROOT_ID = exports("Z","rdw-page-root"); /** The download manager's panel: stays visible over the script's own pages. */ var RDW_DOWNLOADS_PANEL_ID = "rdw-downloads"; var RDW_OWN_PAGE_STYLE_ID = exports("R","rdw-own-page-style"); var HEADER_SELECTOR$1 = exports("M","div#header"); var NAVBAR_SELECTOR = exports("$","div#header ul#navbar"); var CURRENT_PAGE_CLASS$1 = exports("ah","current-page"); var MENU_ITEM_ID = exports("O",{ collections: "rdw-nav-collections", following: "rdw-nav-following", favorites: "rdw-nav-favorites", stats: "rdw-nav-stats", settings: "rdw-nav-settings" }); var MENU_LABEL = exports("a2",{ collections: "Collections", following: "Following", favorites: "Favorites", stats: "Statistics", settings: "RuleDesk" }); /** Site native favorites entry (submenu); hidden when our Favorites item is shown. */ var MY_FAVORITES_CONTAINER_ID = exports("a6","my-favorites-container"); var FEED_MENU_ITEM_ID = exports("a0","rdw-feed-menu"); /** Shared class names for own-page section layouts (relocated from ui/panel). */ var PANEL_UI_CLASS = exports("ax",{ scrollRegion: "rdw-scroll-region", settingsGroup: "rdw-settings-group", settingsRow: "rdw-settings-row", /** A row that belongs to the setting above it (its list of options). */ settingsRowSub: "rdw-settings-row--sub", settingsCaption: "rdw-settings-caption", pageCard: "rdw-page-card" }); var ARTISTS_EMPTY_TITLE = exports("c$","No followed artists yet"); var ARTISTS_EMPTY_HINT = exports("c_","Follow artists with the Follow button next to their name in the tag list."); var ARTIST_FILTER_LABEL = exports("d2","Filter artists (several: space or comma)"); var FEATURE_CHECKBOX_ID_PREFIX = exports("bu","rdw-feature-"); var FEATURE_CHOICE_ID_PREFIX = exports("bx","rdw-feature-choice-"); var UPDATES_GROUP_SIZE_ID = exports("b7","rdw-updates-group-size"); var PLAYLIST_CHUNK_SIZE_ID = exports("b3","rdw-playlist-chunk-size"); var ARTIST_FILTER_ID = exports("d3","rdw-artist-filter"); var GRID_FAV_CHECKBOX_ID = exports("aX","rdw-grid-fav-buttons"); var TWEAKS_SWITCH_ID = exports("aR","rdw-tweaks-enabled"); var TAG_GROUPS_PANEL_LABEL = "Collapse tags"; var TAG_WIKI_FEATURE_ID = "tag-wiki"; /** Short in the settings; the caption under it says where the "?" is. */ var TAG_WIKI_PANEL_LABEL = "Tag description on “?”"; function featurePanelLabel(featureId, fallback) { if (featureId === "tag-groups") return TAG_GROUPS_PANEL_LABEL; if (featureId === TAG_WIKI_FEATURE_ID) return TAG_WIKI_PANEL_LABEL; return fallback; } var HASH_SUFFIX_SPLIT = /[?#]/; var COLLECTION_DETAIL_SEGMENT_INDEX = 1; function isRdwRoute(value) { return RDW_ROUTES.some((route) => route === value); } function isCollectionDetailPage(page) { return typeof page !== "string"; } /** Navbar item for a script page. Collection detail stays under Collections. */ function menuRouteForPage(page) { if (isCollectionDetailPage(page)) return RDW_ROUTE_COLLECTIONS; return page; } function collectionDetailHash(collectionId) { return `${RDW_HASH_PREFIX}${RDW_ROUTE_COLLECTIONS}/${encodeURIComponent(collectionId)}`; } function collectionQueueHash(collectionId) { return `${RDW_COLLECTION_QUEUE_HASH_PREFIX}${encodeURIComponent(collectionId)}`; } function dynamicCollectionMarkHash(collectionId) { return `${RDW_DYNAMIC_MARK_HASH_PREFIX}${encodeURIComponent(collectionId)}`; } /** Collection id from a `#rdw-dc=` hash, or null for any other hash. */ function readDynamicCollectionMark(hash) { if (!hash.startsWith("#rdw-dc=")) return null; const raw = hash.slice(8); if (raw.length === 0) return null; try { return decodeURIComponent(raw); } catch { return raw; } } function rdwPageHash(page) { if (isCollectionDetailPage(page)) return collectionDetailHash(page.collectionId); return `${RDW_HASH_PREFIX}${page}`; } function hashSegment(raw) { return raw.split(HASH_SUFFIX_SPLIT)[0] ?? ""; } function decodeCollectionId(raw) { try { return decodeURIComponent(raw); } catch { return raw; } } /** * Parse location.hash → script page, or null when the hash is not ours. * `#rdw-c=…` is the post-page queue and is never a script page. * `#rdw/collections/` is that custom collection; a bare * `#rdw/collections` stays the list. */ function parseRdwHash(hash) { const trimmed = hash.trim(); if (trimmed.startsWith("#rdw-c") || !trimmed.startsWith("#rdw/")) return null; const segments = trimmed.slice(5).split("/"); const head = hashSegment(segments[0] ?? ""); if (!isRdwRoute(head)) return null; if (head !== "collections" || segments.length <= COLLECTION_DETAIL_SEGMENT_INDEX) return head; const collectionId = decodeCollectionId(hashSegment(segments[COLLECTION_DETAIL_SEGMENT_INDEX] ?? "")); if (collectionId.length === 0) return RDW_ROUTE_COLLECTIONS; return { kind: RDW_COLLECTION_DETAIL_KIND, collectionId }; } /** CSS: hide site siblings after header while own page is open. */ function buildOwnPageCss() { return ` html.${RDW_OWN_PAGE_CLASS} ${HEADER_SELECTOR$1} ~ *:not(#${RDW_PAGE_ROOT_ID}):not(#${RDW_DOWNLOADS_PANEL_ID}) { display: none !important; } #${RDW_PAGE_ROOT_ID} { display: block; box-sizing: border-box; width: 100%; } /* The space under the header is the page's own (the shell's top padding), so that a toolbar right under the header can have the same space above it as below it. */ html.${RDW_OWN_PAGE_CLASS} ${HEADER_SELECTOR$1} { margin-bottom: 0 !important; } `; } var THUMB_CLASS = "rdw-thumb"; /** * On on the site's Favorites page, set before the first paint. The * skin rules for a favorites cell are held to it: the pool page has thumbs * of a similar shape, and their links carry an onclick too. */ var FAVORITES_PAGE_CLASS = "rdw-page-favorites"; var THUMB_ANCHOR_NAME = "--rdw-img"; /** * Anchor of a favorites picture. Its scope is the whole cell and comes from * the stylesheet, so it is there from the first layout; the buttons of a * favorites thumb are placed by it. */ var FAVORITE_IMAGE_ANCHOR_NAME = "--rdw-fav-img"; var FEATURE_STYLE_ID_PREFIX = "rdw-feature-style-"; var POST_ACTIONS_ID = "rdw-post-actions"; function featureBodyClass(id) { return `rdw-f-${id}`; } function featureChoiceBodyClass(id, value) { return `rdw-f-${id}-${value}`; } /** * On the element around the link of a video thumb (site/video-thumbs.ts puts * it there). Kept here, in a module that imports nothing, because both the * marking and the feature that draws the mark need it. */ var VIDEO_THUMB_CLASS = "rdw-video-thumb"; /** How a label on a thumb looks: "GIF", and the play sign of a video. */ var THUMB_LABEL_RULES = ` position: absolute; left: ${String(6)}px; bottom: ${String(6)}px; z-index: 2; padding: 1px 5px; border: 1px solid var(--rdw-border); border-radius: 4px; background: var(--rdw-surface); color: var(--rdw-text); font: 700 10px/1.4 var(--rdw-font); letter-spacing: 0.04em; pointer-events: none;`; /** * Names the start of the page needs before the features are loaded: whether * the Favorites page opens narrowed (and the site's own grid must not be * shown for the moment it takes to read the local list). Kept here, in a * module that imports nothing, so that the start stays small. */ /** On while the script's own grid of favorites stands in place of the site's. */ var FAVORITES_BROWSING_BODY_CLASS = "rdw-fav-browsing"; /** On the script's own grid of favorites. */ var FAVORITES_RESULTS_CLASS = "rdw-fav-results"; /** Feature state: how Favorites is paged. */ var FAVORITES_VIEW_STATE_ID = "favorites-view"; var FAVORITES_VIEW_SCROLL = "scroll"; /** Feature state: AI posts shown or hidden, by the part of the site. */ var AI_STATE_ID = "ai-posts"; var AI_STATE_HIDE = "hide"; var AI_SCOPE_FAVORITES = "favorites"; function isDebugEnabled() { try { return GM_getValue(DEBUG_KEY, void 0) === true; } catch { return false; } } var log = exports("q",{ debug(message, ...details) { if (!isDebugEnabled()) return; console.debug(`[ruledesk-web] ${message}`, ...details); }, info(message, ...details) { if (!isDebugEnabled()) return; console.info(`[ruledesk-web] ${message}`, ...details); }, warn(message, ...details) { console.warn(`[ruledesk-web] ${message}`, ...details); }, error(message, ...details) { console.error(`[ruledesk-web] ${message}`, ...details); } }); function detectPageKind(search) { const params = new URLSearchParams(search); const page = params.get(SEARCH_PARAM_PAGE); const section = params.get("s"); if (page === "post" && section === "list") return "list"; if (page === "post" && section === "view") return "post"; if (page === "favorites" && section === "view") return "favorites"; return "other"; } function readPostIdFromSearch(search) { const params = new URLSearchParams(search); const page = params.get(SEARCH_PARAM_PAGE); const section = params.get("s"); const id = params.get("id"); if (page !== "post" || section !== "view") return null; if (id === null || id.trim().length === 0) return null; if (!/^\d+$/.test(id)) return null; return id; } function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); return Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v); } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } var Cached = class { constructor(getter) { this._getter = getter; this._value = void 0; } get value() { const getter = this._getter; if (getter !== void 0) { this._value = getter(); this._getter = void 0; } return this._value; } }; function cached(getter) { return new Cached(getter); } function nullish(input) { return input === null || input === void 0; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true }); } var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {}; function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } function isPlainObject(o) { if (isObject(o) === false) return false; const ctor = o.constructor; if (ctor === void 0) return true; if (typeof ctor !== "function") return true; const prot = ctor.prototype; if (isObject(prot) === false) return false; if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) return false; return true; } var propertyKeyTypes = /* @__PURE__*/ new Set([ "string", "number", "symbol" ]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== void 0) { if (params?.error !== void 0) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin !== void 0 && shape[k]._zod.optout === "optional"; }); } var NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 34028234663852886e22], float64: [-Number.MAX_VALUE, Number.MAX_VALUE] }))(); function aborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue !== true) return true; return false; } function explicitlyAborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) if (x.issues[i]?.continue === false) return true; return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a; (_a = iss).path ?? (_a.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } /** The leading size checks of `defChecks` that set an upper bound, each paired with it. */ function sizeCaps(defChecks) { const caps = []; for (const ch of defChecks ?? []) { const d = ch._zod.def; if (!/_(length|size)$|_equals$/.test(d.check)) break; const max = d.maximum ?? d.length ?? d.size; if (max >= 0) caps.push([max, ch]); } return caps; } function attachSchema(issues, start, inst) { var _a; for (let i = start; i < issues.length; i++) (_a = issues[i]).schema ?? (_a.schema = inst); } function finalizeIssue(iss, ctx, config) { var _a; const traits = iss.inst?._zod?.traits; if (traits?.has("$ZodType")) { if (traits.has("$ZodCheck")) (_a = iss).schema ?? (_a.schema = iss.inst); else iss.schema = iss.inst; } const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0; const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(schemaError?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; const full = {}; for (const k of Object.keys(iss)) { if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__") continue; full[k] = iss[k]; } full.path ?? (full.path = []); full.message = message; if (ctx?.reportInput) full.input = iss.input; return full; } var highSurrogate = /[\uD800-\uDBFF]/; function codePointLength(str) { const units = str.length; if (!highSurrogate.test(str)) return units; let count = units; for (let i = 0; i < units - 1; i++) if ((str.charCodeAt(i) & 64512) === 55296 && (str.charCodeAt(i + 1) & 64512) === 56320) { count--; i++; } return count; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } /** * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. * * Call this from a `proto` initializer, which runs once per prototype — never per instance. */ function members(proto, table) { for (const key in table) { const desc = Object.getOwnPropertyDescriptor(table, key); if (desc.get) Object.defineProperty(proto, key, { ...desc, enumerable: false }); else defineBound(proto, key, desc.value); } } /** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ function own(inst, key, value, enumerable = true) { Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); return value; } /** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ function hide(inst, key, value) { return own(inst, key, value, false); } function defineBound(proto, key, fn) { Object.defineProperty(proto, key, { configurable: true, get() { return this == null ? fn : own(this, key, fn.bind(this)); }, set(value) { own(this, key, value); } }); } /** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ function claim(inst, sentinel) { const proto = Object.getPrototypeOf(inst); return sentinel in proto ? void 0 : proto; } var installing; var broke = false; var breaker = { configurable: true, get() { broke = true; } }; /** * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s * constructor, computed from the internals object itself and cached there on * first read. One accessor per constructor rather than one per instance. */ function defineLazyInternal(inst, key, compute) { const proto = Object.getPrototypeOf(inst._zod); if (key in proto && installing !== inst._zod) { installing = void 0; return; } installing = inst._zod; Object.defineProperty(proto, key, { configurable: true, get() { Object.defineProperty(this, key, breaker); const outer = broke; broke = false; try { const value = compute(this); if (broke) delete this[key]; else Object.defineProperty(this, key, { configurable: true, writable: true, value }); broke = broke || outer; return value; } catch (err) { delete this[key]; broke = broke || outer; throw err; } }, set(value) { Object.defineProperty(this, key, { configurable: true, writable: true, value }); } }); } /** * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own * data property. One accessor per constructor rather than one per instance, because an own accessor * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. */ function installLazyProp(inst, key, make, enumerable) { const proto = claim(inst, key); if (!proto) return; Object.defineProperty(proto, key, { configurable: true, get() { const desc = { configurable: true, writable: true, enumerable, value: void 0 }; Object.defineProperty(this, key, desc); desc.value = make(this); Object.defineProperty(this, key, desc); return desc.value; }, set(value) { Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); } }); } var _a; var _zodDesc = { value: void 0, enumerable: false }; var _E = "captureStackTrace" in Error ? Error : null; function newError(Definition) { const E = _E; if (E) { const saved = E.stackTraceLimit; if (typeof saved === "number") { try { E.stackTraceLimit = 0; } catch { _E = null; return new Definition(); } try { return new Definition(); } finally { E.stackTraceLimit = saved; } } } return new Definition(); } /* @__NO_SIDE_EFFECTS__ */ function $constructor(name, initializer, proto, params) { const zodProto = {}; function Internals(def) { this.def = def; this.constr = _; this.traits = /* @__PURE__ */ new Set(); } Internals.prototype = zodProto; const protoMembers = proto; const initialized = protoMembers && /* @__PURE__ */ new WeakSet(); function init(inst, def) { if (!inst._zod) { _zodDesc.value = new Internals(def); try { Object.defineProperty(inst, "_zod", _zodDesc); } finally { _zodDesc.value = void 0; } } else if (inst._zod.traits.has(name)) return; inst._zod.traits.add(name); initializer(inst, def); if (initialized) { const own = Object.getPrototypeOf(inst); const ctorProto = inst._zod.constr.prototype; let up = own; while (up && up !== ctorProto) up = Object.getPrototypeOf(up); const target = up ?? own; if (!initialized.has(target)) { initialized.add(target); members(target, protoMembers); } } const proto = _.prototype; for (const k in proto) { if (!Object.prototype.hasOwnProperty.call(proto, k)) continue; if (!(k in inst)) inst[k] = proto[k].bind(inst); } } const Parent = params?.Parent ?? Object; class Definition extends Parent {} Object.defineProperty(Definition, "name", { value: name }); function _(def) { const inst = params?.Parent ? newError(Definition) : this; init(inst, def); const deferred = inst._zod.deferred; if (deferred) { for (const fn of deferred) fn(); inst._zod.deferred = void 0; } const pp = globalThis.__zod_globalConfig?.postProcessor; if (pp) pp(inst); return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name); } }); Object.defineProperty(_, "name", { value: name }); return _; } var $ZodAsyncError = class extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } }; (_a = globalThis).__zod_globalConfig ?? (_a.__zod_globalConfig = {}); var globalConfig = globalThis.__zod_globalConfig; function config(newConfig) { return globalConfig; } function _getMessage() { const internals = this._zod; internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); return internals.message; } function _setMessage(value) { this._zod.message = value; } var _messageDesc = { get: _getMessage, set: _setMessage, enumerable: true, configurable: true }; var _issuesDesc = { value: void 0, enumerable: false }; var _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); var initializer = (inst, def) => { inst.name = "$ZodError"; _issuesDesc.value = def; Object.defineProperty(inst, "issues", _issuesDesc); _issuesDesc.value = void 0; Object.defineProperty(inst, "message", _messageDesc); const proto = Object.getPrototypeOf(inst); if (!_installedToString.has(proto)) { _installedToString.add(proto); Object.defineProperty(proto, "toString", { configurable: true, enumerable: false, get() { const value = () => this.message; Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); return value; }, set(value) { Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); } }); } }; var $ZodRealError = /* @__PURE__ */ $constructor("$ZodError", initializer, void 0, { Parent: Error }); var _parse = (_Err) => { const fn = (schema, value, _ctx, _params) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) throw new $ZodAsyncError(); if (result.issues.length) { const e = new ((_params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, _params?.callee ?? fn); throw e; } return result.value; }; return fn; }; var parse = /* @__PURE__*/ _parse($ZodRealError); var _parseAsync = (_Err) => { const fn = async (schema, value, _ctx, params) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; if (result.issues.length) { const e = new ((params?.Err) ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); captureStackTrace(e, params?.callee ?? fn); throw e; } return result.value; }; return fn; }; var parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); var _safeParse = (_Err) => (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; const result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) throw new $ZodAsyncError(); return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParse = /* @__PURE__*/ _safeParse($ZodRealError); function failure(Err, issues, ctx) { let error; return { success: false, get error() { if (!error) { error = new Err(issues.map((iss) => finalizeIssue(iss, ctx, config()))); issues = void 0; ctx = void 0; } return error; }, set error(e) { error = e; issues = void 0; ctx = void 0; } }; } var _safeParseAsync = (_Err) => async (schema, value, _ctx) => { const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; let result = schema._zod.run({ value, issues: [] }, ctx); if (result instanceof Promise) result = await result; return result.issues.length ? failure(_Err, result.issues, ctx) : { success: true, data: result.value }; }; var safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); var anyString = /^[\s\S]{0,}$/; var number$1 = /^-?\d+(?:\.\d+)?$/; var boolean$1 = /^(?:true|false)$/i; var $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { var _a; inst._zod ?? (inst._zod = {}); inst._zod.def = def; (_a = inst._zod).onattach ?? (_a.onattach = []); }); /** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ var _whenHasLength = (payload) => { const val = payload.value; return !nullish(val) && val.length !== void 0; }; var numericOriginMap = { number: "number", bigint: "bigint", object: "date" }; var $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { $ZodCheck.init(inst, def); const origin = numericOriginMap[typeof def.value]; inst._zod.check = (payload) => { if (def.inclusive ? payload.value >= def.value : payload.value > def.value) return; payload.issues.push({ origin: numericOriginMap[typeof payload.value] ?? origin, code: "too_small", minimum: typeof def.value === "object" ? def.value.getTime() : def.value, input: payload.value, inclusive: def.inclusive, inst, continue: !def.abort }); }; }); var $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { $ZodCheck.init(inst, def); def.format = def.format || "float64"; const isInt = def.format?.includes("int"); const origin = isInt ? "int" : "number"; const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; inst._zod.check = (payload) => { const input = payload.value; if (isInt) { if (!Number.isInteger(input)) { payload.issues.push({ expected: origin, format: def.format, code: "invalid_type", continue: false, input, inst }); return; } if (!Number.isSafeInteger(input)) { if (input > 0) payload.issues.push({ input, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); else payload.issues.push({ input, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst, origin, inclusive: true, continue: !def.abort }); return; } } if (input < minimum) payload.issues.push({ origin: "number", input, code: "too_small", minimum, inclusive: true, inst, continue: !def.abort }); if (input > maximum) payload.issues.push({ origin: "number", input, code: "too_big", maximum, inclusive: true, inst, continue: !def.abort }); }; }); var $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { var _a; $ZodCheck.init(inst, def); (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); inst._zod.check = (payload) => { const input = payload.value; const units = input.length; if ((typeof input === "string" && units >= def.minimum && units < def.minimum * 2 ? codePointLength(input) : units) >= def.minimum) return; const origin = getLengthableOrigin(input); payload.issues.push({ origin, code: "too_small", minimum: def.minimum, inclusive: true, input, inst, continue: !def.abort }); }; }); var version = { major: 4, minor: 6, patch: 7 }; var $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { var _a; inst ?? (inst = {}); inst._zod.def = def; inst._zod.bag = inst._zod.bag || {}; inst._zod.version = version; const defChecks = inst._zod.def.checks; const checks = inst._zod.traits.has("$ZodCheck") ? [inst, ...defChecks ?? []] : defChecks?.length ? [...defChecks] : []; for (const ch of checks) for (const fn of ch._zod.onattach) fn(inst); if (checks.length === 0) { (_a = inst._zod).deferred ?? (_a.deferred = []); inst._zod.deferred?.push(() => { inst._zod.run = inst._zod.parse; }); } else { const runChecks = (payload, checks, ctx) => { if (payload.memo) return payload; let isAborted = aborted(payload); let asyncResult; for (const ch of checks) { if (ch._zod.def.when) { if (explicitlyAborted(payload)) continue; if (!ch._zod.def.when(payload)) continue; } else if (isAborted) continue; const currLen = payload.issues.length; const _ = ch._zod.check(payload); if (_ instanceof Promise && ctx?.async === false) throw new $ZodAsyncError(); if (asyncResult || _ instanceof Promise) asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { await _; if (payload.issues.length === currLen) return; attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); }); else { if (payload.issues.length === currLen) continue; attachSchema(payload.issues, currLen, inst); if (!isAborted) isAborted = aborted(payload, currLen); } } if (asyncResult) return asyncResult.then(() => { return payload; }); return payload; }; const handleCanaryResult = (canary, payload, ctx) => { if (aborted(canary)) { canary.aborted = true; return canary; } const checkResult = runChecks(payload, checks, ctx); if (checkResult instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); } return inst._zod.parse(checkResult, ctx); }; inst._zod.run = (payload, ctx) => { if (ctx.skipChecks) return inst._zod.parse(payload, ctx); if (ctx.direction === "backward") { const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); if (canary instanceof Promise) return canary.then((canary) => { return handleCanaryResult(canary, payload, ctx); }); return handleCanaryResult(canary, payload, ctx); } const result = inst._zod.parse(payload, ctx); if (result instanceof Promise) { if (ctx.async === false) throw new $ZodAsyncError(); return result.then((result) => runChecks(result, checks, ctx)); } return runChecks(result, checks, ctx); }; } }, { get "~standard"() { return hide(this, "~standard", standardProps(this)); }, set "~standard"(value) { own(this, "~standard", value); } }); /** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ var toStandardResult = (r, ctx) => r.issues.length ? { issues: r.issues.map((iss) => finalizeIssue(iss, ctx, config())) } : { value: r.value }; async function validateAsync(inst, value) { const ctx = { async: true }; return toStandardResult(await inst._zod.run({ value, issues: [] }, ctx), ctx); } function standardProps(inst) { return { validate: (value) => { const ctx = { async: false }; try { const r = inst._zod.run({ value, issues: [] }, ctx); if (!(r instanceof Promise)) return toStandardResult(r, ctx); } catch (_) {} return validateAsync(inst, value); }, vendor: "zod", version: 1 }; } var $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = def.pattern ?? anyString; inst._zod.parse = (payload, _) => { if (def.coerce) try { payload.value = String(payload.value); } catch (_) {} if (typeof payload.value === "string") return payload; payload.issues.push({ expected: "string", code: "invalid_type", input: payload.value, inst }); return payload; }; }); var $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = number$1; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Number(payload.value); } catch (_) {} const input = payload.value; if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) return payload; const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? String(input) : void 0 : void 0; payload.issues.push({ expected: "number", code: "invalid_type", input, inst, ...received ? { received } : {} }); return payload; }; }); var $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { $ZodCheckNumberFormat.init(inst, def); $ZodNumber.init(inst, def); }); var $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { $ZodType.init(inst, def); inst._zod.pattern = boolean$1; inst._zod.parse = (payload, _ctx) => { if (def.coerce) try { payload.value = Boolean(payload.value); } catch (_) {} const input = payload.value; if (typeof input === "boolean") return payload; payload.issues.push({ expected: "boolean", code: "invalid_type", input, inst }); return payload; }; }); var $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { $ZodType.init(inst, def); inst._zod.parse = (payload) => payload; }); function capSize(inst, size) { const caps = sizeCaps(inst._zod.def.checks); if (!caps.length) return; const cap = Math.min(...caps.map((c) => c[0])); const parse = inst._zod.parse; inst._zod.parse = (payload, ctx) => { const n = size(payload.value); if (n > cap && !ctx?.skipChecks && ctx?.direction !== "backward") { for (const [max, ch] of sizeCaps(inst._zod.def.checks)) if (n > max && ch._zod.def.when(payload)) { const start = payload.issues.length; ch._zod.check(payload); payload.issues[start].continue = false; attachSchema(payload.issues, start, inst); return payload; } } return parse(payload, ctx); }; } var arraySize = (input) => Array.isArray(input) ? input.length : -1; function handleArrayResult(result, final, index) { if (result.issues.length) final.issues.push(...prefixIssues(index, result.issues)); final.value[index] = result.value; } var $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { $ZodType.init(inst, def); const memo = globalConfig.memoizer; memo?.attach(inst); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!Array.isArray(input)) { payload.issues.push({ expected: "array", code: "invalid_type", input, inst }); return payload; } payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); const proms = []; const abortEarly = ctx?.abortEarly; for (let i = 0; i < input.length; i++) { const item = input[i]; const result = def.element._zod.run({ value: item, issues: [] }, ctx); if (result instanceof Promise) proms.push(result.then((result) => handleArrayResult(result, payload, i))); else { handleArrayResult(result, payload, i); if (abortEarly && result.issues.length !== 0 && aborted(result)) break; } } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; capSize(inst, arraySize); }); function handlePropertyResult(result, final, key, input, optin, optout) { const isPresent = key in input; const isOptionalOut = optout === "optional"; if (!isPresent && isOptionalOut && optin === "optional") return; if (result.issues.length) { if (optin !== void 0 && isOptionalOut && !isPresent) return; final.issues.push(...prefixIssues(key, result.issues)); } if (!isPresent && optin === void 0) { if (!result.issues.length) final.issues.push({ code: "invalid_type", expected: "nonoptional", input: void 0, path: [key] }); return; } if (result.value === void 0) { if (isPresent || optin === "defaulted" && !isOptionalOut) final.value[key] = void 0; } else final.value[key] = result.value; } var NO_SYMBOL_KEYS = []; function normalizeDef(def) { const keys = Object.keys(def.shape); const ownSymbols = Object.getOwnPropertySymbols(def.shape); const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; for (const k of allKeys) if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); const okeys = optionalKeys(def.shape); return { ...def, allKeys, symbolKeys, keySet: new Set(keys), numKeys: keys.length, optionalKeys: new Set(okeys) }; } function handleCatchall(proms, input, payload, ctx, def, inst, abortEarly) { const unrecognized = []; const keySet = def.keySet; const _catchall = def.catchall._zod; const t = _catchall.def.type; const optin = _catchall.optin; const optout = _catchall.optout; let seen = 0; for (const key in input) { if (abortEarly && payload.issues.length !== seen) { if (aborted(payload, seen)) break; seen = payload.issues.length; } if (keySet.has(key)) continue; if (key === "__proto__") { if (t === "never") unrecognized.push(key); continue; } if (t === "never") { unrecognized.push(key); continue; } const r = _catchall.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); else handlePropertyResult(r, payload, key, input, optin, optout); } if (unrecognized.length) payload.issues.push({ code: "unrecognized_keys", keys: unrecognized, input, inst, continue: true }); if (!proms.length) return payload; return Promise.all(proms).then(() => { return payload; }); } var $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { $ZodType.init(inst, def); const desc = Object.getOwnPropertyDescriptor(def, "shape"); const sh = desc?.get ? desc.get.raw : def.shape ?? {}; if (sh) { const get = () => { const newSh = { ...sh }; Object.defineProperty(def, "shape", { value: newSh }); get.raw = newSh; return newSh; }; get.raw = sh; Object.defineProperty(def, "shape", { get }); } const _normalized = cached(() => normalizeDef(def)); defineLazyInternal(inst, "propValues", (zod) => { const shape = zod.def.shape; const propValues = {}; for (const key in shape) { const field = shape[key]._zod; if (field.values) { if (!Object.prototype.hasOwnProperty.call(propValues, key)) assignProp(propValues, key, /* @__PURE__ */ new Set()); for (const v of field.values) propValues[key].add(v); if (field.optin !== void 0) propValues[key].add(void 0); } } return propValues; }); const isObject$1 = isObject; const catchall = def.catchall; let value; const memo = globalConfig.memoizer; memo?.attach(inst); inst._zod.parse = (payload, ctx) => { value ?? (value = _normalized.value); const input = payload.value; if (!isObject$1(input)) { payload.issues.push({ expected: "object", code: "invalid_type", input, inst }); return payload; } payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; const proms = []; const shape = value.shape; const abortEarly = ctx?.abortEarly; let seen = payload.issues.length; for (const key of value.allKeys) { if (abortEarly && payload.issues.length !== seen) { if (aborted(payload, seen)) break; seen = payload.issues.length; } if (key === "__proto__") continue; const el = shape[key]; const optin = el._zod.optin; const optout = el._zod.optout; const r = el._zod.run({ value: input[key], issues: [] }, ctx); if (r instanceof Promise) proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); else handlePropertyResult(r, payload, key, input, optin, optout); } if (!catchall) return proms.length ? Promise.all(proms).then(() => payload) : payload; return handleCatchall(proms, input, payload, ctx, _normalized.value, inst, abortEarly === true); }; }); var $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { $ZodType.init(inst, def); const memo = globalConfig.memoizer; memo?.attach(inst); inst._zod.parse = (payload, ctx) => { const input = payload.value; if (!isPlainObject(input)) { payload.issues.push({ expected: "record", code: "invalid_type", input, inst }); return payload; } const proms = []; const values = def.keyType._zod.values; if (values && !def.partial) { payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; const recordKeys = /* @__PURE__ */ new Set(); for (const key of values) if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { recordKeys.add(typeof key === "number" ? key.toString() : key); if (key === "__proto__") continue; const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); if (keyResult.issues.length) { payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); continue; } const outKey = keyResult.value; if (outKey === "__proto__") continue; const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) proms.push(result.then((result) => { if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); payload.value[outKey] = result.value; })); else { if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); payload.value[outKey] = result.value; } } let unrecognized; for (const key in input) if (!recordKeys.has(key)) { if (def.mode === "loose") { if (key === "__proto__") continue; payload.value[key] = input[key]; } else { unrecognized = unrecognized ?? []; unrecognized.push(key); } } if (unrecognized && unrecognized.length > 0) payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized, continue: true }); } else { payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; let unrecognized; for (const key of Reflect.ownKeys(input)) { if (key === "__proto__") continue; if (!Object.prototype.propertyIsEnumerable.call(input, key)) continue; let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); if (keyResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); if (typeof key === "string" && number$1.test(key) && keyResult.issues.length) { const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); if (retryResult instanceof Promise) throw new Error("Async schemas not supported in object keys currently"); if (retryResult.issues.length === 0) keyResult = retryResult; } if (keyResult.issues.length) { if (def.mode === "loose") payload.value[key] = input[key]; else if (values) { unrecognized = unrecognized ?? []; unrecognized.push(key); } else payload.issues.push({ code: "invalid_key", origin: "record", issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), input: key, path: [key], inst }); continue; } const outKey = keyResult.value; if (outKey === "__proto__") continue; const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); if (result instanceof Promise) proms.push(result.then((result) => { if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); payload.value[outKey] = result.value; })); else { if (result.issues.length) payload.issues.push(...prefixIssues(key, result.issues)); payload.value[outKey] = result.value; } } if (unrecognized && unrecognized.length > 0) payload.issues.push({ code: "unrecognized_keys", input, inst, keys: unrecognized, continue: true }); } if (proms.length) return Promise.all(proms).then(() => payload); return payload; }; }); var $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { $ZodType.init(inst, def); const values = getEnumValues(def.entries); const valuesSet = new Set(values); inst._zod.values = valuesSet; defineLazyInternal(inst, "pattern", (zod) => { const patternValues = getEnumValues(zod.def.entries).filter((k) => propertyKeyTypes.has(typeof k)); return new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); }); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (valuesSet.has(input)) return payload; payload.issues.push({ code: "invalid_value", values, input, inst }); return payload; }; }); var $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { $ZodType.init(inst, def); const values = new Set(def.values); inst._zod.values = values; defineLazyInternal(inst, "pattern", (zod) => { const vals = zod.def.values; return new RegExp(vals.length ? `^(${vals.map((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).join("|")})$` : "^[^\\s\\S]$"); }); inst._zod.parse = (payload, _ctx) => { const input = payload.value; if (values.has(input)) return payload; payload.issues.push({ code: "invalid_value", values: def.values, input, inst }); return payload; }; }); function handleOptionalResult(payload, result) { payload.value = result.issues.length ? void 0 : result.value; return payload; } var $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { $ZodType.init(inst, def); defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); inst._zod.optout = "optional"; defineLazyInternal(inst, "values", (zod) => { const values = zod.def.innerType._zod.values; return values ? /* @__PURE__ */ new Set([...values, void 0]) : void 0; }); defineLazyInternal(inst, "pattern", (zod) => { const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === void 0) { if (def.innerType._zod.optin !== "defaulted") return payload; const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); if (result instanceof Promise) return result.then((result) => handleOptionalResult(payload, result)); return handleOptionalResult(payload, result); } return def.innerType._zod.run(payload, ctx); }; }); var $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { $ZodType.init(inst, def); defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); defineLazyInternal(inst, "pattern", (zod) => { const pattern = zod.def.innerType._zod.pattern; return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0; }); defineLazyInternal(inst, "values", (zod) => { return zod.def.innerType._zod.values ? /* @__PURE__ */ new Set([...zod.def.innerType._zod.values, null]) : void 0; }); inst._zod.parse = (payload, ctx) => { if (payload.value === null) return payload; return def.innerType._zod.run(payload, ctx); }; }); function snapshotChecks(def) { if (def.checks) def.checks = [...def.checks]; return def; } // @__NO_SIDE_EFFECTS__ function _string(Class, params) { return new Class(snapshotChecks({ type: "string", ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _number(Class, params) { return new Class(snapshotChecks({ type: "number", checks: [], ...normalizeParams(params) })); } // @__NO_SIDE_EFFECTS__ function _int(Class, params) { return new Class({ type: "number", check: "number_format", abort: false, format: "safeint", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _boolean(Class, params) { return new Class({ type: "boolean", ...normalizeParams(params) }); } // @__NO_SIDE_EFFECTS__ function _unknown(Class) { return new Class({ type: "unknown" }); } // @__NO_SIDE_EFFECTS__ function _gt(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: false }); } // @__NO_SIDE_EFFECTS__ function _gte(value, params) { return new $ZodCheckGreaterThan({ check: "greater_than", ...normalizeParams(params), value, inclusive: true }); } // @__NO_SIDE_EFFECTS__ function _positive(params) { return /* @__PURE__ */ _gt(0, params); } // @__NO_SIDE_EFFECTS__ function _nonnegative(params) { return /* @__PURE__ */ _gte(0, params); } // @__NO_SIDE_EFFECTS__ function _minLength(minimum, params) { return new $ZodCheckMinLength({ check: "min_length", ...normalizeParams(params), minimum }); } var ZodMiniType = /*@__PURE__*/ $constructor("ZodMiniType", (inst, def) => { if (!inst._zod) throw new Error("Uninitialized schema in ZodMiniType."); $ZodType.init(inst, def); inst.def = def; inst.type = def.type; }, { get with() { return this.check; }, set with(value) { own(this, "with", value); }, parse(data, params) { return parse(this, data, params, { callee: this.parse }); }, parseAsync(data, params) { return parseAsync(this, data, params, { callee: this.parseAsync }); }, safeParse(data, params) { return safeParse(this, data, params); }, safeParseAsync(data, params) { return safeParseAsync(this, data, params); }, check(...checks) { const def = this.def; return this.clone({ ...def, checks: [...def.checks ?? [], ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)] }, { parent: true }); }, clone(_def, params) { return clone(this, _def, params); }, brand() { return this; }, register(reg, meta) { reg.add(this, meta); return this; }, apply(fn, ...args) { return args.length === 0 ? fn(this) : fn(this, ...args); } }); var ZodMiniString = /*@__PURE__*/ $constructor("ZodMiniString", (inst, def) => { $ZodString.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function string(params) { return /* @__PURE__ */ _string(ZodMiniString, params); } var ZodMiniNumber = /*@__PURE__*/ $constructor("ZodMiniNumber", (inst, def) => { $ZodNumber.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function number(params) { return /* @__PURE__ */ _number(ZodMiniNumber, params); } var ZodMiniNumberFormat = /*@__PURE__*/ $constructor("ZodMiniNumberFormat", (inst, def) => { $ZodNumberFormat.init(inst, def); ZodMiniNumber.init(inst, def); }); function int(params) { return /* @__PURE__ */ _int(ZodMiniNumberFormat, params); } var ZodMiniBoolean = /*@__PURE__*/ $constructor("ZodMiniBoolean", (inst, def) => { $ZodBoolean.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function boolean(params) { return /* @__PURE__ */ _boolean(ZodMiniBoolean, params); } var ZodMiniUnknown = /*@__PURE__*/ $constructor("ZodMiniUnknown", (inst, def) => { $ZodUnknown.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function unknown() { return /* @__PURE__ */ _unknown(ZodMiniUnknown); } var ZodMiniArray = /*@__PURE__*/ $constructor("ZodMiniArray", (inst, def) => { $ZodArray.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function array(element, params) { return new ZodMiniArray({ type: "array", element, ...normalizeParams(params) }); } var ZodMiniObject = /*@__PURE__*/ $constructor("ZodMiniObject", (inst, def) => { $ZodObject.init(inst, def); ZodMiniType.init(inst, def); installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); }); // @__NO_SIDE_EFFECTS__ function object(shape, params) { return new ZodMiniObject({ type: "object", shape: shape ?? {}, ...normalizeParams(params) }); } var ZodMiniRecord = /*@__PURE__*/ $constructor("ZodMiniRecord", (inst, def) => { $ZodRecord.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function record(keyType, valueType, params) { if (!valueType || !valueType._zod) return new ZodMiniRecord({ type: "record", keyType: /* @__PURE__ */ string(), valueType: keyType, ...normalizeParams(valueType) }); return new ZodMiniRecord({ type: "record", keyType, valueType, ...normalizeParams(params) }); } var ZodMiniEnum = /*@__PURE__*/ $constructor("ZodMiniEnum", (inst, def) => { $ZodEnum.init(inst, def); ZodMiniType.init(inst, def); inst.options = [...inst._zod.values]; }); // @__NO_SIDE_EFFECTS__ function _enum(values, params) { return new ZodMiniEnum({ type: "enum", entries: Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values, ...normalizeParams(params) }); } var ZodMiniLiteral = /*@__PURE__*/ $constructor("ZodMiniLiteral", (inst, def) => { $ZodLiteral.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function literal(value, params) { return new ZodMiniLiteral({ type: "literal", values: Array.isArray(value) ? value : [value], ...normalizeParams(params) }); } var ZodMiniOptional = /*@__PURE__*/ $constructor("ZodMiniOptional", (inst, def) => { $ZodOptional.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function optional(innerType) { return new ZodMiniOptional({ type: "optional", innerType }); } var ZodMiniNullable = /*@__PURE__*/ $constructor("ZodMiniNullable", (inst, def) => { $ZodNullable.init(inst, def); ZodMiniType.init(inst, def); }); // @__NO_SIDE_EFFECTS__ function nullable(innerType) { return new ZodMiniNullable({ type: "nullable", innerType }); } var UPDATES_ID_TOKEN_PATTERN = /^id:>(\d+)$/; var PLAYLIST_ID_TOKEN_PATTERN = /^id:(\d+)$/; function normalizeArtistTag(raw) { const trimmed = raw.trim().toLowerCase(); if (trimmed.length === 0) return null; const withUnderscores = trimmed.replaceAll(" ", "_"); if (/\s/.test(withUnderscores)) return null; if (withUnderscores === "(" || withUnderscores === ")" || withUnderscores === "~") return null; if (withUnderscores.startsWith("-")) return null; if (withUnderscores.length === 0) return null; return withUnderscores; } function parseTags(raw) { return raw.trim().split(/\s+/).filter((token) => token.length > 0).map((token) => { if (token.startsWith("-") && token.length > 1) return { tag: token.slice(1), type: TAG_TYPE_EXCLUDE }; return { tag: token, type: TAG_TYPE_INCLUDE }; }); } function serialize(tags) { return tags.map((entry) => entry.type === "exclude" ? `-${entry.tag}` : entry.tag).join(" "); } function encodeSearchToken(raw) { return encodeURIComponent(raw).replaceAll("(", "%28").replaceAll(")", "%29"); } function buildSearchUrl(tags) { const encoded = tags.map((entry) => { return encodeSearchToken(entry.type === "exclude" ? `-${entry.tag}` : entry.tag); }).join("+"); const params = new URLSearchParams(); params.set(SEARCH_PARAM_PAGE, SEARCH_PAGE); params.set("s", SEARCH_SECTION); return `${SITE_ORIGIN}${SEARCH_PATH}?${params.toString()}&${SEARCH_PARAM_TAGS}=${encoded}`; } function formatGroupQuery(tags) { if (tags.length === 1) { const only = tags[0]; return only === void 0 ? "" : only; } return `( ${tags.join(` ~ `)} )`; } function buildUpdatesQueries(artistTags, seenPostId, groupSize) { const normalized = []; for (const raw of artistTags) { const tag = normalizeArtistTag(raw); if (tag !== null) normalized.push(tag); } if (normalized.length === 0) return []; const groups = []; if (groupSize <= 0) groups.push(normalized); else for (let index = 0; index < normalized.length; index += groupSize) groups.push(normalized.slice(index, index + groupSize)); return groups.map((group) => { const base = formatGroupQuery(group); return base; }); } function buildUpdatesSearchUrl(query) { return buildSearchUrl(parseTags(query)); } /** * First artist OR-group without an id:> token (single tag, no parentheses, if one artist). */ function buildFeedQuery(artistTags, groupSize) { const first = buildUpdatesQueries(artistTags, 0, groupSize)[0]; return first === void 0 ? "" : first; } /** Search URL for the first feed group of followed artists. */ function buildFeedUrl(artistTags, groupSize) { const query = buildFeedQuery(artistTags, groupSize); if (query.length === 0) return buildSearchUrl([]); return buildUpdatesSearchUrl(query); } /** One search query per group of followed artists, without an id filter. */ function feedGroupQueries(artistTags, groupSize) { return buildUpdatesQueries(artistTags, 0, groupSize); } /** * Which group's search a results page shows, when the followed artists do not * fit one search. -1 for any other page, for a page with an id filter, and * when all artists fit one group (the feed is then a single ordinary search). */ function findFeedGroupIndex(tagsParam, artistTags, groupSize) { const queries = feedGroupQueries(artistTags, groupSize); if (queries.length < 2) return -1; const page = tagsParam.trim(); if (page.length === 0) return -1; return queries.findIndex((query) => queriesMatchIgnoringSortRandom(page, query)); } function stripUpdatesIdFilter(tagsParam) { const tokens = tagsParam.trim().split(/\s+/).filter((token) => token.length > 0); if (tokens.length === 0) return ""; const last = tokens[tokens.length - 1]; if (last !== void 0 && UPDATES_ID_TOKEN_PATTERN.test(last)) return tokens.slice(0, -1).join(" "); return tokens.join(" "); } function trackedArtistSet(artistTags) { const tracked = /* @__PURE__ */ new Set(); for (const raw of artistTags) { const tag = normalizeArtistTag(raw); if (tag !== null) tracked.add(tag); } return tracked; } function parseUpdatesArtistQuery(tagsParam, tracked) { if (tracked.size === 0) return null; const tokens = tagsParam.trim().split(/\s+/).filter((token) => token.length > 0); if (tokens.length === 0) return null; let body = tokens; let hasIdFilter = false; const last = tokens[tokens.length - 1]; if (last !== void 0 && UPDATES_ID_TOKEN_PATTERN.test(last)) { body = tokens.slice(0, -1); hasIdFilter = true; } if (body.some((token) => UPDATES_ID_TOKEN_PATTERN.test(token))) return null; if (body.length === 0) return null; const tags = []; if (body.length === 1) { const only = body[0]; if (only === void 0) return null; const tag = normalizeArtistTag(only); if (tag === null || !tracked.has(tag)) return null; tags.push(tag); return { tags, hasIdFilter }; } const first = body[0]; const lastBody = body[body.length - 1]; if (first !== "(" || lastBody !== ")") return null; const inner = body.slice(1, -1); if (inner.length === 0 || inner.length % 2 === 0) return null; for (let index = 0; index < inner.length; index += 1) { const token = inner[index]; if (token === void 0) return null; if (index % 2 === 1) { if (token !== "~") return null; continue; } const tag = normalizeArtistTag(token); if (tag === null || !tracked.has(tag)) return null; if (tags.includes(tag)) return null; tags.push(tag); } return { tags, hasIdFilter }; } function isExactTrackedSet(tags, tracked) { if (tags.length !== tracked.size) return false; for (const tag of tags) if (!tracked.has(tag)) return false; return true; } function isFullUpdatesQuery(tagsParam, artistTags) { const tracked = trackedArtistSet(artistTags); const parsed = parseUpdatesArtistQuery(tagsParam, tracked); if (parsed === null) return false; return isExactTrackedSet(parsed.tags, tracked); } function isPartialUpdatesQuery(tagsParam, artistTags) { const tracked = trackedArtistSet(artistTags); const parsed = parseUpdatesArtistQuery(tagsParam, tracked); if (parsed === null) return false; if (!parsed.hasIdFilter) return false; if (isExactTrackedSet(parsed.tags, tracked)) return false; return parsed.tags.length > 0 && parsed.tags.length < tracked.size; } function formatPlaylistIdToken(postId) { return `id:${String(postId)}`; } function formatPlaylistChunkQuery(ids) { if (ids.length === 1) { const only = ids[0]; return only === void 0 ? "" : formatPlaylistIdToken(only); } return `( ${ids.map(formatPlaylistIdToken).join(` ~ `)} )`; } /** * Builds playlist search queries: ids descending, chunked by `chunkSize`. * One id → `id:N`; multiple → `( id:A ~ id:B ~ ... )`. * `chunkSize <= 0` keeps all ids in a single query. */ function buildPlaylistQueries(postIds, chunkSize) { const unique = /* @__PURE__ */ new Set(); for (const raw of postIds) { if (!Number.isFinite(raw)) continue; const id = Math.trunc(raw); if (id >= 0) unique.add(id); } const sorted = Array.from(unique).sort((a, b) => b - a); if (sorted.length === 0) return []; const chunks = []; if (chunkSize <= 0) chunks.push(sorted); else for (let index = 0; index < sorted.length; index += chunkSize) chunks.push(sorted.slice(index, index + chunkSize)); return chunks.map(formatPlaylistChunkQuery); } /** * Parses a playlist id-query produced by `buildPlaylistQueries`. * Returns null when any non-playlist token is present. */ function parsePlaylistQuery(tagsParam) { const tokens = tagsParam.trim().split(/\s+/).filter((token) => token.length > 0); if (tokens.length === 0) return null; if (tokens.length === 1) { const only = tokens[0]; if (only === void 0) return null; const match = PLAYLIST_ID_TOKEN_PATTERN.exec(only); if (match === null) return null; const id = Number(match[1]); if (!Number.isFinite(id)) return null; return [id]; } const first = tokens[0]; const last = tokens[tokens.length - 1]; if (first !== "(" || last !== ")") return null; const inner = tokens.slice(1, -1); if (inner.length === 0 || inner.length % 2 === 0) return null; const ids = []; for (let index = 0; index < inner.length; index += 1) { const token = inner[index]; if (token === void 0) return null; if (index % 2 === 1) { if (token !== "~") return null; continue; } const match = PLAYLIST_ID_TOKEN_PATTERN.exec(token); if (match === null) return null; const id = Number(match[1]); if (!Number.isFinite(id)) return null; if (ids.includes(id)) return null; ids.push(id); } return ids; } /** Site shuffle token. Ignored when matching a saved dynamic search. */ var SORT_RANDOM_TOKEN = "sort:random"; var SEARCH_TOKEN_SPLIT = /\s+/; function searchTokens(raw) { return raw.trim().split(SEARCH_TOKEN_SPLIT).filter((token) => token.length > 0); } function tokenCountsIgnoringSortRandom(raw) { const counts = /* @__PURE__ */ new Map(); for (const token of searchTokens(raw)) { if (token === "sort:random") continue; counts.set(token, (counts.get(token) ?? 0) + 1); } return counts; } /** * True for a search that narrows nothing: empty, the site's `all`, or either * of them with `sort:random`. */ function isUnfilteredQuery(raw) { const query = withoutSortRandom(raw); return query.length === 0 || query === "all"; } /** True when `raw` contains at least one `sort:random` token. */ function queryHasSortRandom(raw) { return searchTokens(raw).includes(SORT_RANDOM_TOKEN); } /** Token string with every `sort:random` removed. Other tokens keep their order. */ function withoutSortRandom(raw) { return searchTokens(raw).filter((token) => token !== SORT_RANDOM_TOKEN).join(" "); } /** * Token string that includes one trailing `sort:random`. * Existing shuffle tokens are left in place. */ function withSortRandom(raw) { const tokens = searchTokens(raw); if (!tokens.includes("sort:random")) tokens.push(SORT_RANDOM_TOKEN); return tokens.join(" "); } /** * True when two search strings are the same multiset of tokens. * Token order does not matter. Every `sort:random` token is ignored. */ function queriesMatchIgnoringSortRandom(left, right) { const leftCounts = tokenCountsIgnoringSortRandom(left); const rightCounts = tokenCountsIgnoringSortRandom(right); if (leftCounts.size !== rightCounts.size) return false; for (const [token, count] of leftCounts) if (rightCounts.get(token) !== count) return false; return true; } /** localStorage key for the followed-artists tag list mirror (not a cookie). */ var ARTISTS_MIRROR_KEY = "ruledesk-web.artists-mirror"; /** * Writes the followed artist tags to localStorage. * Store calls this on every artists-list save (authoritative), and seeds once * on load only when the mirror is missing/unparseable — never replace-from-GM * over an existing fresher mirror (bfcache). * Swallows localStorage errors and logs them. */ function writeArtistsMirror(tags) { try { localStorage.setItem(ARTISTS_MIRROR_KEY, JSON.stringify([...tags])); } catch (error) { log.error("artists-mirror: write failed", error); } } /** * Reads the mirrored artist tags. * @returns tag list, or null if missing / unparseable */ function readArtistsMirror() { try { const raw = localStorage.getItem(ARTISTS_MIRROR_KEY); if (raw === null) return null; const parsed = JSON.parse(raw); if (!Array.isArray(parsed)) return null; for (const item of parsed) if (typeof item !== "string") return null; return parsed; } catch (error) { log.error("artists-mirror: read failed", error); return null; } } /** localStorage key for dynamic-collection covers, keyed by collection id. */ var COVER_MIRROR_KEY = "ruledesk-web.covers-mirror"; var CoverMirrorSchema = /* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ array(/* @__PURE__ */ string())); /** * Covers are written on a results page and read on the Collections page. * Coming back with the browser Back button restores that page from bfcache, * where the userscript storage can still hold the old value; localStorage is * shared and current, so the card reads the cover from here first. */ function readAll() { try { const raw = localStorage.getItem(COVER_MIRROR_KEY); if (raw === null) return {}; const parsed = CoverMirrorSchema.safeParse(JSON.parse(raw)); return parsed.success ? parsed.data : {}; } catch (error) { log.error("cover-mirror: read failed", error); return {}; } } function writeAll(mirror) { try { localStorage.setItem(COVER_MIRROR_KEY, JSON.stringify(mirror)); } catch (error) { log.error("cover-mirror: write failed", error); } } /** Mirrored cover of one collection, or null when none is stored. */ function readCoverMirror(collectionId) { const cover = readAll()[collectionId]; return cover === void 0 ? null : cover; } /** Stores one cover and drops entries of collections that no longer exist. */ function writeCoverMirror(collectionId, cover, knownIds) { const current = readAll(); const next = {}; for (const id of knownIds) { const kept = current[id]; if (kept !== void 0) next[id] = kept; } next[collectionId] = [...cover]; writeAll(next); } /** Forgets the cover of one collection (query changed, collection deleted). */ function removeCoverMirror(collectionId) { const current = readAll(); if (current[collectionId] === void 0) return; const next = {}; for (const [id, cover] of Object.entries(current)) if (id !== collectionId) next[id] = cover; writeAll(next); } /** localStorage key for dynamic-collection post counts, keyed by collection id. */ var COUNT_MIRROR_KEY = "ruledesk-web.counts-mirror"; var CountSchema = /* @__PURE__ */ object({ value: int(), exact: /* @__PURE__ */ boolean() }); var CountMirrorSchema = /* @__PURE__ */ record(/* @__PURE__ */ string(), CountSchema); function readAllCounts() { try { const raw = localStorage.getItem(COUNT_MIRROR_KEY); if (raw === null) return {}; const parsed = CountMirrorSchema.safeParse(JSON.parse(raw)); return parsed.success ? parsed.data : {}; } catch (error) { log.error("count-mirror: read failed", error); return {}; } } function writeAllCounts(mirror) { try { localStorage.setItem(COUNT_MIRROR_KEY, JSON.stringify(mirror)); } catch (error) { log.error("count-mirror: write failed", error); } } /** Mirrored post count of one collection, or null when none is stored. */ function readCountMirror(collectionId) { const count = readAllCounts()[collectionId]; return count === void 0 ? null : count; } /** Stores one count and drops entries of collections that no longer exist. */ function writeCountMirror(collectionId, count, knownIds) { const current = readAllCounts(); const next = {}; for (const id of knownIds) { const kept = current[id]; if (kept !== void 0) next[id] = kept; } next[collectionId] = { value: count.value, exact: count.exact }; writeAllCounts(next); } /** Forgets the count of one collection (query changed, collection deleted). */ function removeCountMirror(collectionId) { const current = readAllCounts(); if (current[collectionId] === void 0) return; const next = {}; for (const [id, count] of Object.entries(current)) if (id !== collectionId) next[id] = count; writeAllCounts(next); } /** Keep at most this many mark entries (highest post ids). */ var MARKS_KEEP_LIMIT = 2e4; /** Prune only after size exceeds keep limit by this fraction (hysteresis). */ var MARKS_PRUNE_OVERFLOW_RATIO = .1; function marksPruneThreshold(keepLimit = MARKS_KEEP_LIMIT) { return keepLimit + Math.floor(keepLimit * MARKS_PRUNE_OVERFLOW_RATIO); } function postIdSortKey(postId) { const parsed = Number(postId); if (!Number.isFinite(parsed)) return Number.NEGATIVE_INFINITY; return Math.trunc(parsed); } /** * When marks size exceeds keepLimit by 10%, keep only the highest * `keepLimit` post ids. Below/at the threshold, returns the same object. */ function pruneMarksIfNeeded(marks, keepLimit = MARKS_KEEP_LIMIT) { const entries = Object.entries(marks); const threshold = marksPruneThreshold(keepLimit); if (entries.length <= threshold) return { marks, pruned: false }; const sorted = [...entries].sort((left, right) => postIdSortKey(right[0]) - postIdSortKey(left[0])); const next = {}; for (const [postId, flags] of sorted.slice(0, keepLimit)) next[postId] = flags; return { marks: next, pruned: true }; } /** * Design tokens for RuleDesk Web UI and site skin. * Light values match docs/design/mock-components.html. */ var TOKEN_VAR = exports("ay",{ bg: "--rdw-bg", surface: "--rdw-surface", surface2: "--rdw-surface-2", border: "--rdw-border", text: "--rdw-text", muted: "--rdw-muted", accent: "--rdw-accent", accentSoft: "--rdw-accent-soft", danger: "--rdw-danger", dangerSoft: "--rdw-danger-soft", warn: "--rdw-warn", warnSoft: "--rdw-warn-soft", tagArtist: "--rdw-tag-artist", tagCharacter: "--rdw-tag-character", tagCopyright: "--rdw-tag-copyright", tagMetadata: "--rdw-tag-metadata", radiusS: "--rdw-radius-s", radiusM: "--rdw-radius-m", radiusL: "--rdw-radius-l", shadow1: "--rdw-shadow-1", shadow2: "--rdw-shadow-2", font: "--rdw-font", segTrack: "--rdw-seg-track", segText: "--rdw-seg-text", segOn: "--rdw-seg-on", segOnText: "--rdw-seg-on-text", backgroundImage: "--rdw-background-image", backgroundDim: "--rdw-background-dim" }); /** Light palette — page bg from mock-site-skin.html (.new); surfaces from mock-components. */ var LIGHT_PALETTE = { bg: "#f3f5f7", surface: "#ffffff", surface2: "#f4f6f8", border: "#cfd6dd", text: "#1c2228", muted: "#5a6672", accent: "#2f6fed", accentSoft: "#e8f0fe", danger: "#c0392b", dangerSoft: "#fdecea", warn: "#6b4e00", warnSoft: "#fff4d6", tagArtist: "#b00020", tagCharacter: "#0a7a2f", tagCopyright: "#8e24aa", tagMetadata: "#ff8800", radiusS: "6px", radiusM: "8px", radiusL: "10px", shadow1: "0 1px 2px rgba(0, 0, 0, 0.06)", shadow2: "0 8px 24px rgba(0, 0, 0, 0.25)", font: "system-ui, \"Segoe UI\", sans-serif", segTrack: "#c9d1d9", segText: "#4a5560", segOn: "#ffffff", segOnText: "#1c2228" }; /** Dark palette for theme=dark / site-dark / custom base. */ var DARK_PALETTE = { bg: "#16181c", surface: "#1e2228", surface2: "#262b33", border: "#3a424c", text: "#e8edf2", muted: "#8a96a3", accent: "#4c8bf5", accentSoft: "#1a2f5a", danger: "#e57373", dangerSoft: "#3d1f1f", warn: "#f0d68a", warnSoft: "#3a3016", tagArtist: "#ff6b81", tagCharacter: "#5dcea0", tagCopyright: "#ce93d8", tagMetadata: "#ffb74d", radiusS: "6px", radiusM: "8px", radiusL: "10px", shadow1: "0 1px 2px rgba(0, 0, 0, 0.35)", shadow2: "0 8px 24px rgba(0, 0, 0, 0.55)", font: "system-ui, \"Segoe UI\", sans-serif", segTrack: "transparent", segText: "#8a96a3", segOn: "#3a424c", segOnText: "#e8edf2" }; var HEX_SHORT_PATTERN = /^#([0-9a-fA-F]{3})$/; var HEX_LONG_PATTERN = /^#([0-9a-fA-F]{6})$/; var SRGB_LINEAR_THRESHOLD = .03928; var SRGB_LINEAR_DIVISOR = 12.92; var SRGB_GAMMA = 2.4; var SRGB_A = .055; var SRGB_B = 1.055; var LUMA_R = .2126; var LUMA_G = .7152; var LUMA_B = .0722; function channelToLinear(channel) { const c = channel / 255; if (c <= SRGB_LINEAR_THRESHOLD) return c / SRGB_LINEAR_DIVISOR; return ((c + SRGB_A) / SRGB_B) ** SRGB_GAMMA; } /** Parse #rgb / #rrggbb into 0–255 channels; null if unsupported. */ function parseHexColor(value) { const short = HEX_SHORT_PATTERN.exec(value.trim()); if (short !== null) { const hex = short[1]; if (hex === void 0) return null; return { r: Number.parseInt(hex[0] + hex[0], 16), g: Number.parseInt(hex[1] + hex[1], 16), b: Number.parseInt(hex[2] + hex[2], 16) }; } const long = HEX_LONG_PATTERN.exec(value.trim()); if (long !== null) { const hex = long[1]; if (hex === void 0) return null; return { r: Number.parseInt(hex.slice(0, 2), 16), g: Number.parseInt(hex.slice(2, 4), 16), b: Number.parseInt(hex.slice(4, 6), 16) }; } return null; } function relativeLuminance(hex) { const rgb = parseHexColor(hex); if (rgb === null) return null; const r = channelToLinear(rgb.r); const g = channelToLinear(rgb.g); const b = channelToLinear(rgb.b); return LUMA_R * r + LUMA_G * g + LUMA_B * b; } var CONTRAST_OFFSET$1 = .05; /** * Hex equivalents of `docs/design/site-desktop.css` light `* { --c-* }`. * Script-page Site default chrome; keep in sync with skin/theme site palette. */ var SITE_LIGHT_C_BG = exports("aC","#aae5a4"); var SITE_LIGHT_C_BG_ALT = exports("aD","#89cf81"); var SITE_LIGHT_C_BG_OVERLAY = "#98d491"; var SITE_LIGHT_C_TEXT = "#000000"; var SITE_LIGHT_C_LINK = "#000099"; /** * The script's own secondary text on the site's light background. The site's * own soft text (#666666) is 3.95:1 there; this is 5.82:1. */ var SITE_LIGHT_TEXT_SOFT_AA = "#4d4d4d"; /** Site dark script-page chrome (theme=site-dark). */ var SITE_DARK_C_BG = exports("aE","#303a30"); var SITE_DARK_C_SURFACE2 = "#303030"; var SITE_DARK_C_BORDER = exports("aF","#505a50"); var SITE_DARK_C_TEXT = "#c0c0c0"; var SITE_DARK_C_ACCENT = "#b0e0b0"; /** * The script's own secondary text on the site's dark background. The site's * own muted text (#878787) is 3.30:1 there; this is 4.98:1. */ var SITE_DARK_TEXT_SOFT_AA = "#a8a8a8"; /** * Site default switch ON track: green-family control color (not link blue). * Must keep ≥ {@link CONTRAST_RATIO_UI_MIN} vs card bg ({@link SITE_LIGHT_C_BG}). */ var SITE_DEFAULT_SWITCH_ON = "#1a4d1a"; /** Preferred thumb fill on Site default switch ON (page/card green). */ var SITE_DEFAULT_SWITCH_THUMB_ON = SITE_LIGHT_C_BG; /** WCAG contrast ratio of two hex colors; null if either is unparseable. */ function contrastRatio$1(foreground, background) { const l1 = relativeLuminance(foreground); const l2 = relativeLuminance(background); if (l1 === null || l2 === null) return null; const lighter = Math.max(l1, l2); const darker = Math.min(l1, l2); return (lighter + CONTRAST_OFFSET$1) / (darker + CONTRAST_OFFSET$1); } /** * Prefer `preferred` when it meets `minRatio` vs `background`; else first * candidate that does. Falls back to `preferred` if none pass. */ function pickContrastingHex(background, preferred, candidates, minRatio) { const preferredRatio = contrastRatio$1(preferred, background); if (preferredRatio !== null && preferredRatio >= minRatio) return preferred; for (const candidate of candidates) { const ratio = contrastRatio$1(candidate, background); if (ratio !== null && ratio >= minRatio) return candidate; } return preferred; } /** Thumb fill for a switch ON track that meets UI contrast, if possible. */ function resolveSwitchThumbOn(trackOn, preferredThumb, fallbacks = ["#ffffff"]) { return pickContrastingHex(trackOn, preferredThumb, fallbacks, 3); } /** Pick light/dark custom base from a legacy background hex. */ function customBaseFromLegacyBg(bg) { if (bg === void 0) return "light"; const luma = relativeLuminance(bg); if (luma !== null && luma < .5) return "dark"; return "light"; } function escapeCssValue(value) { return value.replace(/ 0) target.style.setProperty(TOKEN_VAR.backgroundImage, `url("${custom.backgroundImage.replace(/"/g, "\\\"")}")`); if (custom.backgroundDim !== void 0) target.style.setProperty(TOKEN_VAR.backgroundDim, String(custom.backgroundDim)); } function clearCustomThemeProperties(target) { target.style.removeProperty(TOKEN_VAR.accent); target.style.removeProperty(TOKEN_VAR.bg); target.style.removeProperty(TOKEN_VAR.surface); target.style.removeProperty(TOKEN_VAR.text); target.style.removeProperty(TOKEN_VAR.backgroundImage); target.style.removeProperty(TOKEN_VAR.backgroundDim); } var TagTypeSchema = /* @__PURE__ */ _enum([TAG_TYPE_INCLUDE, TAG_TYPE_EXCLUDE]); var CollectionKindSchema = /* @__PURE__ */ _enum([COLLECTION_KIND_SEARCH, COLLECTION_KIND_POSTS]); var TagEntrySchema = /* @__PURE__ */ object({ tag: (/* @__PURE__ */ string()).check(/* @__PURE__ */ _minLength(1)), type: TagTypeSchema }); /** * Optional `kind` / `postIds`: missing `kind` means a saved search. * Custom (`posts`) rows may also carry `thumbs` and `shuffledOrder`. * Dynamic searches may carry `query` (raw tag string). All three are optional * so 0.15 blobs still parse; {@link migrateCollectionMediaFields} fills the * custom-collection defaults without dropping `postIds` or search tags. * `shuffledOrder: null` means insertion order (`postIds`). * Dynamic searches may also carry `cover`: thumb URLs seen on the first * page of their results, newest visit wins. `postCount` comes from the same page. */ /** * Size of a saved search as read from its results page. * `exact: false` means "at least `value`" (taken from the last-page link). */ var PostCountSchema = /* @__PURE__ */ object({ value: int(), exact: /* @__PURE__ */ boolean() }); var CollectionSchema = /* @__PURE__ */ object({ id: (/* @__PURE__ */ string()).check(/* @__PURE__ */ _minLength(1)), name: (/* @__PURE__ */ string()).check(/* @__PURE__ */ _minLength(1)), tags: /* @__PURE__ */ array(TagEntrySchema), kind: /* @__PURE__ */ optional(CollectionKindSchema), postIds: /* @__PURE__ */ optional(/* @__PURE__ */ array(int())), thumbs: /* @__PURE__ */ optional(/* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ string())), shuffledOrder: /* @__PURE__ */ optional(/* @__PURE__ */ nullable(/* @__PURE__ */ array(int()))), query: /* @__PURE__ */ optional(/* @__PURE__ */ string()), cover: /* @__PURE__ */ optional(/* @__PURE__ */ array(/* @__PURE__ */ string())), postCount: /* @__PURE__ */ optional(PostCountSchema), /** A saved search: the newest post id on its first page when you last opened it. */ openedPostId: /* @__PURE__ */ optional(int()), /** A saved search: the newest post id found by the last "Check for new". */ newestPostId: /* @__PURE__ */ optional(int()), /** The group the user put the collection into on the Collections page. */ group: /* @__PURE__ */ optional(/* @__PURE__ */ string()) }); /** * A followed artist. Everything except `tag` is what the Following page shows * and is filled in as it becomes known. */ /** * What a followed tag is. The list began as artists only, so an entry without * a kind is an artist. */ var FOLLOW_KIND_ARTIST = exports("F","artist"); var FOLLOW_KIND_CHARACTER = exports("n","character"); var FOLLOW_KIND_COPYRIGHT = exports("o","copyright"); var FollowKindSchema = /* @__PURE__ */ _enum([ FOLLOW_KIND_ARTIST, FOLLOW_KIND_CHARACTER, FOLLOW_KIND_COPYRIGHT ]); var ArtistEntrySchema = /* @__PURE__ */ object({ tag: (/* @__PURE__ */ string()).check(/* @__PURE__ */ _minLength(1)), /** Absent for an artist. */ kind: /* @__PURE__ */ optional(FollowKindSchema), /** The group the user put the entry into on the Following page. */ group: /* @__PURE__ */ optional(/* @__PURE__ */ string()), /** When the artist was followed, ms since epoch. Absent for older entries. */ addedAt: /* @__PURE__ */ optional(/* @__PURE__ */ number()), /** First thumbs of the artist's results page, for the card cover. */ cover: /* @__PURE__ */ optional(/* @__PURE__ */ array(/* @__PURE__ */ string())), postCount: /* @__PURE__ */ optional(PostCountSchema), /** Newest post id of the artist seen so far. */ lastPostId: /* @__PURE__ */ optional(int()), /** When `lastPostId` took its current value, ms since epoch. */ lastPostSince: /* @__PURE__ */ optional(/* @__PURE__ */ number()) }); /** Legacy `fav` remains optional so old storage/export blobs still parse. */ var MarkFlagsSchema = /* @__PURE__ */ object({ fav: /* @__PURE__ */ optional(/* @__PURE__ */ boolean()), seen: /* @__PURE__ */ optional(/* @__PURE__ */ boolean()) }); var AppearanceThemeSchema = exports("bM",/* @__PURE__ */ _enum([ APPEARANCE_THEME_SITE, APPEARANCE_THEME_SITE_DARK, APPEARANCE_THEME_LIGHT, APPEARANCE_THEME_DARK, APPEARANCE_THEME_CUSTOM ])); var APPEARANCE_CUSTOM_BASE_LIGHT = exports("bo","light"); var APPEARANCE_CUSTOM_BASE_DARK = exports("bp","dark"); var AppearanceCustomBaseSchema = /* @__PURE__ */ _enum([APPEARANCE_CUSTOM_BASE_LIGHT, APPEARANCE_CUSTOM_BASE_DARK]); /** Canonical custom theme: Light/Dark base + optional background image/dim. */ var AppearanceCustomSchema = /* @__PURE__ */ object({ base: AppearanceCustomBaseSchema, backgroundImage: /* @__PURE__ */ optional(/* @__PURE__ */ string()), backgroundDim: /* @__PURE__ */ optional(/* @__PURE__ */ number()) }); /** * Storage/export parse shape: accepts legacy accent/bg/surface/text so 0.10 * blobs still load; normalize via {@link normalizeAppearanceCustom}. */ var AppearanceCustomStoredSchema = /* @__PURE__ */ object({ base: /* @__PURE__ */ optional(AppearanceCustomBaseSchema), accent: /* @__PURE__ */ optional(/* @__PURE__ */ string()), bg: /* @__PURE__ */ optional(/* @__PURE__ */ string()), surface: /* @__PURE__ */ optional(/* @__PURE__ */ string()), text: /* @__PURE__ */ optional(/* @__PURE__ */ string()), backgroundImage: /* @__PURE__ */ optional(/* @__PURE__ */ string()), backgroundDim: /* @__PURE__ */ optional(/* @__PURE__ */ number()) }); var AppearanceSchema = /* @__PURE__ */ object({ theme: AppearanceThemeSchema, custom: /* @__PURE__ */ optional(AppearanceCustomSchema) }); var AppearanceStoredSchema = /* @__PURE__ */ object({ theme: AppearanceThemeSchema, custom: /* @__PURE__ */ optional(AppearanceCustomStoredSchema) }); /** * Package B: module toggle id for «Video player tweaks» * (`settings.features[VIDEO_PLAYER_FEATURE_ID]`). */ var VIDEO_PLAYER_FEATURE_ID = "video-player"; /** Package B: `settings.featureChoice[VIDEO_PLAYER_FEATURE_ID]` values. */ var VIDEO_SIZE_FIT_HEIGHT = "fit-height"; var VIDEO_SIZE_FIT_WIDTH = "fit-width"; var VIDEO_SIZE_ORIGINAL = "original"; var DEFAULT_VIDEO_SIZE = VIDEO_SIZE_FIT_HEIGHT; var VideoSizeSchema = /* @__PURE__ */ _enum([ VIDEO_SIZE_FIT_HEIGHT, VIDEO_SIZE_FIT_WIDTH, VIDEO_SIZE_ORIGINAL ]); /** * Package B: persisted player prefs under * `settings.featureState[VIDEO_PLAYER_FEATURE_ID]`. */ var VideoPlayerStateSchema = /* @__PURE__ */ object({ volume: /* @__PURE__ */ optional(/* @__PURE__ */ number()), muted: /* @__PURE__ */ optional(/* @__PURE__ */ boolean()), playbackRate: /* @__PURE__ */ optional(/* @__PURE__ */ number()) }); var SettingsSchema = /* @__PURE__ */ object({ gridFavButtons: /* @__PURE__ */ boolean(), updatesGroupSize: /* @__PURE__ */ optional(int().check(/* @__PURE__ */ _nonnegative())), playlistChunkSize: /* @__PURE__ */ optional(int().check(/* @__PURE__ */ _positive())), tweaksEnabled: /* @__PURE__ */ optional(/* @__PURE__ */ boolean()), features: /* @__PURE__ */ optional(/* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ boolean())), featureChoice: /* @__PURE__ */ optional(/* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ string())), featureState: /* @__PURE__ */ optional(/* @__PURE__ */ record(/* @__PURE__ */ string(), /* @__PURE__ */ unknown())), appearance: /* @__PURE__ */ optional(AppearanceStoredSchema) }); var UpdatesSchema = /* @__PURE__ */ object({ seenPostId: int().check(/* @__PURE__ */ _nonnegative()) }); var StorageSchema = exports("c2",/* @__PURE__ */ object({ version: /* @__PURE__ */ literal(1), collections: /* @__PURE__ */ array(CollectionSchema), artists: /* @__PURE__ */ array(ArtistEntrySchema), marks: /* @__PURE__ */ record(/* @__PURE__ */ string(), MarkFlagsSchema), settings: /* @__PURE__ */ optional(SettingsSchema), updates: /* @__PURE__ */ optional(UpdatesSchema) })); /** Legacy floating-panel size keys under settings.featureState.panel. */ var LEGACY_PANEL_FEATURE_STATE_ID = "panel"; var LEGACY_PANEL_WIDTH_KEY = "width"; var LEGACY_PANEL_HEIGHT_KEY = "height"; var GRID_DENSITY_CHOICE_ID = "grid-density"; var GRID_DENSITY_DEFAULT_VALUE = "default"; var LEGACY_MASONRY_CHOICE_VALUE = "masonry"; /** Post panel Info/Comments tab used to live here. Always Info as of 0.15.1. */ var POST_PANEL_TAB_CHOICE_ID = "post-actions"; var FavsSyncLockSchema = /* @__PURE__ */ object({ tabId: (/* @__PURE__ */ string()).check(/* @__PURE__ */ _minLength(1)), beatAt: /* @__PURE__ */ number() }); /** Package F HANDOFF: incremental stops early; full walks every page. */ var FAVS_SYNC_MODE_INCREMENTAL = "incremental"; var FAVS_SYNC_MODE_FULL = "full"; var FavsSyncModeSchema = /* @__PURE__ */ _enum([FAVS_SYNC_MODE_INCREMENTAL, FAVS_SYNC_MODE_FULL]); var FavsSyncSchema = /* @__PURE__ */ object({ nextPid: int(), lastPid: int(), startedAt: /* @__PURE__ */ string(), finishedAt: /* @__PURE__ */ optional(/* @__PURE__ */ string()), running: /* @__PURE__ */ optional(/* @__PURE__ */ boolean()), userId: /* @__PURE__ */ optional(int()), lock: /* @__PURE__ */ optional(FavsSyncLockSchema), mode: /* @__PURE__ */ optional(FavsSyncModeSchema) }); var FavsSchema = exports("c5",/* @__PURE__ */ object({ version: /* @__PURE__ */ literal(1), ids: /* @__PURE__ */ array(int()), sync: /* @__PURE__ */ optional(FavsSyncSchema) })); function createDefaultVideoPlayerState() { return { volume: 1, muted: false, playbackRate: 1 }; } function parseVideoPlayerState(raw) { const parsed = VideoPlayerStateSchema.safeParse(raw); if (!parsed.success) return createDefaultVideoPlayerState(); const defaults = createDefaultVideoPlayerState(); const volume = parsed.data.volume; const muted = parsed.data.muted; const playbackRate = parsed.data.playbackRate; return { volume: volume !== void 0 && Number.isFinite(volume) ? Math.min(1, Math.max(0, volume)) : defaults.volume, muted: muted ?? defaults.muted, playbackRate: playbackRate !== void 0 && Number.isFinite(playbackRate) && playbackRate > 0 ? playbackRate : defaults.playbackRate }; } function resolveVideoSize(raw) { const parsed = VideoSizeSchema.safeParse(raw); if (!parsed.success) return DEFAULT_VIDEO_SIZE; return parsed.data; } function isUnknownRecord$1(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } /** * Drop legacy floating-panel width/height from featureState.panel. * Keeps tab and any other keys. No SCHEMA_VERSION bump. */ function stripLegacyPanelWindowSize(data) { const featureState = data.settings?.featureState; if (featureState === void 0) return { data, changed: false }; const panelRaw = featureState[LEGACY_PANEL_FEATURE_STATE_ID]; if (!isUnknownRecord$1(panelRaw)) return { data, changed: false }; const hasWidth = Object.prototype.hasOwnProperty.call(panelRaw, LEGACY_PANEL_WIDTH_KEY); const hasHeight = Object.prototype.hasOwnProperty.call(panelRaw, LEGACY_PANEL_HEIGHT_KEY); if (!hasWidth && !hasHeight) return { data, changed: false }; const nextPanel = {}; for (const [key, value] of Object.entries(panelRaw)) { if (key === "width" || key === "height") continue; nextPanel[key] = value; } const nextFeatureState = { ...featureState }; if (Object.keys(nextPanel).length === 0) delete nextFeatureState[LEGACY_PANEL_FEATURE_STATE_ID]; else nextFeatureState[LEGACY_PANEL_FEATURE_STATE_ID] = nextPanel; const nextSettings = data.settings === void 0 ? { gridFavButtons: true } : { ...data.settings }; if (Object.keys(nextFeatureState).length === 0) delete nextSettings.featureState; else nextSettings.featureState = nextFeatureState; return { data: { ...data, settings: nextSettings }, changed: true }; } /** * Saved masonry grid becomes default. Post-panel tab choice is removed. * No SCHEMA_VERSION bump. */ function migrateRetiredFeatureChoices(data) { const featureChoice = data.settings?.featureChoice; if (featureChoice === void 0) return { data, changed: false }; const nextChoice = { ...featureChoice }; let changed = false; if (nextChoice[GRID_DENSITY_CHOICE_ID] === LEGACY_MASONRY_CHOICE_VALUE) { nextChoice[GRID_DENSITY_CHOICE_ID] = GRID_DENSITY_DEFAULT_VALUE; changed = true; } if (Object.prototype.hasOwnProperty.call(nextChoice, POST_PANEL_TAB_CHOICE_ID)) { delete nextChoice[POST_PANEL_TAB_CHOICE_ID]; changed = true; } if (!changed) return { data, changed: false }; const nextSettings = data.settings === void 0 ? { gridFavButtons: true } : { ...data.settings }; if (Object.keys(nextChoice).length === 0) delete nextSettings.featureChoice; else nextSettings.featureChoice = nextChoice; return { data: { ...data, settings: nextSettings }, changed: true }; } function isPlaylist(collection) { return collection.kind === COLLECTION_KIND_POSTS; } /** * Posts collections gain `thumbs: {}` and `shuffledOrder: null` when those * keys are absent. Saved searches (including explicit `kind: "search"`) are * copied through unchanged. No SCHEMA_VERSION bump. */ function migrateCollectionMediaFields(data) { let changed = false; const collections = []; for (const collection of data.collections) { if (!isPlaylist(collection)) { collections.push(collection); continue; } const needsThumbs = collection.thumbs === void 0; const needsOrder = collection.shuffledOrder === void 0; if (!needsThumbs && !needsOrder) { collections.push(collection); continue; } changed = true; const next = { ...collection }; if (needsThumbs) next.thumbs = {}; if (needsOrder) next.shuffledOrder = null; collections.push(next); } if (!changed) return { data, changed: false }; return { data: { ...data, collections }, changed: true }; } function resolveCollectionKind(collection) { return collection.kind ?? "search"; } function createDefaultFavs() { return { version: 1, ids: [] }; } function createDefaultAppearance() { return { theme: DEFAULT_APPEARANCE_THEME }; } /** * Drop legacy custom color fields; pick Light/Dark base from stored base or * luminance of legacy `bg`. */ function normalizeAppearanceCustom(raw) { const next = { base: raw.base === "light" || raw.base === "dark" ? raw.base : customBaseFromLegacyBg(raw.bg) }; if (raw.backgroundImage !== void 0) next.backgroundImage = raw.backgroundImage; if (raw.backgroundDim !== void 0) next.backgroundDim = raw.backgroundDim; return next; } function normalizeAppearance(stored) { if (stored.custom === void 0) return { theme: stored.theme }; return { theme: stored.theme, custom: normalizeAppearanceCustom(stored.custom) }; } function createDefaultStorage() { return { version: 1, collections: [], artists: [], marks: {}, settings: { gridFavButtons: true, updatesGroupSize: 0, tweaksEnabled: true, appearance: createDefaultAppearance() }, updates: { seenPostId: 0 } }; } function resolveAppearance(data) { const stored = data.settings?.appearance; if (stored === void 0) return createDefaultAppearance(); return normalizeAppearance(stored); } function resolveGridFavButtons(data) { return data.settings?.gridFavButtons ?? true; } function resolveTweaksEnabled(data) { return data.settings?.tweaksEnabled ?? true; } function resolveUpdatesGroupSize(data) { return data.settings?.updatesGroupSize ?? 0; } function resolvePlaylistChunkSize(data) { return data.settings?.playlistChunkSize ?? 40; } function resolveSeenPostId(data) { return data.updates?.seenPostId ?? 0; } var cachedIds = null; var cachedSync; var cacheHydrated = false; function getGmGetValue$1() { return GM_getValue; } function getGmSetValue$1() { return GM_setValue; } function isUnknownRecord(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function isIntNumber(value) { return typeof value === "number" && Number.isInteger(value); } function isIntNumberArray(value) { return Array.isArray(value) && value.every(isIntNumber); } /** * Cheap page-path shape check: version + integer id array. * Optional `sync` is validated with the small FavsSyncSchema when present. * Full FavsSchema is reserved for {@link parseFavsStrict} (import / migration). */ function cheapParseFavs(raw) { if (!isUnknownRecord(raw)) return null; if (raw.version !== 1) return null; if (!isIntNumberArray(raw.ids)) return null; const next = { version: 1, ids: raw.ids }; if (raw.sync !== void 0) { const syncParsed = FavsSyncSchema.safeParse(raw.sync); if (syncParsed.success) next.sync = syncParsed.data; } return next; } /** Full zod parse for import / migration callers. */ function parseFavsStrict(raw) { const parsed = FavsSchema.safeParse(raw); if (!parsed.success) return null; return parsed.data; } function normalizePostId$1(id) { if (typeof id === "number") { if (!Number.isFinite(id)) return null; return Math.trunc(id); } const trimmed = id.trim(); if (trimmed.length === 0) return null; const parsed = Number(trimmed); if (!Number.isFinite(parsed)) return null; return Math.trunc(parsed); } function readFavsRaw() { const raw = getGmGetValue$1()(FAVS_STORAGE_KEY, void 0); if (raw === void 0 || raw === null) return createDefaultFavs(); const parsed = cheapParseFavs(raw); if (parsed === null) { log.error("Invalid favs storage content; using empty favs", { key: FAVS_STORAGE_KEY }); return createDefaultFavs(); } return parsed; } function writeFavsData(data) { getGmSetValue$1()(FAVS_STORAGE_KEY, data); } function setCacheFromData(data) { cachedIds = new Set(data.ids); cachedSync = data.sync; cacheHydrated = true; } function readMainStorageRaw() { const raw = getGmGetValue$1()(STORAGE_KEY, void 0); if (raw === void 0 || raw === null) return null; const parsed = StorageSchema.safeParse(raw); if (!parsed.success) return null; return parsed.data; } function writeMainStorage(data) { const pruned = pruneMarksIfNeeded(data.marks); const next = pruned.pruned ? { ...data, marks: pruned.marks } : data; getGmSetValue$1()(STORAGE_KEY, StorageSchema.parse(next)); } /** * Extract legacy `marks.*.fav === true` into favs.ids, strip `fav` from marks, * strip legacy panel window size from featureState, save both keys. * Idempotent. Preserves `marks.seen` and other featureState keys. * Favs blob: full zod when rewriting after a marks/panel change; cheap read otherwise. */ function migrateMarksFavToFavs() { const main = readMainStorageRaw(); const favsRaw = getGmGetValue$1()(FAVS_STORAGE_KEY, void 0); const favsCheap = favsRaw === void 0 || favsRaw === null ? createDefaultFavs() : cheapParseFavs(favsRaw); const favs = favsCheap ?? createDefaultFavs(); if (favsCheap === null && favsRaw !== void 0 && favsRaw !== null) log.error("Invalid favs storage content; using empty favs", { key: FAVS_STORAGE_KEY }); const ids = new Set(favs.ids); let marksChanged = false; let mainToWrite = null; if (main !== null) { const nextMarks = {}; for (const [postId, flags] of Object.entries(main.marks)) { const nextFlags = {}; if (flags.seen === true) nextFlags.seen = true; if (flags.fav === true) { const normalized = normalizePostId$1(postId); if (normalized !== null) ids.add(normalized); marksChanged = true; } else if (flags.fav !== void 0) marksChanged = true; if (Object.keys(nextFlags).length > 0) nextMarks[postId] = nextFlags; else if (flags.fav === void 0 && flags.seen === void 0) nextMarks[postId] = {}; } let nextMain = main; if (marksChanged) nextMain = { ...main, marks: nextMarks }; const stripped = stripLegacyPanelWindowSize(nextMain); const choices = migrateRetiredFeatureChoices(stripped.data); if (marksChanged || stripped.changed || choices.changed) mainToWrite = choices.data; } if (mainToWrite !== null) writeMainStorage(mainToWrite); const nextFavs = { version: favs.version, ids: Array.from(ids) }; if (favs.sync !== void 0) nextFavs.sync = favs.sync; if (nextFavs.ids.length !== favs.ids.length || nextFavs.ids.some((id) => !favs.ids.includes(id))) { const strict = parseFavsStrict(nextFavs); if (strict === null) log.error("migrateMarksFavToFavs: strict favs validate failed; skipping write", { key: FAVS_STORAGE_KEY }); else { writeFavsData(strict); setCacheFromData(strict); return; } } setCacheFromData(nextFavs); } function ensureCache() { if (cacheHydrated && cachedIds !== null) return cachedIds; migrateMarksFavToFavs(); if (cachedIds === null) setCacheFromData(readFavsRaw()); return cachedIds ?? /* @__PURE__ */ new Set(); } function persistIds(ids) { const next = { version: createDefaultFavs().version, ids: Array.from(ids) }; if (cachedSync !== void 0) next.sync = cachedSync; writeFavsData(next); cachedIds = ids; cacheHydrated = true; } /** Clears the in-memory fav cache (tests / full remount). */ function clearFavsCache() { cachedIds = null; cachedSync = void 0; cacheHydrated = false; } function loadFavSet() { return ensureCache(); } function isFav(id) { const normalized = normalizePostId$1(id); if (normalized === null) return false; return ensureCache().has(normalized); } function addFav(id) { const normalized = normalizePostId$1(id); if (normalized === null) return; const ids = new Set(ensureCache()); if (ids.has(normalized)) { cachedIds = ids; return; } ids.add(normalized); persistIds(ids); } function removeFav(id) { const normalized = normalizePostId$1(id); if (normalized === null) return; const ids = new Set(ensureCache()); if (!ids.has(normalized)) { cachedIds = ids; return; } ids.delete(normalized); persistIds(ids); } function addFavs(ids) { if (ids.length === 0) { ensureCache(); return; } const next = new Set(ensureCache()); let changed = false; for (const id of ids) { const normalized = normalizePostId$1(id); if (normalized === null) continue; if (!next.has(normalized)) { next.add(normalized); changed = true; } } if (changed) persistIds(next); else cachedIds = next; } function getSyncState() { ensureCache(); return cachedSync; } function setSyncState(sync) { const ids = ensureCache(); cachedSync = sync; const next = { version: createDefaultFavs().version, ids: Array.from(ids) }; if (sync !== void 0) next.sync = sync; writeFavsData(next); cacheHydrated = true; } /** * Strip legacy `fav` flags from a marks record and return the fav post ids found. * Used by import to treat old `marks.fav` as fav ids. */ function extractFavIdsFromMarks(marks) { const favIds = []; const nextMarks = {}; for (const [postId, flags] of Object.entries(marks)) { if (flags.fav === true) { const normalized = normalizePostId$1(postId); if (normalized !== null) favIds.push(normalized); } const nextFlags = {}; if (flags.seen === true) nextFlags.seen = true; if (Object.keys(nextFlags).length > 0) nextMarks[postId] = nextFlags; } return { marks: nextMarks, favIds }; } var cachedStorage = null; var storageCacheHydrated = false; /** When the cache last matched storage: a real read, or our own write. */ var cacheFreshAt = 0; /** How old the cache may be for {@link loadRecent}. */ var RECENT_READ_WINDOW_MS = 1e3; function getGmGetValue$2() { return GM_getValue; } function getGmSetValue() { return GM_setValue; } function readRaw() { return getGmGetValue$2()(STORAGE_KEY, void 0); } function writeData(data) { getGmSetValue()(STORAGE_KEY, data); } function setStorageCache(data) { cachedStorage = data; storageCacheHydrated = true; cacheFreshAt = Date.now(); } /** Authoritative replace: used after intentional GM writes ({@link save}). */ function syncArtistsMirror(data) { writeArtistsMirror(data.artists.map((entry) => entry.tag)); } /** * Seeds the mirror from GM only when missing/unparseable. * Never replaces an existing fresher mirror (bfcache / cross-tab). */ function seedArtistsMirrorIfMissing(data) { if (readArtistsMirror() !== null) return; syncArtistsMirror(data); } /** Clears the in-memory main storage cache (tests / full remount). */ function clearStorageCache() { cachedStorage = null; storageCacheHydrated = false; cacheFreshAt = 0; } function loadUncached() { const raw = readRaw(); if (raw === void 0 || raw === null) { migrateMarksFavToFavs(); const empty = createDefaultStorage(); seedArtistsMirrorIfMissing(empty); return empty; } const parsed = StorageSchema.safeParse(raw); if (!parsed.success) { backupInvalid(raw); migrateMarksFavToFavs(); const empty = createDefaultStorage(); seedArtistsMirrorIfMissing(empty); return empty; } migrateMarksFavToFavs(); const after = readRaw(); if (after === void 0 || after === null) { const empty = createDefaultStorage(); seedArtistsMirrorIfMissing(empty); return empty; } const reparsed = StorageSchema.safeParse(after); if (!reparsed.success) { seedArtistsMirrorIfMissing(parsed.data); return persistCollectionMediaMigration(parsed.data); } seedArtistsMirrorIfMissing(reparsed.data); return persistCollectionMediaMigration(reparsed.data); } function persistCollectionMediaMigration(data) { const migrated = migrateCollectionMediaFields(data); if (!migrated.changed) return data; const parsed = StorageSchema.parse(migrated.data); writeData(parsed); return parsed; } function backupInvalid(raw) { getGmSetValue()(STORAGE_BACKUP_KEY, raw); log.error("Invalid storage content backed up", { key: STORAGE_KEY, backupKey: STORAGE_BACKUP_KEY }); } function currentSettings(data) { const next = { gridFavButtons: resolveGridFavButtons(data), updatesGroupSize: resolveUpdatesGroupSize(data), playlistChunkSize: resolvePlaylistChunkSize(data), tweaksEnabled: resolveTweaksEnabled(data) }; if (data.settings?.features !== void 0) next.features = { ...data.settings.features }; if (data.settings?.featureChoice !== void 0) next.featureChoice = { ...data.settings.featureChoice }; if (data.settings?.featureState !== void 0) next.featureState = { ...data.settings.featureState }; if (data.settings?.appearance !== void 0) next.appearance = data.settings.appearance; return next; } function normalizePostId(postId) { if (!Number.isFinite(postId)) return null; const truncated = Math.trunc(postId); if (truncated < 0) return null; return truncated; } function load$1() { if (storageCacheHydrated && cachedStorage !== null) return cachedStorage; const data = loadUncached(); setStorageCache(data); return data; } /** Drop the in-memory cache and re-read + validate from GM storage. */ function reloadFromStorage() { clearStorageCache(); return load$1(); } /** * Data for reading only, at most a second old. Reading and validating the * whole storage is slow on a large library, and a page's modules each want * "current" data within the same moment: they share one read through this. * Anything that writes must use {@link reloadFromStorage} first, so a change * made in another tab is not overwritten. */ function loadRecent() { if (storageCacheHydrated && cachedStorage !== null && Date.now() - cacheFreshAt < RECENT_READ_WINDOW_MS) return cachedStorage; return reloadFromStorage(); } /** True when any mark still carries the legacy `fav` flag. */ function hasLegacyFavMarks(marks) { for (const flags of Object.values(marks)) if (flags.fav !== void 0) return true; return false; } function save(data) { const migrated = migrateCollectionMediaFields(StorageSchema.parse(data)).data; const pruned = pruneMarksIfNeeded(migrated.marks); const toWrite = pruned.pruned ? { ...migrated, marks: pruned.marks } : migrated; writeData(toWrite); if (!hasLegacyFavMarks(toWrite.marks)) { setStorageCache(toWrite); syncArtistsMirror(toWrite); return; } migrateMarksFavToFavs(); const after = readRaw(); if (after === void 0 || after === null) { const empty = createDefaultStorage(); setStorageCache(empty); syncArtistsMirror(empty); return; } const reparsed = StorageSchema.safeParse(after); if (!reparsed.success) { setStorageCache(toWrite); syncArtistsMirror(toWrite); return; } setStorageCache(reparsed.data); syncArtistsMirror(reparsed.data); } function renameCollection(id, name) { const data = reloadFromStorage(); const target = data.collections.find((item) => item.id === id); if (target === void 0) return null; target.name = name.trim(); CollectionSchema.parse(target); save(data); return target; } function deleteCollection(id) { const data = reloadFromStorage(); const next = data.collections.filter((item) => item.id !== id); if (next.length === data.collections.length) return false; removeCoverMirror(id); removeCountMirror(id); data.collections = next; save(data); return true; } /** Creates a post playlist (`kind: "posts"`, empty tags, empty postIds). */ function createPlaylist(name) { const data = reloadFromStorage(); const collection = CollectionSchema.parse({ id: crypto.randomUUID(), name: name.trim(), tags: [], kind: COLLECTION_KIND_POSTS, postIds: [], thumbs: {}, shuffledOrder: null }); data.collections.push(collection); save(data); return collection; } function listPlaylists() { return load$1().collections.filter(isPlaylist); } function playlistsContaining(postId) { const normalized = normalizePostId(postId); if (normalized === null) return []; return listPlaylists().filter((playlist) => (playlist.postIds ?? []).includes(normalized)); } var FISHER_YATES_STOP_INDEX = 0; var SHUFFLE_DISTINCT_MIN_LENGTH = 2; var SHUFFLE_FALLBACK_INDEX = 1; function thumbKey(postId) { return String(postId); } function readThumb(thumbs, postId) { if (thumbs === void 0) return null; const value = thumbs[thumbKey(postId)]; if (value === void 0 || value.length === 0) return null; return value; } function normalizeThumbUrl(thumbUrl) { if (thumbUrl === void 0) return null; const trimmed = thumbUrl.trim(); if (trimmed.length === 0) return null; return trimmed; } function samePostOrder(left, right) { if (left.length !== right.length) return false; for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false; return true; } /** Fisher-Yates. When another permutation exists, the result is not `order`. */ function shufflePermutation(order) { const next = [...order]; for (let index = next.length - 1; index > FISHER_YATES_STOP_INDEX; index -= 1) { const swapIndex = Math.floor(Math.random() * (index + 1)); const current = next[index]; const swapped = next[swapIndex]; if (current === void 0 || swapped === void 0) continue; next[index] = swapped; next[swapIndex] = current; } if (next.length < SHUFFLE_DISTINCT_MIN_LENGTH || !samePostOrder(next, order)) return next; const first = next[FISHER_YATES_STOP_INDEX]; const second = next[SHUFFLE_FALLBACK_INDEX]; if (first === void 0 || second === void 0) return next; next[FISHER_YATES_STOP_INDEX] = second; next[SHUFFLE_FALLBACK_INDEX] = first; return next; } function clampInsertIndex(index, length) { if (!Number.isFinite(index) || index < FISHER_YATES_STOP_INDEX) return length; const truncated = Math.trunc(index); if (truncated > length) return length; return truncated; } /** * Display order: `shuffledOrder` with deleted ids dropped, then postIds that * are not in that list (new since the shuffle), in insertion order. * `null` / missing `shuffledOrder` is insertion order. */ function collectionDisplayOrder(collection) { const insertion = collection.postIds ?? []; const shuffled = collection.shuffledOrder; if (shuffled === void 0 || shuffled === null) return [...insertion]; const present = new Set(insertion); const ordered = []; const seen = /* @__PURE__ */ new Set(); for (const id of shuffled) { if (!present.has(id) || seen.has(id)) continue; ordered.push(id); seen.add(id); } for (const id of insertion) { if (seen.has(id)) continue; ordered.push(id); seen.add(id); } return ordered; } function findPlaylist(data, collectionId) { const target = data.collections.find((item) => item.id === collectionId); if (target === void 0 || !isPlaylist(target)) return null; return target; } function ensurePostsMedia(target) { target.kind = COLLECTION_KIND_POSTS; target.tags = []; if (target.thumbs === void 0) target.thumbs = {}; if (target.shuffledOrder === void 0) target.shuffledOrder = null; } /** * Phase 2 HANDOFF: custom collections are `kind: "posts"`. * Append `postId` (no duplicates). Pass `thumbUrl` to store a thumb. * Re-add with a URL fills an empty thumb; re-add without a URL keeps a known thumb. * New ids stay out of `shuffledOrder` and show up at the end of {@link getCollectionOrder}. */ function addPostToCollection(collectionId, postId, thumbUrl) { const normalized = normalizePostId(postId); if (normalized === null) return null; const data = reloadFromStorage(); const target = findPlaylist(data, collectionId); if (target === null) return null; const postIds = [...target.postIds ?? []]; if (!postIds.includes(normalized)) { postIds.push(normalized); if (target.shuffledOrder !== void 0 && target.shuffledOrder !== null) target.shuffledOrder = target.shuffledOrder.filter((id) => id !== normalized); } target.postIds = postIds; const incoming = normalizeThumbUrl(thumbUrl); const known = readThumb(target.thumbs, normalized); const nextThumb = incoming ?? known; if (nextThumb !== null) target.thumbs = { ...target.thumbs ?? {}, [thumbKey(normalized)]: nextThumb }; ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return target; } /** * Appends several posts to a custom collection in one write, by the rules of * {@link addPostToCollection}. `added` counts the posts that were not in the * collection before. A missing or non-posts collection returns null. */ function addPostsToCollection(collectionId, posts) { const data = reloadFromStorage(); const target = findPlaylist(data, collectionId); if (target === null) return null; const postIds = [...target.postIds ?? []]; const present = new Set(postIds); const thumbs = { ...target.thumbs ?? {} }; const fresh = /* @__PURE__ */ new Set(); for (const post of posts) { const normalized = normalizePostId(post.id); if (normalized === null) continue; if (!present.has(normalized)) { present.add(normalized); postIds.push(normalized); fresh.add(normalized); } const nextThumb = normalizeThumbUrl(post.thumbUrl ?? void 0) ?? readThumb(thumbs, normalized); if (nextThumb !== null) thumbs[thumbKey(normalized)] = nextThumb; } if (fresh.size > 0 && target.shuffledOrder !== void 0 && target.shuffledOrder !== null) target.shuffledOrder = target.shuffledOrder.filter((id) => !fresh.has(id)); target.postIds = postIds; target.thumbs = thumbs; ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return { collection: target, added: fresh.size }; } /** * Phase 2 HANDOFF: drops the given ids from a custom collection. * Returned snapshot is the undo input for {@link restorePosts}. * Unknown ids are omitted. A missing or non-posts collection returns null. */ function removePostsFromCollection(collectionId, postIds) { const data = reloadFromStorage(); const target = findPlaylist(data, collectionId); if (target === null) return null; const removal = /* @__PURE__ */ new Set(); for (const rawId of postIds) { const normalized = normalizePostId(rawId); if (normalized !== null) removal.add(normalized); } const currentIds = target.postIds ?? []; const display = collectionDisplayOrder(target); const posts = []; for (let index = 0; index < currentIds.length; index += 1) { const id = currentIds[index]; if (id === void 0 || !removal.has(id)) continue; const displayIndex = display.indexOf(id); posts.push({ postId: id, thumbUrl: readThumb(target.thumbs, id), insertionIndex: index, displayIndex: displayIndex < FISHER_YATES_STOP_INDEX ? index : displayIndex }); } if (posts.length === 0) return { collectionId, posts }; const removedIds = new Set(posts.map((post) => post.postId)); target.postIds = currentIds.filter((id) => !removedIds.has(id)); if (target.shuffledOrder !== void 0 && target.shuffledOrder !== null) target.shuffledOrder = target.shuffledOrder.filter((id) => !removedIds.has(id)); ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return { collectionId, posts }; } function removePostFromPlaylist(id, postId) { const normalized = normalizePostId(postId); if (normalized === null) return null; if (removePostsFromCollection(id, [normalized]) === null) return null; return load$1().collections.find((item) => item.id === id) ?? null; } /** Phase 2 HANDOFF: puts {@link removePostsFromCollection} posts back. */ function restorePosts(snapshot) { const data = reloadFromStorage(); const target = findPlaylist(data, snapshot.collectionId); if (target === null) return null; if (snapshot.posts.length === 0) return target; const postIds = [...target.postIds ?? []]; const thumbs = { ...target.thumbs ?? {} }; const byInsertion = [...snapshot.posts].sort((left, right) => left.insertionIndex - right.insertionIndex); for (const post of byInsertion) { const normalized = normalizePostId(post.postId); if (normalized === null) continue; if (!postIds.includes(normalized)) { const index = clampInsertIndex(post.insertionIndex, postIds.length); postIds.splice(index, 0, normalized); } if (post.thumbUrl !== null && post.thumbUrl.length > 0) thumbs[thumbKey(normalized)] = post.thumbUrl; } target.postIds = postIds; target.thumbs = thumbs; if (target.shuffledOrder !== void 0 && target.shuffledOrder !== null) { const order = [...target.shuffledOrder]; const byDisplay = [...snapshot.posts].sort((left, right) => left.displayIndex - right.displayIndex); for (const post of byDisplay) { const normalized = normalizePostId(post.postId); if (normalized === null || order.includes(normalized)) continue; const index = clampInsertIndex(post.displayIndex, order.length); order.splice(index, 0, normalized); } target.shuffledOrder = order; } ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return target; } /** Phase 2 HANDOFF: replaces `shuffledOrder` with a new permutation of the display order. */ function shuffleCollection(collectionId) { const data = reloadFromStorage(); const target = findPlaylist(data, collectionId); if (target === null) return null; target.shuffledOrder = shufflePermutation(collectionDisplayOrder(target)); ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return target; } /** Phase 2 HANDOFF: `shuffledOrder: null` so {@link getCollectionOrder} follows `postIds`. */ function resetCollectionOrder(collectionId) { const data = reloadFromStorage(); const target = findPlaylist(data, collectionId); if (target === null) return null; target.shuffledOrder = null; ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return target; } /** * Moves one post to the place of another in the order the collection shows. * While the collection is shuffled the shuffled order is edited; otherwise the * insertion order. Returns false when nothing moved. */ function movePostInCollection(collectionId, postId, targetPostId) { const data = reloadFromStorage(); const target = findPlaylist(data, collectionId); if (target === null || postId === targetPostId) return false; const order = collectionDisplayOrder(target); const from = order.indexOf(postId); const to = order.indexOf(targetPostId); if (from < 0 || to < 0) return false; order.splice(from, 1); order.splice(to, 0, postId); if (target.shuffledOrder === void 0 || target.shuffledOrder === null) target.postIds = order; else target.shuffledOrder = order; ensurePostsMedia(target); CollectionSchema.parse(target); save(data); return true; } /** Phase 2 HANDOFF: read-only display order. Null when the id is missing or not a posts collection. */ function getCollectionOrder(collectionId) { const target = findPlaylist(load$1(), collectionId); if (target === null) return null; return collectionDisplayOrder(target); } /** * Phase 2 HANDOFF: saved search. `query` is stored raw; `tags` are `parseTags(query)` * so existing search links keep working. Missing `query` on older rows means * `serialize(collection.tags)`. */ function createDynamicCollection(name, query) { const data = reloadFromStorage(); const trimmedQuery = query.trim(); const collection = CollectionSchema.parse({ id: crypto.randomUUID(), name: name.trim(), tags: parseTags(trimmedQuery), kind: COLLECTION_KIND_SEARCH, query: trimmedQuery }); data.collections.push(collection); save(data); return collection; } /** * Remembers the first thumbs of a saved search for its card cover. * Keeps at most {@link DYNAMIC_COVER_SIZE} non-empty URLs. Writes only when the * cover changed; an empty list never clears a stored cover. * Returns true when storage was written. */ function setDynamicCover(collectionId, thumbUrls) { const cover = []; for (const url of thumbUrls) { const trimmed = url.trim(); if (trimmed.length === 0) continue; cover.push(trimmed); if (cover.length === 4) break; } if (cover.length === 0) return false; const known = load$1().collections; const cached = known.find((item) => item.id === collectionId); if (cached === void 0 || isPlaylist(cached)) return false; writeCoverMirror(collectionId, cover, known.map((item) => item.id)); if (sameStrings(cached.cover ?? [], cover)) return false; const data = reloadFromStorage(); const target = data.collections.find((item) => item.id === collectionId); if (target === void 0 || isPlaylist(target)) return false; if (sameStrings(target.cover ?? [], cover)) return false; target.cover = cover; CollectionSchema.parse(target); save(data); return true; } /** * Remembers how many posts a saved search has, as read from its results page. * Negative or fractional values are ignored. Writes only when the count changed. * Returns true when storage was written. */ function setDynamicPostCount(collectionId, count) { if (!Number.isInteger(count.value) || count.value < 0) return false; const known = load$1().collections; const cached = known.find((item) => item.id === collectionId); if (cached === void 0 || isPlaylist(cached)) return false; writeCountMirror(collectionId, count, known.map((item) => item.id)); if (samePostCount(cached.postCount, count)) return false; const data = reloadFromStorage(); const target = data.collections.find((item) => item.id === collectionId); if (target === void 0 || isPlaylist(target)) return false; if (samePostCount(target.postCount, count)) return false; target.postCount = { value: count.value, exact: count.exact }; CollectionSchema.parse(target); save(data); return true; } /** * Remembers the newest post id of a saved search. `opened` is true when the * user is looking at its results (they have then seen everything up to that * post), false when a "Check for new" run found it. Writes only on a change. */ function setDynamicNewest(collectionId, newestPostId, opened) { if (!Number.isInteger(newestPostId) || newestPostId <= 0) return false; const cached = load$1().collections.find((item) => item.id === collectionId); if (cached === void 0 || isPlaylist(cached)) return false; if (cached.newestPostId === newestPostId && (!opened || cached.openedPostId === newestPostId)) return false; const data = reloadFromStorage(); const target = data.collections.find((item) => item.id === collectionId); if (target === void 0 || isPlaylist(target)) return false; target.newestPostId = Math.max(target.newestPostId ?? 0, newestPostId); if (opened) { target.openedPostId = newestPostId; target.newestPostId = newestPostId; } CollectionSchema.parse(target); save(data); return true; } /** True when a check found posts newer than the ones seen at the last opening. */ function dynamicHasNew(collection) { return collection.openedPostId !== void 0 && collection.newestPostId !== void 0 && collection.newestPostId > collection.openedPostId; } function samePostCount(left, right) { return left !== void 0 && left.value === right.value && left.exact === right.exact; } function sameStrings(left, right) { if (left.length !== right.length) return false; for (let index = 0; index < left.length; index += 1) if (left[index] !== right[index]) return false; return true; } /** Phase 2 HANDOFF: replaces `query` and `tags` on a saved search. Posts collections return null. */ function updateDynamicQuery(collectionId, query) { const data = reloadFromStorage(); const target = data.collections.find((item) => item.id === collectionId); if (target === void 0 || isPlaylist(target)) return null; const trimmedQuery = query.trim(); if (target.query !== trimmedQuery) { delete target.cover; delete target.postCount; removeCoverMirror(collectionId); removeCountMirror(collectionId); } target.query = trimmedQuery; target.tags = parseTags(trimmedQuery); target.kind = COLLECTION_KIND_SEARCH; CollectionSchema.parse(target); save(data); return target; } function setPostSeenMark(postId) { const data = load$1(); const previous = data.marks[postId] ?? {}; data.marks[postId] = { ...previous, seen: true }; save(data); } function getGridFavButtonsEnabled() { return resolveGridFavButtons(load$1()); } function setGridFavButtonsEnabled(enabled) { const data = load$1(); data.settings = { ...currentSettings(data), gridFavButtons: enabled }; save(data); } function getTweaksEnabled() { return resolveTweaksEnabled(load$1()); } function setTweaksEnabled(enabled) { const data = load$1(); data.settings = { ...currentSettings(data), tweaksEnabled: enabled }; save(data); } function getFeatureEnabled(id, defaultEnabled) { const stored = load$1().settings?.features?.[id]; if (stored === void 0) return defaultEnabled; return stored; } function setFeatureEnabled(id, enabled) { const data = load$1(); const settings = currentSettings(data); const features = { ...settings.features ?? {}, [id]: enabled }; data.settings = { ...settings, features }; save(data); } /** Drops a feature's saved state so its defaults apply on the next mount. */ function clearFeatureState(id) { const data = load$1(); const settings = currentSettings(data); const current = settings.featureState; if (current === void 0 || !(id in current)) return; const featureState = {}; for (const [key, value] of Object.entries(current)) if (key !== id) featureState[key] = value; data.settings = { ...settings, featureState }; save(data); } function getFeatureChoiceValue(id) { return load$1().settings?.featureChoice?.[id]; } function setFeatureChoiceValue(id, value) { const data = load$1(); const settings = currentSettings(data); const featureChoice = { ...settings.featureChoice ?? {}, [id]: value }; data.settings = { ...settings, featureChoice }; save(data); } function getFeatureState(id) { return load$1().settings?.featureState?.[id]; } function setFeatureState(id, value) { const data = reloadFromStorage(); const settings = currentSettings(data); const featureState = { ...settings.featureState ?? {}, [id]: value }; data.settings = { ...settings, featureState }; save(data); } /** * Effective artists-per-search pack size for query building. * Stored 0 (default) means MAX_UPDATES_GROUP_SIZE; values above the max are capped. */ function getUpdatesGroupSize() { const stored = resolveUpdatesGroupSize(load$1()); if (!Number.isFinite(stored) || stored <= 0) return 400; return Math.min(Math.floor(stored), 400); } function setUpdatesGroupSize(size) { const data = load$1(); let safeSize = Number.isFinite(size) && size >= 0 ? Math.floor(size) : 0; if (safeSize > 400) safeSize = 400; data.settings = { ...currentSettings(data), updatesGroupSize: safeSize }; save(data); } function getPlaylistChunkSize() { return resolvePlaylistChunkSize(load$1()); } function setPlaylistChunkSize(size) { const data = load$1(); const safeSize = Number.isFinite(size) && size > 0 ? Math.floor(size) : 40; data.settings = { ...currentSettings(data), playlistChunkSize: safeSize }; save(data); } function getAppearance() { return resolveAppearance(load$1()); } function setAppearance(appearance) { const parsed = AppearanceSchema.parse(appearance); const data = load$1(); data.settings = { ...currentSettings(data), appearance: parsed }; save(data); return parsed; } function getSeenPostId() { return resolveSeenPostId(load$1()); } function setSeenPostId(seenPostId) { const data = load$1(); data.updates = { seenPostId: Number.isFinite(seenPostId) && seenPostId >= 0 ? Math.floor(seenPostId) : 0 }; save(data); } /** * Followed artist tags from a recent GM read (see {@link loadRecent}). * Feed href / recognition and Follow/Unfollow must not diverge across pages. */ function listArtistTags() { return loadRecent().artists.map((entry) => entry.tag); } /** The kind of a followed entry; one saved before kinds existed is an artist. */ function followKindOf(entry) { return entry.kind ?? "artist"; } /** * Groups of the Following page and of the Collections page. A followed tag or * a collection is in one group or in none: its `group` is the name. A group * made with nothing in it yet, or left empty, has no entry to carry its name, * so the names are kept as well, per page, in the feature state. */ var FOLLOW_GROUPS_STATE_ID = "follow-groups"; var COLLECTION_GROUPS_STATE_ID = "collection-groups"; function keptGroupNames(data, stateId) { const kept = data.settings?.featureState?.[stateId]; if (!Array.isArray(kept)) return []; const names = []; for (const name of kept) if (typeof name === "string" && name.length > 0) names.push(name); return names; } function writeKeptGroupNames(data, stateId, names) { const settings = currentSettings(data); data.settings = { ...settings, featureState: { ...settings.featureState ?? {}, [stateId]: [...new Set(names)] } }; } /** * The groups in the order they were made (the designer, 18.11.2026). A group * older than the kept list, known only from what is in it, comes after those, * by name. */ function sortedGroupNames(used, kept) { const names = new Set(kept); const older = /* @__PURE__ */ new Set(); for (const name of used) if (name !== void 0 && name.length > 0 && !names.has(name)) older.add(name); return [...names, ...[...older].sort((a, b) => a.localeCompare(b))]; } /** The names of the groups of the Following page, in the order they were made. */ function listFollowGroups() { const data = load$1(); return sortedGroupNames(data.artists.map((entry) => entry.group), keptGroupNames(data, FOLLOW_GROUPS_STATE_ID)); } /** * Puts the given followed tags into a group, or takes them out of theirs when * `group` is null or blank. Returns how many entries changed. */ function setFollowGroup(tags, group) { const name = group === null ? "" : group.trim(); const wanted = new Set(tags); const data = reloadFromStorage(); let changed = 0; data.artists = data.artists.map((entry) => { if (!wanted.has(entry.tag) || (entry.group ?? "") === name) return entry; changed += 1; const { group: _dropped, ...rest } = entry; return name.length > 0 ? { ...rest, group: name } : rest; }); if (name.length > 0) writeKeptGroupNames(data, FOLLOW_GROUPS_STATE_ID, [...keptGroupNames(data, FOLLOW_GROUPS_STATE_ID), name]); if (changed > 0 || name.length > 0) save(data); return changed; } /** Makes a group with nothing in it. False when the name is blank or taken. */ function createFollowGroup(group) { const name = group.trim(); if (name.length === 0 || listFollowGroups().includes(name)) return false; const data = reloadFromStorage(); writeKeptGroupNames(data, FOLLOW_GROUPS_STATE_ID, [...keptGroupNames(data, FOLLOW_GROUPS_STATE_ID), name]); save(data); return true; } /** Gives a group another name. False when the new name is blank or taken. */ function renameFollowGroup(from, to) { const name = to.trim(); if (name.length === 0 || name === from || listFollowGroups().includes(name)) return false; const data = reloadFromStorage(); data.artists = data.artists.map((entry) => entry.group === from ? { ...entry, group: name } : entry); writeKeptGroupNames(data, FOLLOW_GROUPS_STATE_ID, [...keptGroupNames(data, FOLLOW_GROUPS_STATE_ID).map((kept) => kept === from ? name : kept), name]); save(data); return true; } /** Deletes a group; what was in it is in no group. Returns how many entries that was. */ function deleteFollowGroup(group) { const data = reloadFromStorage(); let changed = 0; data.artists = data.artists.map((entry) => { if (entry.group !== group) return entry; changed += 1; const { group: _dropped, ...rest } = entry; return rest; }); writeKeptGroupNames(data, FOLLOW_GROUPS_STATE_ID, keptGroupNames(data, FOLLOW_GROUPS_STATE_ID).filter((kept) => kept !== group)); save(data); return changed; } /** The names of the groups of the Collections page, in the order they were made. */ function listCollectionGroups() { const data = load$1(); return sortedGroupNames(data.collections.map((item) => item.group), keptGroupNames(data, COLLECTION_GROUPS_STATE_ID)); } /** * Puts the given collections into a group, or takes them out of theirs when * `group` is null or blank. Returns how many collections changed. */ function setCollectionGroup(ids, group) { const name = group === null ? "" : group.trim(); const wanted = new Set(ids); const data = reloadFromStorage(); let changed = 0; data.collections = data.collections.map((item) => { if (!wanted.has(item.id) || (item.group ?? "") === name) return item; changed += 1; const { group: _dropped, ...rest } = item; return name.length > 0 ? { ...rest, group: name } : rest; }); if (name.length > 0) writeKeptGroupNames(data, COLLECTION_GROUPS_STATE_ID, [...keptGroupNames(data, COLLECTION_GROUPS_STATE_ID), name]); if (changed > 0 || name.length > 0) save(data); return changed; } /** Makes a group of collections with nothing in it. False when the name is blank or taken. */ function createCollectionGroup(group) { const name = group.trim(); if (name.length === 0 || listCollectionGroups().includes(name)) return false; const data = reloadFromStorage(); writeKeptGroupNames(data, COLLECTION_GROUPS_STATE_ID, [...keptGroupNames(data, COLLECTION_GROUPS_STATE_ID), name]); save(data); return true; } /** Gives a group of collections another name. False when the new name is blank or taken. */ function renameCollectionGroup(from, to) { const name = to.trim(); if (name.length === 0 || name === from || listCollectionGroups().includes(name)) return false; const data = reloadFromStorage(); data.collections = data.collections.map((item) => item.group === from ? { ...item, group: name } : item); writeKeptGroupNames(data, COLLECTION_GROUPS_STATE_ID, [...keptGroupNames(data, COLLECTION_GROUPS_STATE_ID).map((kept) => kept === from ? name : kept), name]); save(data); return true; } /** Deletes a group of collections; what was in it is in no group. Returns how many that was. */ function deleteCollectionGroup(group) { const data = reloadFromStorage(); let changed = 0; data.collections = data.collections.map((item) => { if (item.group !== group) return item; changed += 1; const { group: _dropped, ...rest } = item; return rest; }); writeKeptGroupNames(data, COLLECTION_GROUPS_STATE_ID, keptGroupNames(data, COLLECTION_GROUPS_STATE_ID).filter((kept) => kept !== group)); save(data); return changed; } /** Follows several artist tags in one write. Unknown shapes are counted, not thrown. */ function addArtists(tags) { const data = reloadFromStorage(); const known = new Set(data.artists.map((entry) => entry.tag)); let added = 0; let duplicates = 0; let invalid = 0; for (const raw of tags) { const normalized = normalizeArtistTag(raw); if (normalized === null) { invalid += 1; continue; } if (known.has(normalized)) { duplicates += 1; continue; } known.add(normalized); data.artists.push(ArtistEntrySchema.parse({ tag: normalized, addedAt: Date.now() })); added += 1; } if (added > 0) save(data); return { added, duplicates, invalid }; } /** Unfollows several artists in one write. Returns how many were removed. */ function removeArtists(tags) { const doomed = new Set(tags); const data = reloadFromStorage(); const next = data.artists.filter((entry) => !doomed.has(entry.tag)); const removed = data.artists.length - next.length; if (removed > 0) { data.artists = next; save(data); } return removed; } /** True when a snapshot would change what is stored about an artist. */ function snapshotChanges(target, snapshot) { const count = snapshot.postCount; return snapshot.cover.length > 0 && !sameStrings(target.cover ?? [], snapshot.cover) || count !== null && (target.postCount?.value !== count.value || target.postCount.exact !== count.exact) || snapshot.lastPostId > (target.lastPostId ?? 0); } /** A newer post than the remembered one: keep it and when it was first seen. */ function applyLastPost(target, postId, now) { if (postId <= 0 || postId <= (target.lastPostId ?? 0)) return false; target.lastPostId = postId; target.lastPostSince = now; return true; } /** * Remembers what an artist's first results page showed. An empty cover or a * missing count never clears a stored one. Writes only when something changed. */ function rememberArtistSnapshot(tag, snapshot, now = Date.now()) { const known = loadRecent().artists.find((entry) => entry.tag === tag); if (known === void 0 || !snapshotChanges(known, snapshot)) return false; const data = reloadFromStorage(); const target = data.artists.find((entry) => entry.tag === tag); if (target === void 0) return false; let changed = false; if (snapshot.cover.length > 0 && !sameStrings(target.cover ?? [], snapshot.cover)) { target.cover = [...snapshot.cover]; changed = true; } const count = snapshot.postCount; if (count !== null && (target.postCount?.value !== count.value || target.postCount.exact !== count.exact)) { target.postCount = { value: count.value, exact: count.exact }; changed = true; } if (applyLastPost(target, snapshot.lastPostId, now)) changed = true; if (changed) save(data); return changed; } /** Remembers the newest post seen per artist tag, in one write. */ function rememberArtistLastPosts(newest, now = Date.now()) { if (!loadRecent().artists.some((entry) => (newest.get(entry.tag) ?? 0) > (entry.lastPostId ?? 0))) return false; const data = reloadFromStorage(); let changed = false; for (const target of data.artists) { const postId = newest.get(target.tag); if (postId !== void 0 && applyLastPost(target, postId, now)) changed = true; } if (changed) save(data); return changed; } function removeArtist(tag) { const normalized = normalizeArtistTag(tag); if (normalized === null) return false; const data = reloadFromStorage(); const next = data.artists.filter((entry) => entry.tag !== normalized); if (next.length === data.artists.length) return false; data.artists = next; save(data); return true; } var SITE_SELECTORS = exports("S",{ thumb: "span.thumb", thumbLink: "a[href*=\"s=view\"]", previewImage: "img.preview", cardFavButton: `button.${CSS_CLASS.cardFav}`, favoritesDeleteLink: "a[onclick]", tagSidebar: "ul#tag-sidebar", tagTypeArtist: "li.tag-type-artist", tagTypeCharacter: "li.tag-type-character", tagTypeCopyright: "li.tag-type-copyright", /** A tag row of the sidebar, any tag type. */ tagSidebarRow: "ul#tag-sidebar > li[class*=\"tag-type-\"]", /** Number of posts with the tag, inside its sidebar row. */ tagCount: "span.tag-count", imageList: "div.image-list", /** Comments page: the list of posts with their comments. */ commentList: "div#comments div#comment-list", /** Comments page: the preview cell of a post, `div#p{ID}.post > div.col1.thumb > a > img.preview`. */ commentThumb: "div#comments div#comment-list > div.post > div.col1.thumb", /** Comments page: the whole tag list of a post, one `span` per tag. */ commentTags: "div#comments div#comment-list > div.post > div.col2 > div.header > div.tags", postListContent: "#post-list div.content", contentRoot: "#content", artistFollowButton: `button.${CSS_CLASS.artistFollow}`, /** Native AI filter checkbox (site owns click/cookie logic). */ filterAiCheckbox: "input.toggleSwitch#chkFilterAI", /** Row wrapping the native AI filter control — hide when search-tools mirrors it. */ filterAiRow: "li:has(> label > span.switch > input.toggleSwitch#chkFilterAI)", /** Post page: site link to the previous post of the last search (href="#", site JS). */ postPrevSearchLink: "a#prev_search_link", /** Post page: site link to the next post of the last search (href="#", site JS). */ postNextSearchLink: "a#next_search_link", /** List page pager. */ pagination: "div.pagination", /** Pager link to the last results page; its `pid` is the offset of that page. */ paginationLastPage: "div.pagination a[alt=\"last page\"]", /** Any pager link to another results page. */ paginationPageLink: "div.pagination > a[href]", /** Stray Tags heading between #rdw-search-tools and the tag list. */ tagsHeadingAfterSearchTools: "#rdw-search-tools + h5" }); var THUMB_ID_PATTERN = /^s(\d+)$/; var THUMB_LINK_ID_PATTERN = /^p(\d+)$/; var FAVORITES_DELETE_ID_PATTERN = /s=delete&id=(\d+)/; function extractPostIdFromThumb(thumb) { const match = THUMB_ID_PATTERN.exec(thumb.id); if (match === null) return null; const postId = match[1]; return postId === void 0 ? null : postId; } /** * Post id from the thumb's link `a#p{ID}`. A favorites thumb has no `s{ID}` * id of its own, so this is the only place its post id is written. */ function extractPostIdFromThumbLink(thumb) { const link = thumb.querySelector(SITE_SELECTORS.thumbLink); if (link === null) return null; const match = THUMB_LINK_ID_PATTERN.exec(link.id); if (match === null) return null; const postId = match[1]; return postId === void 0 ? null : postId; } /** * Post id of a Comments page preview: the cell has no id, the post around it * is `div#p{ID}.post`. */ function extractPostIdFromCommentThumb(thumb) { const post = thumb.parentElement; if (post === null) return null; const match = THUMB_LINK_ID_PATTERN.exec(post.id); if (match === null) return null; const postId = match[1]; return postId === void 0 ? null : postId; } function extractPostIdFromFavoritesDeleteOnclick(onclick) { const match = FAVORITES_DELETE_ID_PATTERN.exec(onclick); if (match === null) return null; const postId = match[1]; return postId === void 0 ? null : postId; } var n; var t$1; var u$2; var i$1; var f$2; var o$2; var e$1; var l$1; var c$1; var a$2; var s$1; var h$1 = Symbol.for("pv"); var p$1 = {}; var y$1 = []; var v$1 = /^m(i|n|o|s|text|space)$/; var w$2 = Array.isArray; var d$1 = y$1.slice; var _$1 = Object.assign; function g$1(n) { n && n.parentNode && n.remove(); } function k$1(n, t, r) { var u, i, f, o = {}, e = arguments.length; for (f in t) "key" == f ? u = t[f] : "ref" == f && "function" != typeof n ? i = t[f] : o[f] = t[f]; return e > 2 && (o.children = e > 3 ? d$1.call(arguments, 2) : r), m$1(n, o, u, i, null); } function m$1(r, u, i, f, o) { var e = { type: r, props: u, key: i, ref: f, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: h$1, __v: o || ++t$1, __i: -1, __u: 0 }; return !o && n.vnode && n.vnode(e), e; } function $$1(n) { return n.children; } function x$1(n, t) { this.props = n, this.context = t, this.__g = 0; } function S(n, t) { if (null == t) return n.__ && S(n.__, n.__i + 1); for (var r; t < n.__k.length; t++) if ((r = n.__k[t]) && r.__e) return r.__e; return "function" != typeof n.type || n.props.__P ? null : S(n); } function C$1(t) { var r, u = t.__v, i = u.__e, f = [], o = [], e = t.__P; e && ((r = _$1({ constructor: h$1 }, u)).__v = u.__v + 1, n.vnode && n.vnode(r), z$2(e, r, u, t.__n, e.namespaceURI, 32 & u.__u ? [i] : null, f, i || S(u), 32 & u.__u, o), r.__v = u.__v, r.__.__k[r.__i] = r, E$1(f, r, o), u.__ = u.__e = null, r.__e != i && j$1(r)); } function j$1(n) { if ((n = n.__) && n.__c && !n.props.__P) return n.__e = null, n.__k.some(function(t) { return t && (n.__e = t.__e); }), j$1(n); } function L(t) { (8 & t.__g || (t.__g |= 8, u$2.push(t), f$2++)) && i$1 == n.debounceRendering || ((i$1 = n.debounceRendering) || queueMicrotask)(H$1); } function H$1() { try { for (var n, t = 1; u$2.length;) u$2.length > t && u$2.sort(o$2), n = u$2.shift(), t = u$2.length, 8 & n.__g && C$1(n); } finally { (f$2 = u$2.length) && (i$1 || queueMicrotask)(H$1); } } function I(n, t, r, u, i, f, o, e, l, c, a) { var s, h, v, w, d, _, g = u.__k || y$1, k = t.length; for (l = q(r, t, g, l, k), s = 0; s < k; s++) null != (v = r.__k[s]) && (h = ~v.__i && g[v.__i] || p$1, v.__i = s, _ = z$2(n, v, h, i, f, o, e, l, c, a), w = v.__e, (h.ref != v.ref || 8 & h.__u) && (h.ref && G$1(h.ref, null, v, h), v.ref && a.push(v.ref, v.__c || w, v)), d = d || w, 4 & v.__u ? (l = A$1(v, l, n, !h.__v), h.__e && (h.__e = null)) : "function" == typeof v.type && void 0 !== _ ? l = _ : w && (l = w.nextSibling), v.__u &= -21); return r.__e = d, l; } function q(n, t, r, u, i) { var f, o, e, l, c, a, s, p, y, v = r.length, d = v, _ = 0, g = 0, k = n.__k = Array(i); for (f = 0; f < i; f++) null != (o = t[f]) && "boolean" != typeof o && "function" != typeof o ? ("object" != typeof o || o.constructor === String ? o = k[f] = m$1(null, o) : w$2(o) ? o = k[f] = m$1($$1, { children: o }) : o.constructor === h$1 && o.__b ? o = k[f] = m$1(o.type, o.props, o.key, o.ref, o.__v) : k[f] = o, l = f + _, o.__ = n, o.__b = n.__b + 1, e = null, ~(c = o.__i = P$2(o, r, l, d)) && (d--, (e = r[c]) && (e.__u |= 2)), e && e.__v ? (o.__u |= 16, c == l - 1 ? _-- : c == l + 1 ? _++ : c != l && (c > l ? _-- : _++, g = 1)) : (~c || (i > v ? _-- : i < v && _++), "function" != typeof o.type && (o.__u |= 4))) : k[f] = null; if (g) { for (a = [], s = [], f = 0; f < i; f++) if ((o = k[f]) && 16 & o.__u) { for (_ = 0, p = a.length; _ < p;) a[y = _ + p >> 1] < o.__i ? _ = y + 1 : p = y; a[_] = o.__i, s[f] = _ + 1; } for (_ = a.length; f--;) s[f] && (s[f] == _ ? _-- : k[f].__u |= 4); } if (d) for (f = 0; f < v; f++) !(e = r[f]) || 2 & e.__u || (e.__e == u && (u = S(e)), J$1(e, e)); return u; } function A$1(n, t, r, u) { var i, f, o, e; if ("function" == typeof n.type) { if (n.props.__P) return t; if (i = n.__k) for (f = 0; f < i.length; f++) i[f] && (i[f].__ = n, t = A$1(i[f], t, r, false)); return t; } for (t && !t.parentNode && (t = S(n)) && !t.parentNode && (t = null), o = n.__e, e = t; e && 8 == e.nodeType;) e = e.nextSibling; for (o != e && (!u && r.moveBefore && o.parentNode ? r.moveBefore(o, t) : r.insertBefore(o, t || null)), t = o; (t = t && t.nextSibling) && 8 == t.nodeType && !t.data.startsWith("$s");); return t; } function O(n, t) { return t = t || [], null != n && "boolean" != typeof n && (w$2(n) ? n.some(function(n) { O(n, t); }) : t.push(n)), t; } function P$2(n, t, r, u) { var i, f = n.key, o = n.type, e = t[r], l = e && !(2 & e.__u); if (null === e && null == f || l && f == e.key && o == e.type) return r; if (u > (l ? 1 : 0)) { for (i = r - 1; i >= 0; i--) if ((e = t[i]) && !(2 & e.__u) && f == e.key && o == e.type) return i; for (i = r + 1; i < t.length; i++) if ((e = t[i]) && !(2 & e.__u) && f == e.key && o == e.type) return i; } return -1; } function T$1(n, t, r) { r ??= "", "-" == t[0] ? n.setProperty(t, r) : n[t] = r; } function N(n, t, r, u, i) { var f, o; if ("style" == t) if ("string" == typeof r) n.style.cssText = r; else { if ("string" == typeof u && (n.style.cssText = u = ""), u) for (t in u) r && t in r || T$1(n.style, t); if (r) for (t in r) u && r[t] == u[t] || T$1(n.style, t, r[t]); } else if ("o" == t[0] && "n" == t[1]) "function" != typeof r && (r = null), "function" != typeof u && (u = null), (n.__e || (n.__e = {}))[t] = r, r && u || (o = a$2[t] || (a$2[t] = V(t)), (n.__a || (n.__a = {}))[t] = c$1, f = t != (t = t.replace(l$1, "$1")), (t = t.slice(2))[0] < "a" && (t = t.toLowerCase()), r ? n.addEventListener(t, o, f) : n.removeEventListener(t, o, f)); else { if ("http://www.w3.org/2000/svg" == i) t = t.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s"); else if ("width" != t && "height" != t && "href" != t && "list" != t && "form" != t && "tabIndex" != t && "download" != t && "rowSpan" != t && "colSpan" != t && "role" != t && "popover" != t && t in n) try { n[t] = null == r ? "" : r; return; } catch (n) {} if ("function" == typeof r) return; null == r || false === r && "-" != t[4] ? n.removeAttribute(t) : n.setAttribute(t, "popover" == t && 1 == r ? "" : r); } } function V(t) { return function(r) { var u = this.__e; if (u) { if (u = u[t], null == r[e$1]) r[e$1] = c$1++; else if (r[e$1] < this.__a[t]) return; return u(n.event ? n.event(r) : r); } }; } function z$2(t, r, u, i, f, o, e, l, c, a) { var s, p, v, d, k, b, m, M, C, j, L, H, q, A, O, P, T, N, V = r.type; if (r.constructor !== h$1) return null; 128 & u.__u && (c = 32 & u.__u, s = u.__c.__z) && (r.__u |= c, p = o = [], 8 == s.nodeType ? l = B$1(s, o) : o.push(s), l = o[0] || l), (s = n.__b) && s(r); n: if ("function" == typeof V) { v = e.length; try { if (M = r.props, C = (s = V.prototype) && s.render, j = (s = V.contextType) && i[s.__c], L = s ? j ? j.props.value : s.__ : i, (d = u.__c) ? (r.__c = d, 2 & d.__g && (d.__g |= 1)) : (C ? r.__c = d = new V(M, L) : (r.__c = d = new x$1(M, L), d.constructor = V, d.render = K$1), j && j.sub(d), d.state || (d.state = {}), d.__n = i, d.__g |= 8, d.__h = [], d.__k = []), C && (d.__s || (d.__s = d.state), V.getDerivedStateFromProps && (d.__s == d.state && (d.__s = _$1({}, d.__s)), _$1(d.__s, V.getDerivedStateFromProps(M, d.__s)))), k = d.props, b = d.state, d.__v = r, u.__c) { if (M !== k && C && !V.getDerivedStateFromProps && d.componentWillReceiveProps && d.componentWillReceiveProps(M, L), r.__v == u.__v && !(8 & d.__g) || !(4 & d.__g) && d.shouldComponentUpdate && !1 === d.shouldComponentUpdate(M, d.__s, L)) { r.__v != u.__v && (d.props = M, d.state = d.__s, d.__g &= -9), r.__e = u.__e, r.__k = u.__k, r.__k.some(function(n) { n && (n.__ = r); }), y$1.push.apply(d.__h, d.__k), d.__k = [], d.__h.length && e.push(d), l = S(u); break n; } d.componentWillUpdate && d.componentWillUpdate(M, d.__s, L), C && d.componentDidUpdate && d.__h.push(function() { d.componentDidUpdate(k, b, m); }); } else C && !V.getDerivedStateFromProps && d.componentWillMount && d.componentWillMount(), C && d.componentDidMount && d.__h.push(d.componentDidMount); d.context = L, d.props = M, d.__P = t, d.__g &= -5, H = n.__r, q = C ? 25 : 0; do d.__g &= -9, H && H(r), s = d.render(d.props, d.state = d.__s, d.context); while (8 & d.__g && ++q < 25); C && (y$1.push.apply(d.__h, d.__k), d.__k = []), d.state = d.__s, d.getChildContext && (i = _$1({}, i, d.getChildContext())), C && u.__c && d.getSnapshotBeforeUpdate && (m = d.getSnapshotBeforeUpdate(k, b)), A = s && s.type === $$1 && null == s.key ? s.props.children : s, M.__P && (s = l, f = (t = M.__P).namespaceURI, c = o = null, u.props && u.props.__P != t && (u.__k.some(function(n) { n && J$1(n, n); }), u.__k = null), l = u.__k ? S(u, 0) : null), l = I(t, w$2(A) ? A : [A], r, u, i, f, o, e, l, c, a), M.__P && (r.__e = null, l = s), r.__u &= -161, p && p.some(g$1), d.__h.length && e.push(d), 1 & d.__g && (d.__g &= -4); } catch (t) { if (e.length = v, r.__v = null, c || o) if (t && t.then) { if (r.__u |= 128 | c, o) { for (~(T = o.indexOf(l || void 0)) || (T = o.length); (N = o[T - 1]) && 8 == N.nodeType;) T--; for (; T < o.length; T++) if (N = o[T]) if (o[T] = null, O) { if (N == P) break; } else { if (8 != N.nodeType) break; N.data.startsWith("$s") && (P = B$1(O = N)); } } if (!O) { for (; l && 8 == l.nodeType && l.nextSibling;) l = l.nextSibling; O = l; } (s = B$1(O = r.__c.__z || (r.__c.__z = O))) ? (r.__e = O, l = s) : r.__e = l, l = l && l.nextSibling; } else o && o.some(g$1); else r.__e = u.__e; r.__k || (r.__k = u.__k || []), t && t.then || D$1(r), n.__e(t, r, u); } } else l = r.__e = F$1(u.__e, r, u, i, f, o, e, c, a, t); return (s = n.diffed) && s(r), l; } function B$1(n, t) { if (n && 8 == n.nodeType && n.data.startsWith("$s")) for (var r = 1; n = n.nextSibling;) { if (8 == n.nodeType) { if (n.data.startsWith("$s")) r++; else if (n.data.startsWith("/$s") && !--r) return n; } t && t.push(n); } } function D$1(n) { n && (n.__c && (n.__c.__g |= 4), n.__k && n.__k.some(D$1)); } function E$1(t, r, u) { for (var i = 0; i < u.length;) G$1(u[i++], u[i++], u[i++]); n.__c && n.__c(r, t), t.some(function(r) { try { t = r.__h, r.__h = [], t.some(function(n) { n.call(r); }); } catch (t) { n.__e(t, r.__v); } }); } function F$1(t, r, u, i, f, o, e, l, c, a) { var s, h, y, _, k, b, m, M, $ = u.props || p$1, x = r.props, C = r.type; if ("svg" == C ? f = "http://www.w3.org/2000/svg" : "math" == C ? f = "http://www.w3.org/1998/Math/MathML" : f || (f = "http://www.w3.org/1999/xhtml"), o) { for (s = 0; s < o.length; s++) if ((k = o[s]) && (C ? k.localName == C : 3 == k.nodeType)) { t = k, o[s] = null; break; } } if (!t) { if (M = a.ownerDocument || document, !C) return M.createTextNode(x); t = M.createElementNS(f, C, x.is ? x : a), l && (n.__m && n.__m(r, o), l = false), o = null; } if (C) { if (a = "template" == C && t.content || t, o = "textarea" == C && null != x.defaultValue ? null : o && d$1.call(a.childNodes), !l && o) for ($ = {}, s = 0; s < t.attributes.length; s++) $[(k = t.attributes[s]).name] = k.value; for (s in $) k = $[s], "dangerouslySetInnerHTML" == s ? y = k : "children" == s || s in x || "value" == s && "defaultValue" in x || "checked" == s && "defaultChecked" in x || N(t, s, null, k, f); for (s in x) k = x[s], "children" == s ? _ = k : "dangerouslySetInnerHTML" == s ? h = k : "value" == s ? b = k : "checked" == s ? m = k : l && "function" != typeof k || $[s] === k || N(t, s, k, $[s], f); h ? (l || y && (h.__html == y.__html || h.__html == t.innerHTML) || (t.innerHTML = h.__html), r.__k = []) : (y && (t.textContent = ""), ("foreignObject" == C || "http://www.w3.org/1998/Math/MathML" == f && v$1.test(C)) && (f = "http://www.w3.org/1999/xhtml"), I(a, w$2(_) ? _ : [_], r, u, i, f, o, e, o ? o[0] : u.__k && S(u, 0), l, c), o && o.some(g$1)), l && "textarea" != C || (s = "value", "progress" == C && null == b ? t.removeAttribute(s) : null == b || b === t[s] && ("progress" != C || b) || N(t, s, b, $[s], f), s = "checked", null != m && m != t[s] && N(t, s, m, $[s], f)); } else $ === x || l && t.data == x || (t.data = x); return t; } function G$1(t, r, u, i) { try { "function" == typeof t ? r ? r.__x = t(r) || 1 : i && (i = i.__c || i.__e) && (r = i.__x) && (i.__x = null, "function" == typeof r ? r() : t(null)) : t.current = r; } catch (t) { n.__e(t, u); } } function J$1(t, r, u) { var i, f, o, e; if (n.unmount && n.unmount(t), !(i = t.ref) || i.current && i.current != t.__e || G$1(i, null, r, t), i = t.__c) { if (i.componentWillUnmount) try { i.componentWillUnmount(); } catch (t) { n.__e(t, r); } i.__P = i.__n = null; } if (i = t.__k) for (e = 0; e < i.length; e++) i[e] && J$1(i[e], r, "function" != typeof t.type || u && !t.props.__P); !u && (i = t.__c) && (i = i.__z) && (f = B$1(i, o = [])) && (i == t.__e && o.some(g$1), g$1(f), g$1(i)), u || g$1(t.__e), t.__e = t.__c = t.__ = null; } function K$1(n, t, r) { return this.constructor(n, r); } function Q$1(t, r) { var u, i, f, o; n.__ && n.__(t, r), 9 == r.nodeType && (r = r.documentElement), i = (u = t && 32 & t.__u) ? null : r.__k, r.__k = m$1($$1, { children: [t] }), f = [], o = [], z$2(r, r.__k, i || p$1, p$1, r.namespaceURI, i ? null : r.firstChild ? d$1.call(r.childNodes) : null, f, i ? i.__e : r.firstChild, u, o), E$1(f, r.__k, o), r.__k.props.children = null; } function U$1(n) { function t(n) { var r, u; return this.getChildContext || (r = /* @__PURE__ */ new Set(), (u = {})[t.__c] = this, this.getChildContext = function() { return u; }, this.shouldComponentUpdate = function(n) { this.props.value != n.value && r.forEach(function(n) { n.__g |= 4, L(n); }); }, this.sub = function(n) { r.add(n); var t = n.componentWillUnmount; n.componentWillUnmount = function() { r.delete(n), t && t.call(n); }; }), n.children; } return t.__c = "__cC" + s$1++, t.__ = n, t.Provider = (t.Consumer = function(n, t) { return n.children(t); }).contextType = t, t; } function W(n) { return n.children; } function X(n, t) { return m$1(W, { __P: t, children: n }); } n = { __e: function(n, t, r, u) { for (var i, o, e; t = t.__;) if ((i = t.__c) && !(1 & i.__g)) { i.__g |= 4; try { if ((e = (o = i.constructor) && o.getDerivedStateFromError) && i.setState(o.getDerivedStateFromError(n)), i.componentDidCatch && (i.componentDidCatch(n, u || {}), e = 1), e && 8 & i.__g) return void (i.__g |= 2); } catch (t) { n = t; } } throw f$2 = 0, n; } }, t$1 = 0, x$1.prototype.setState = function(n, t) { var r = this.__s; r && r != this.state || (r = this.__s = _$1({}, this.state)), "function" == typeof n && (n = n(_$1({}, r), this.props)), n && (_$1(r, n), this.__v && (t && this.__k.push(t), L(this))); }, x$1.prototype.forceUpdate = function(n) { this.__v && (this.__g |= 4, n && this.__h.push(n), L(this)); }, x$1.prototype.render = $$1, u$2 = [], f$2 = 0, o$2 = function(n, t) { return n.__v.__b - t.__v.__b; }, e$1 = Symbol(), l$1 = /(PointerCapture)$|Capture$/i, c$1 = 0, a$2 = {}, s$1 = 0; var t; var r; var u$1; var i; var o$1 = Object.is; var f$1 = 0; var c = []; var e = []; var a$1 = n; var v$2 = a$1.__b; var l = a$1.__r; var m = a$1.diffed; var h = a$1.__c; var s = a$1.unmount; var p = a$1.__; function y(n, t) { a$1.__h && a$1.__h(r, n, f$1 || t), f$1 = 0; var u = r.__H || (r.__H = { __: [], __h: [] }); return n >= u.__.length && u.__.push({}), u.__[n]; } function d(n) { return f$1 = 1, _(G, n); } function _(n, u, i) { var f = y(t++, 2); if (f.t = n, !f.__c && (f.__ = [G(void 0, u), function(n) { var t = (f.__N || f.__)[0], r = f.t(t, n); o$1(t, r) || (f.__N = [r, f.__[1]], f.__c.setState({})); }], f.__c = r, !r.__f)) { r.__f = true; var c = r.shouldComponentUpdate; r.shouldComponentUpdate = function(n, t, r) { var u = this.__H; if (!u) return true; var i = false, f = this.props != n; if (u.__.some(function(n) { n.__N && (i = true, o$1(n.__[0], n.__N[0]) || (f = true)); }), c) { var e = c.call(this, n, t, r); return i ? e || f : e; } return !i || f; }; } return f.__; } function A(n, u) { var i = y(t++, 3); !a$1.__s && E(i.__H, u) && (i.__P = true, i.__ = n, i.u = u, r.__H.__h.push(i)); } function F(n, u) { var i = y(t++, 4); !a$1.__s && E(i.__H, u) && (i.__P = false, i.__ = n, i.u = u, r.__h.push(i)); } function T(n) { return f$1 = 5, w$1(function() { return { current: n }; }, []); } function w$1(n, r) { var u = y(t++, 7); return E(u.__H, r) && (u.__ = n(), u.__H = r), u.__; } function b(n, t) { return f$1 = 8, w$1(function() { return n; }, t); } function j(n) { var u = r.context[n.__c], i = y(t++, 9); return i.c = n, u ? (i.__ ?? (i.__ = true, u.sub(r)), u.props.value) : n.__; } function P$1() { var n = y(t++, 11); if (!n.__) { for (var u = r.__v; !u.__m && u.__;) u = u.__; var i = u.__m || (u.__m = [0, 0]); n.__ = "P" + i[0] + "-" + i[1]++; } return n.__; } function g() { var n; do { for (; n = e.shift();) try { C(n); } catch (t) { a$1.__e(t, { __: (n = n.__P) && n.__v }); } for (; n = c.shift();) { var t = n.__H; if (n.__P && t) try { t.__h.some(C), t.__h.some(D), t.__h = []; } catch (r) { t.__h = [], a$1.__e(r, n.__v); } } } while (e.length); } a$1.__b = function(n) { r = null, v$2 && v$2(n); }, a$1.__ = function(n, t) { n && t.__k && t.__k.__m && (n.__m = t.__k.__m), p && p(n, t); }, a$1.__r = function(n) { l && l(n), t = 0; var i = (r = n.__c).__H; i && (u$1 == r ? r.__h = [] : (i.__h.some(C), i.__h.some(D), t = 0), i.__h = [], i.__.some(function(n) { n.__N && (n.__ = n.__N), n.u = n.__N = void 0; })), u$1 = r; }, a$1.diffed = function(n) { m && m(n); var t = n.__c; t && t.__H && (t.__H.__h.length && B(c.push(t)), t.__H.__.some(function(n) { n.u && (n.__H = n.u); })), u$1 = r = null; }, a$1.__c = function(n, t) { t.some(function(n) { try { n.__h.some(C), n.__h = n.__h.filter(function(n) { return !n.__ || D(n); }); } catch (t) { n.__h = [function() { throw t; }]; } }), h && h(n, t); }, a$1.unmount = function(n) { s && s(n); var t, r, u = n.__c; u && u.__H && (u.__H.__.some(function(u) { try { if (u.__P && u.__c) { if (void 0 === r) { for (r = n.__; r && (!r.__c || !r.__c.__P);) r = r.__; r = r && r.__c; } u.__P = r, B(e.push(u)); } else C(u); } catch (n) { t = n; } }), u.__H = void 0, t && a$1.__e(t, u.__v)); }; var k = "function" == typeof requestAnimationFrame; function z$1(n) { var t, r = function() { clearTimeout(u), k && cancelAnimationFrame(t), setTimeout(n); }, u = setTimeout(r, 35); k && (t = requestAnimationFrame(r)); } function B(n) { 1 != n && i == a$1.requestAnimationFrame || ((i = a$1.requestAnimationFrame) || z$1)(g); } function C(n) { var t = r, u = n.__c; "function" == typeof u && (n.__c = void 0, u()), r = t; } function D(n) { var t = r; n.__c = n.__(), r = t; } function E(n, t) { return !n || n.length != t.length || t.some(function(t, r) { return !o$1(t, n[r]); }); } function G(n, t) { return "function" == typeof t ? t(n) : t; } /** A page may make the kit's controls larger by setting these on its root. */ var KIT_CONTROL_HEIGHT_VAR = exports("at","--rdw-control-h"); var KIT_CONTROL_FONT_VAR = exports("au","--rdw-control-font"); var KIT_CONTROL_FONT_PX = 12; /** Height of a button, a field, a switch of options; 28px unless the page says otherwise. */ var KIT_CONTROL_HEIGHT = `var(${KIT_CONTROL_HEIGHT_VAR}, ${String(28)}px)`; /** Text size inside those controls; 12px unless the page says otherwise. */ var KIT_CONTROL_FONT = `var(${KIT_CONTROL_FONT_VAR}, ${String(KIT_CONTROL_FONT_PX)}px)`; var KIT_FOCUS_CSS = exports("bi",` .rdw-kit-focusable:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } `); var f = Symbol.for("pv"); var o = 0; function a(t, e, n$6, u, a, i) { e || (e = {}); var c, l, p = e; if ("ref" in p && "function" != typeof t) for (l in p = {}, e) "ref" == l ? c = e[l] : p[l] = e[l]; var s = { type: t, props: p, key: n$6, ref: c, __k: null, __: null, __b: 0, __e: null, __c: null, constructor: f, __v: --o, __i: -1, __u: 0 }; return n.vnode && n.vnode(s), s; } var KEY_ARROW_DOWN = "ArrowDown"; var KEY_ARROW_UP = "ArrowUp"; var KEY_ENTER$1 = "Enter"; var KEY_ESCAPE$4 = "Escape"; var NO_ACTIVE_INDEX = -1; var AUTOCOMPLETE_FIELD_CSS = ` ${KIT_FOCUS_CSS} .rdw-ac { position: relative; display: flex; flex-direction: column; gap: 4px; min-width: 0; } .rdw-ac__dot { display: inline-block; width: 7px; height: 7px; margin-right: 6px; border-radius: 50%; vertical-align: middle; } .rdw-ac__dot[data-kind="artist"] { background: var(--rdw-tag-artist); } .rdw-ac__dot[data-kind="character"] { background: var(--rdw-tag-character); } .rdw-ac__dot[data-kind="copyright"] { background: var(--rdw-tag-copyright); } .rdw-ac__dot[data-kind="metadata"] { background: var(--rdw-tag-metadata); } .rdw-ac__label { font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); } .rdw-ac__input { box-sizing: border-box; min-height: ${KIT_CONTROL_HEIGHT}; height: ${KIT_CONTROL_HEIGHT}; width: 100%; padding: 0 8px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); font: inherit; font-size: ${KIT_CONTROL_FONT}; } /* Site CSS paints focused text inputs light yellow; keep the theme colours. */ input.rdw-ac__input.rdw-kit-focusable:focus { background: var(--rdw-surface); color: var(--rdw-text); } .rdw-ac__input::placeholder { color: var(--rdw-muted); } .rdw-ac__input:disabled { opacity: 0.55; cursor: not-allowed; } .rdw-ac__list { position: absolute; z-index: 20; top: calc(100% + 4px); left: 0; right: 0; margin: 0; padding: 4px; list-style: none; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); box-shadow: var(--rdw-shadow-2); max-height: 220px; overflow: auto; } .rdw-ac__option { min-height: ${KIT_CONTROL_HEIGHT}; display: flex; align-items: center; padding: 0 8px; border-radius: var(--rdw-radius-s); font-size: ${KIT_CONTROL_FONT}; color: var(--rdw-text); cursor: pointer; } .rdw-ac__option[aria-selected="true"], .rdw-ac__option:hover { background: var(--rdw-surface-2); } `; function AutocompleteField(props) { const autoId = P$1(); const listId = P$1(); const inputId = props.id ?? autoId; const rootRef = T(null); const [open, setOpen] = d(false); const [activeIndex, setActiveIndex] = d(NO_ACTIVE_INDEX); const suggestions = props.suggestions; const hasSuggestions = suggestions.length > 0; const listOpen = open && hasSuggestions && props.disabled !== true; A(() => { setActiveIndex(NO_ACTIVE_INDEX); if (hasSuggestions) setOpen(true); else setOpen(false); }, [suggestions, hasSuggestions]); A(() => { if (!listOpen) return; const onPointerDown = (event) => { const root = rootRef.current; if (root === null) return; if (!event.composedPath().includes(root)) { setOpen(false); setActiveIndex(NO_ACTIVE_INDEX); } }; document.addEventListener("mousedown", onPointerDown); return () => { document.removeEventListener("mousedown", onPointerDown); }; }, [listOpen]); const selectOption = (option) => { if (props.replaceOnSelect !== false) props.onChange(option.value); props.onSelect?.(option); setOpen(false); setActiveIndex(NO_ACTIVE_INDEX); }; const className = ["rdw-ac", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); const activeOption = activeIndex >= 0 && activeIndex < suggestions.length ? suggestions[activeIndex] : void 0; return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: AUTOCOMPLETE_FIELD_CSS }), /* @__PURE__ */ a("div", { className, ref: rootRef, children: [ props.label !== void 0 ? /* @__PURE__ */ a("label", { className: "rdw-ac__label", htmlFor: inputId, children: props.label }) : null, /* @__PURE__ */ a("input", { id: inputId, className: "rdw-ac__input rdw-kit-focusable", type: "text", role: "combobox", "aria-autocomplete": "list", "aria-expanded": listOpen, "aria-controls": listId, "aria-activedescendant": activeOption !== void 0 ? `${listId}-opt-${String(activeIndex)}` : void 0, value: props.value, placeholder: props.placeholder, disabled: props.disabled, "aria-label": props["aria-label"] ?? props.label, autoComplete: "off", onInput: (event) => { props.onChange(event.currentTarget.value); }, onFocus: () => { if (hasSuggestions) setOpen(true); }, onKeyDown: (event) => { if (event.key === KEY_ESCAPE$4) { if (listOpen) { event.preventDefault(); setOpen(false); setActiveIndex(NO_ACTIVE_INDEX); } return; } if (event.key === KEY_ARROW_DOWN) { if (!hasSuggestions) return; event.preventDefault(); setOpen(true); setActiveIndex((current) => { if (current < 0) return 0; return Math.min(current + 1, suggestions.length - 1); }); return; } if (event.key === KEY_ARROW_UP) { if (!listOpen) return; event.preventDefault(); setActiveIndex((current) => { if (current <= 0) return NO_ACTIVE_INDEX; return current - 1; }); return; } if (event.key === KEY_ENTER$1) { if (listOpen && activeOption !== void 0) { event.preventDefault(); selectOption(activeOption); } } } }), listOpen ? /* @__PURE__ */ a("ul", { className: "rdw-ac__list", role: "listbox", id: listId, tabIndex: -1, children: suggestions.map((option, index) => /* @__PURE__ */ a("li", { id: `${listId}-opt-${String(index)}`, role: "option", className: "rdw-ac__option rdw-kit-focusable", "aria-selected": index === activeIndex, onMouseDown: (event) => { event.preventDefault(); }, onClick: () => { selectOption(option); }, children: [option.type === "artist" || option.type === "character" || option.type === "copyright" || option.type === "metadata" ? /* @__PURE__ */ a("span", { className: "rdw-ac__dot", "data-kind": option.type, "aria-hidden": "true" }) : null, option.label] }, `${option.value}:${option.type ?? ""}:${option.label}`)) }) : null ] })] }); } var BUTTON_CSS = ` ${KIT_FOCUS_CSS} .rdw-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; box-sizing: border-box; min-height: ${KIT_CONTROL_HEIGHT}; border-radius: var(--rdw-radius-m); font: inherit; font-size: ${KIT_CONTROL_FONT}; font-weight: 600; cursor: pointer; border: 1px solid transparent; padding: 0 12px; color: var(--rdw-text); background: var(--rdw-surface); } .rdw-btn--s { min-height: ${KIT_CONTROL_HEIGHT}; padding: 0 10px; font-size: ${KIT_CONTROL_FONT}; } .rdw-btn--m { min-height: ${KIT_CONTROL_HEIGHT}; padding: 0 12px; } .rdw-btn--primary { background: var(--rdw-accent); border-color: var(--rdw-accent); color: var(--rdw-surface); } .rdw-btn--secondary { background: var(--rdw-surface); border-color: var(--rdw-border); color: var(--rdw-text); } .rdw-btn[aria-pressed="true"] { background: var(--rdw-accent-soft); border-color: var(--rdw-accent); color: var(--rdw-text); } .rdw-btn--ghost { background: transparent; border-color: transparent; color: var(--rdw-accent); } .rdw-btn--danger { background: var(--rdw-danger); border-color: var(--rdw-danger); color: var(--rdw-surface); } .rdw-btn--danger-quiet { background: var(--rdw-surface); border-color: var(--rdw-danger); color: var(--rdw-danger); } .rdw-btn--danger-quiet:hover:not(:disabled) { background: var(--rdw-danger-soft); } .rdw-btn:disabled, .rdw-btn[aria-busy="true"] { opacity: 0.55; cursor: not-allowed; } /* A main button that cannot be pressed is grey: dimmed blue read as pressed. */ .rdw-btn--primary:disabled:not([aria-busy="true"]) { background: var(--rdw-surface-2); border-color: var(--rdw-border); color: var(--rdw-muted); opacity: 1; } .rdw-btn__spinner { width: 12px; height: 12px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: rdw-btn-spin 0.7s linear infinite; } @keyframes rdw-btn-spin { to { transform: rotate(360deg); } } `; function Button(props) { const variant = props.variant ?? "secondary"; const size = props.size ?? "m"; const loading = props.loading === true; const disabled = props.disabled === true || loading; const className = [ "rdw-btn", "rdw-kit-focusable", `rdw-btn--${variant}`, `rdw-btn--${size}`, props.className ].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: BUTTON_CSS }), /* @__PURE__ */ a("button", { type: props.type ?? "button", className, disabled, "aria-busy": loading ? true : void 0, "aria-label": props["aria-label"], title: props.title, "aria-pressed": props.pressed, ...props.buttonRef === void 0 ? {} : { ref: props.buttonRef }, onClick: props.onClick, children: [loading ? /* @__PURE__ */ a("span", { className: "rdw-btn__spinner", "aria-hidden": "true" }) : null, props.children] })] }); } var CARD_CSS$1 = ` .rdw-card { background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-1); } `; function Card(props) { const Tag = props.as ?? "div"; const className = ["rdw-card", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: CARD_CSS$1 }), /* @__PURE__ */ a(Tag, { className, children: props.children })] }); } var DEFAULT_SIZE = 16; function baseProps(size, className, title) { const props = { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": 2, "stroke-linecap": "round", "stroke-linejoin": "round", "aria-hidden": title === void 0 ? true : void 0, role: title === void 0 ? void 0 : "img" }; if (className !== void 0) props.className = className; if (title !== void 0) props["aria-label"] = title; return props; } function IconStar(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("polygon", { points: "12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" })] }); } function IconStarFilled(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), fill: "currentColor", stroke: "none", children: [props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("polygon", { points: "12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2" })] }); } function IconPlus(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("line", { x1: "12", y1: "5", x2: "12", y2: "19" }), /* @__PURE__ */ a("line", { x1: "5", y1: "12", x2: "19", y2: "12" }) ] }); } function IconCheck(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("polyline", { points: "20 6 9 17 4 12" })] }); } function IconX(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("line", { x1: "18", y1: "6", x2: "6", y2: "18" }), /* @__PURE__ */ a("line", { x1: "6", y1: "6", x2: "18", y2: "18" }) ] }); } function IconChevronDown(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("polyline", { points: "6 9 12 15 18 9" })] }); } function IconArrowUp(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("line", { x1: "12", y1: "19", x2: "12", y2: "5" }), /* @__PURE__ */ a("polyline", { points: "5 12 12 5 19 12" }) ] }); } function IconExternalLink(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" }), /* @__PURE__ */ a("polyline", { points: "15 3 21 3 21 9" }), /* @__PURE__ */ a("line", { x1: "10", y1: "14", x2: "21", y2: "3" }) ] }); } function IconDroplet(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M12 2.69l5.66 5.66a8 8 0 1 1-11.31 0z" })] }); } function IconPencil(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M12 20h9" }), /* @__PURE__ */ a("path", { d: "M16.5 3.5a2.12 2.12 0 0 1 3 3L7 19l-4 1 1-4Z" }) ] }); } function IconFlag(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z" }), /* @__PURE__ */ a("line", { x1: "4", y1: "22", x2: "4", y2: "15" }) ] }); } function IconNote(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" }), /* @__PURE__ */ a("polyline", { points: "14 2 14 8 20 8" }), /* @__PURE__ */ a("line", { x1: "8", y1: "13", x2: "16", y2: "13" }), /* @__PURE__ */ a("line", { x1: "8", y1: "17", x2: "12", y2: "17" }) ] }); } function IconSearch(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("circle", { cx: "11", cy: "11", r: "8" }), /* @__PURE__ */ a("line", { x1: "21", y1: "21", x2: "16.65", y2: "16.65" }) ] }); } function IconTrash(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("polyline", { points: "3 6 5 6 21 6" }), /* @__PURE__ */ a("path", { d: "M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" }) ] }); } function IconImage(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }), /* @__PURE__ */ a("circle", { cx: "8.5", cy: "8.5", r: "1.5" }), /* @__PURE__ */ a("polyline", { points: "21 15 16 10 5 21" }) ] }); } function IconDice(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("rect", { x: "3", y: "3", width: "18", height: "18", rx: "2", ry: "2" }), /* @__PURE__ */ a("path", { d: "M16 8h.01" }), /* @__PURE__ */ a("path", { d: "M12 12h.01" }), /* @__PURE__ */ a("path", { d: "M8 16h.01" }) ] }); } function IconDots(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("circle", { cx: "12", cy: "12", r: "1" }), /* @__PURE__ */ a("circle", { cx: "19", cy: "12", r: "1" }), /* @__PURE__ */ a("circle", { cx: "5", cy: "12", r: "1" }) ] }); } function IconHelp(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("circle", { cx: "12", cy: "12", r: "10" }), /* @__PURE__ */ a("path", { d: "M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" }), /* @__PURE__ */ a("path", { d: "M12 17h.01" }) ] }); } function IconDownload(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" }), /* @__PURE__ */ a("polyline", { points: "7 10 12 15 17 10" }), /* @__PURE__ */ a("line", { x1: "12", y1: "15", x2: "12", y2: "3" }) ] }); } function IconRefresh(props) { return /* @__PURE__ */ a("svg", { ...baseProps(props.size ?? DEFAULT_SIZE, props.className, props.title), children: [ props.title !== void 0 ? /* @__PURE__ */ a("title", { children: props.title }) : null, /* @__PURE__ */ a("path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8" }), /* @__PURE__ */ a("path", { d: "M21 3v5h-5" }), /* @__PURE__ */ a("path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16" }), /* @__PURE__ */ a("path", { d: "M8 16H3v5" }) ] }); } var CHIP_CSS = ` ${KIT_FOCUS_CSS} .rdw-chip { display: inline-flex; align-items: center; gap: 5px; min-height: 24px; height: 24px; padding: 0 4px 0 8px; border-radius: 12px; background: var(--rdw-surface-2); border: 1px solid var(--rdw-border); font-size: ${KIT_CONTROL_FONT}; color: var(--rdw-text); max-width: 100%; white-space: nowrap; } .rdw-chip__dot { width: 7px; height: 7px; border-radius: 50%; background: var(--rdw-muted); flex: none; } .rdw-chip--artist .rdw-chip__dot { background: var(--rdw-tag-artist); } .rdw-chip--character .rdw-chip__dot { background: var(--rdw-tag-character); } .rdw-chip--copyright .rdw-chip__dot { background: var(--rdw-tag-copyright); } .rdw-chip--metadata .rdw-chip__dot { background: var(--rdw-tag-metadata); } .rdw-chip--exclude { background: var(--rdw-danger-soft); border-color: var(--rdw-danger); color: var(--rdw-danger); text-decoration: line-through; } .rdw-chip--group { background: var(--rdw-accent-soft); border-color: var(--rdw-accent); color: var(--rdw-accent); font-weight: 600; } .rdw-chip__remove { box-sizing: border-box; width: ${KIT_CONTROL_HEIGHT}; height: ${KIT_CONTROL_HEIGHT}; min-width: ${KIT_CONTROL_HEIGHT}; min-height: ${KIT_CONTROL_HEIGHT}; margin: -2px -2px -2px 0; border: 0; border-radius: 50%; background: transparent; color: var(--rdw-muted); display: grid; place-items: center; cursor: pointer; padding: 0; } .rdw-chip__remove:hover { background: var(--rdw-surface); } `; function Chip(props) { const variant = props.variant ?? "dot"; const kind = props.kind ?? "default"; const className = [ "rdw-chip", `rdw-chip--${variant}`, kind !== "default" ? `rdw-chip--${kind}` : void 0, props.className ].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: CHIP_CSS }), /* @__PURE__ */ a("span", { className, children: [ variant === "dot" ? /* @__PURE__ */ a("i", { className: "rdw-chip__dot", "aria-hidden": "true" }) : null, /* @__PURE__ */ a("span", { children: props.label }), props.onRemove !== void 0 ? /* @__PURE__ */ a("button", { type: "button", className: "rdw-chip__remove rdw-kit-focusable", "aria-label": `Remove ${props.label}`, onClick: props.onRemove, children: /* @__PURE__ */ a(IconX, { size: 12 }) }) : null ] })] }); } var w = Object.assign; var x = /^(-|f[lo].*[^se]$|g.{5,}[^ps]$|z|o[pr]|(W.{5})?[lL]i.*(t|mp)$|an|(bo|s).{4}Im|sca|m.{6}[ds]|ta|c.*[st]$|wido|ini|asp|fill|st)/; function U(n, t) { var e = X(n, t); return e.containerInfo = t, e; } var P = Symbol.for("react.element"); var $ = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(?!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/; var z = /[A-Z0-9]/g; var H = typeof document < "u"; var Y = function(n) { return /fil|che|rad/.test(n); }; x$1.prototype.isReactComponent = true, [ "componentWillMount", "componentWillReceiveProps", "componentWillUpdate" ].forEach(function(n) { Object.defineProperty(x$1.prototype, n, { configurable: true, get: function() { return this["UNSAFE_" + n]; }, set: function(t) { Object.defineProperty(this, n, { configurable: true, writable: true, value: t }); } }); }); var J = n.event; n.event = function(n) { return J && (n = J(n)), n.persist = function() {}, n.isPropagationStopped = function() { return this.cancelBubble; }, n.isDefaultPrevented = function() { return this.defaultPrevented; }, n.nativeEvent = n; }; var K = { configurable: true, get: function() { return this.class; } }; var Q = n.vnode; n.vnode = function(t) { if ("string" == typeof t.type) (function(t) { var e = t.props, r = t.type, u = {}, i = -1 == r.indexOf("-"); for (var o in e) { var f = e[o]; if (!("value" == o && "defaultValue" in e && null == f || H && "children" == o && "noscript" == r || "class" == o || "className" == o)) { if ("style" == o && f && f.constructor == Object) { var l = void 0; for (var a in f) "number" != typeof f[a] || x.test(a) || (l || (l = f = w({}, f)), f[a] += "px"); } else if ("defaultValue" == o && "value" in e && null == e.value) o = "value"; else if ("download" == o && true === f) f = ""; else if ("translate" == o && "no" === f) f = false; else if ("o" == o[0] && "n" == o[1]) { var c = o.toLowerCase(); "ondoubleclick" == c ? o = "ondblclick" : "onchange" != c || "input" != r && "textarea" != r || Y(e.type) ? "onfocus" == c ? o = "onfocusin" : "onblur" == c && (o = "onfocusout") : c = o = "oninput", "oninput" == c && u[o = c] && (o = "oninputCapture"); } else i && $.test(o) ? o = o.replace(z, "-$&").toLowerCase() : null === f && (f = void 0); u[o] = f; } } if ("select" == r) { var s = null != u.defaultValue ? u.defaultValue : u.multiple && Array.isArray(u.value) ? u.value : null; null != s && (u.value = O(e.children).forEach(function(n) { n.props.selected = u.multiple ? -1 != s.indexOf(n.props.value) : s == n.props.value; })); } e.class && !e.className ? (u.class = e.class, Object.defineProperty(u, "className", K)) : e.className && (u.class = u.className = e.className), t.props = u; })(t); else if ("function" == typeof t.type && ("ref" in t.props && "prototype" in t.type && t.type.prototype.render && (t.ref = t.props.ref, delete t.props.ref), t.type.defaultProps)) { var e = w({}, t.props); for (var r in t.type.defaultProps) void 0 === e[r] && (e[r] = t.type.defaultProps[r]); t.props = e; } t.ref && !("ref" in t.props) && Object.defineProperty(t.props, "ref", { value: t.ref, configurable: true, writable: true }), t.$$typeof = P, Q && Q(t); }; /** * Where the things that open over the page are drawn: a dialog, the list of a * select. On the site's pages they are drawn in , never where the * component stands. The blocks the script adds there are held while the page * scrolls (the sidebar of Posts, the column of Favorites, the header): a held * block is a layer of its own and clips what does not fit, so a dialog drawn * inside it lies under the thumbnails that come after it, however high its * z-index, and a list is cut at the block's edge. The own pages live in a * shadow root with their own styles, and say so with this context: there * everything stays where it stands. */ var OverlayInPlace = exports("ao",U$1(false)); var TEXT_FIELD_CSS = ` ${KIT_FOCUS_CSS} .rdw-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; } .rdw-field__label { font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); } .rdw-field__input { box-sizing: border-box; min-height: ${KIT_CONTROL_HEIGHT}; height: ${KIT_CONTROL_HEIGHT}; width: 100%; padding: 0 8px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); font: inherit; font-size: ${KIT_CONTROL_FONT}; } /* Site CSS paints focused text inputs light yellow; keep the theme colours. */ input.rdw-field__input.rdw-kit-focusable:focus { background: var(--rdw-surface); color: var(--rdw-text); } /* A value filled in by the browser keeps the theme's colours too. */ .rdw-field__input:-webkit-autofill, .rdw-field__input:-webkit-autofill:hover, .rdw-field__input:-webkit-autofill:focus { -webkit-text-fill-color: var(--rdw-text); caret-color: var(--rdw-text); box-shadow: 0 0 0 1000px var(--rdw-surface) inset; } /* The ring of a field lies on its border and does not stand off it. */ .rdw-field__input.rdw-kit-focusable:focus-visible { outline-offset: -1px; border-color: var(--rdw-accent); } .rdw-field__input::placeholder { color: var(--rdw-muted); } .rdw-field__input:disabled { opacity: 0.55; cursor: not-allowed; } `; function TextField(props) { const autoId = P$1(); const inputId = props.id ?? autoId; const className = ["rdw-field", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: TEXT_FIELD_CSS }), /* @__PURE__ */ a("div", { className, children: [props.label !== void 0 ? /* @__PURE__ */ a("label", { className: "rdw-field__label", htmlFor: inputId, children: props.label }) : null, props.type === "password" ? /* @__PURE__ */ a("input", { id: inputId, className: "rdw-field__input rdw-kit-focusable", type: "password", value: props.value, placeholder: props.placeholder, disabled: props.disabled, "aria-label": props["aria-label"] ?? props.label, onInput: (event) => { props.onChange(event.currentTarget.value); } }) : /* @__PURE__ */ a("input", { id: inputId, className: "rdw-field__input rdw-kit-focusable", type: "text", value: props.value, placeholder: props.placeholder, disabled: props.disabled, "aria-label": props["aria-label"] ?? props.label, ...props.inputAttrs, ...props.inputRef === void 0 ? {} : { ref: props.inputRef }, onInput: (event) => { props.onChange(event.currentTarget.value); } })] })] }); } var DIALOG_VARIANT_CONFIRM$1 = "confirm"; var DIALOG_VARIANT_FIELDS$1 = "fields"; var DIALOG_FIELD_NAME = "name"; var DIALOG_FIELD_QUERY = "query"; var DEFAULT_NAME_LABEL = "Name"; var DEFAULT_QUERY_LABEL = "Query"; var DEFAULT_CONFIRM_TONE = "primary"; var KEY_ESCAPE$3 = "Escape"; var ROLE_COMBOBOX = "combobox"; var ARIA_TRUE$1 = "true"; var KEY_TAB$1 = "Tab"; var EVENT_KEYDOWN$3 = "keydown"; var EVENT_MOUSEDOWN$1 = "mousedown"; var DIALOG_Z_INDEX = 40; var DIALOG_MAX_WIDTH_PX = 360; var DIALOG_BACKDROP_PADDING_PX = 16; var DIALOG_BACKDROP_ALPHA = .45; var DIALOG_PANEL_PADDING_PX = 16; var DIALOG_PANEL_GAP_PX = 12; var DIALOG_FIELDS_GAP_PX = 8; var DIALOG_ACTIONS_GAP_PX = 8; var FOCUSABLE_SELECTOR = [ "a[href]", "button:not([disabled])", "textarea:not([disabled])", "input:not([disabled])", "select:not([disabled])", "[tabindex]:not([tabindex=\"-1\"])" ].join(", "); var DIALOG_CSS = ` ${KIT_FOCUS_CSS} .rdw-dialog-backdrop { position: fixed; inset: 0; z-index: ${String(DIALOG_Z_INDEX)}; display: flex; align-items: center; justify-content: center; box-sizing: border-box; padding: ${String(DIALOG_BACKDROP_PADDING_PX)}px; background: rgba(0, 0, 0, ${String(DIALOG_BACKDROP_ALPHA)}); } .rdw-dialog { box-sizing: border-box; width: 100%; max-width: ${String(DIALOG_MAX_WIDTH_PX)}px; display: grid; gap: ${String(DIALOG_PANEL_GAP_PX)}px; padding: ${String(DIALOG_PANEL_PADDING_PX)}px; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-2); color: var(--rdw-text); font: 12.5px/1.4 var(--rdw-font); } .rdw-dialog__title { margin: 0; font-size: 13px; font-weight: 600; color: var(--rdw-text); } .rdw-dialog__message { margin: 0; } .rdw-dialog__fields { display: grid; gap: ${String(DIALOG_FIELDS_GAP_PX)}px; margin: 0; } .rdw-dialog__actions { display: flex; justify-content: flex-end; gap: ${String(DIALOG_ACTIONS_GAP_PX)}px; } `; function listFocusable(root) { const nodes = root.querySelectorAll(FOCUSABLE_SELECTOR); const result = []; for (const node of nodes) { if (!(node instanceof HTMLElement)) continue; if (node.closest("[hidden]") !== null) continue; result.push(node); } return result; } function pathIncludesNode$1(path, node) { if (node === null) return false; for (const entry of path) if (entry === node) return true; return false; } function renderDialogBody(props) { if (props.variant === DIALOG_VARIANT_CONFIRM$1) { const tone = props.confirmTone ?? DEFAULT_CONFIRM_TONE; return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("p", { className: "rdw-dialog__message", children: props.message }), /* @__PURE__ */ a("div", { className: "rdw-dialog__actions", children: [/* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: props.onClose, children: props.cancelLabel }), /* @__PURE__ */ a(Button, { variant: tone, size: "s", onClick: props.onConfirm, children: props.confirmLabel })] })] }); } if (props.variant === DIALOG_VARIANT_FIELDS$1) { const nameLabel = props.nameLabel ?? DEFAULT_NAME_LABEL; const queryLabel = props.queryLabel ?? DEFAULT_QUERY_LABEL; const onQueryChange = (query) => { props.onFieldsChange({ name: props.fields.name, query }); }; return /* @__PURE__ */ a("form", { className: "rdw-dialog__fields", onSubmit: (event) => { event.preventDefault(); props.onSubmit(); }, children: [ props.only !== DIALOG_FIELD_QUERY ? /* @__PURE__ */ a(TextField, { label: nameLabel, value: props.fields.name, onChange: (name) => { props.onFieldsChange({ name, query: props.fields.query }); } }) : null, props.only === DIALOG_FIELD_NAME ? null : props.renderQueryField !== void 0 ? props.renderQueryField({ label: queryLabel, value: props.fields.query, onChange: onQueryChange }) : /* @__PURE__ */ a(TextField, { label: queryLabel, value: props.fields.query, onChange: onQueryChange }), /* @__PURE__ */ a("div", { className: "rdw-dialog__actions", children: [/* @__PURE__ */ a(Button, { variant: "secondary", size: "s", type: "button", onClick: props.onClose, children: props.cancelLabel }), /* @__PURE__ */ a(Button, { variant: "primary", size: "s", type: "submit", children: props.submitLabel })] }) ] }); } return /* @__PURE__ */ a($$1, { children: props.children }); } function isOpenCombobox(event) { const origin = event.composedPath()[0]; return origin instanceof Element && origin.getAttribute("role") === ROLE_COMBOBOX && origin.getAttribute("aria-expanded") === ARIA_TRUE$1; } function Dialog(props) { const panelRef = T(null); const wasOpenRef = T(false); const restoreFocusRef = T(null); const titleId = P$1(); const hasTitle = props.title !== void 0 && props.title.length > 0; const inPlace = j(OverlayInPlace); A(() => { if (!props.open) { if (wasOpenRef.current) { wasOpenRef.current = false; const restore = restoreFocusRef.current; restoreFocusRef.current = null; if (restore !== null && typeof restore.focus === "function") restore.focus(); } return; } if (!wasOpenRef.current) { const active = document.activeElement; restoreFocusRef.current = active instanceof HTMLElement ? active : null; wasOpenRef.current = true; } const panel = panelRef.current; if (panel !== null) { const initial = props.initialFocusRef?.current ?? null; if (initial !== null && typeof initial.focus === "function") initial.focus(); else { const first = listFocusable(panel)[0]; if (first !== void 0) first.focus(); else panel.focus(); } } const onKeyDown = (event) => { if (event.key === KEY_ESCAPE$3) { if (isOpenCombobox(event)) return; event.preventDefault(); event.stopPropagation(); props.onClose(); return; } if (event.key !== KEY_TAB$1) return; const currentPanel = panelRef.current; if (currentPanel === null) return; const focusable = listFocusable(currentPanel); if (focusable.length === 0) { event.preventDefault(); currentPanel.focus(); return; } const first = focusable[0]; const last = focusable[focusable.length - 1]; if (first === void 0 || last === void 0) return; const active = document.activeElement; if (event.shiftKey) { if (active === first || !currentPanel.contains(active)) { event.preventDefault(); last.focus(); } return; } if (active === last) { event.preventDefault(); first.focus(); } }; const onPointerDown = (event) => { const currentPanel = panelRef.current; if (currentPanel === null) return; if (pathIncludesNode$1(event.composedPath(), currentPanel)) return; props.onClose(); }; document.addEventListener(EVENT_KEYDOWN$3, onKeyDown, true); document.addEventListener(EVENT_MOUSEDOWN$1, onPointerDown, true); return () => { document.removeEventListener(EVENT_KEYDOWN$3, onKeyDown, true); document.removeEventListener(EVENT_MOUSEDOWN$1, onPointerDown, true); }; }, [ props.open, props.onClose, props.initialFocusRef ]); if (!props.open) return null; const className = ["rdw-dialog", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); const body = /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: DIALOG_CSS }), /* @__PURE__ */ a("div", { className: "rdw-dialog-backdrop", children: /* @__PURE__ */ a("div", { ref: panelRef, className, role: "dialog", "aria-modal": "true", "aria-label": hasTitle ? void 0 : props["aria-label"], "aria-labelledby": hasTitle ? titleId : void 0, tabIndex: -1, children: [hasTitle ? /* @__PURE__ */ a("h2", { id: titleId, className: "rdw-dialog__title", children: props.title }) : null, renderDialogBody(props)] }) })] }); return inPlace ? body : U(body, document.body); } var EMPTY_STATE_CSS = ` .rdw-empty { display: grid; gap: 6px; justify-items: start; padding: 16px 8px; color: var(--rdw-muted); font: 12.5px/1.4 var(--rdw-font); } .rdw-empty__title { margin: 0; font-size: 13px; font-weight: 600; color: var(--rdw-text); } .rdw-empty__desc { margin: 0; } `; function EmptyState(props) { const className = ["rdw-empty", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: EMPTY_STATE_CSS }), /* @__PURE__ */ a("div", { className, role: "status", children: [ /* @__PURE__ */ a("p", { className: "rdw-empty__title", children: props.title }), props.description !== void 0 ? /* @__PURE__ */ a("p", { className: "rdw-empty__desc", children: props.description }) : null, props.action ] })] }); } var ICON_BUTTON_CSS = ` ${KIT_FOCUS_CSS} .rdw-icon-btn { box-sizing: border-box; display: inline-grid; place-items: center; min-width: ${KIT_CONTROL_HEIGHT}; min-height: ${KIT_CONTROL_HEIGHT}; width: ${KIT_CONTROL_HEIGHT}; height: ${KIT_CONTROL_HEIGHT}; padding: 0; border-radius: var(--rdw-radius-m); border: 1px solid var(--rdw-border); background: var(--rdw-surface); color: var(--rdw-text); cursor: pointer; } .rdw-icon-btn[aria-pressed="true"] { background: var(--rdw-accent-soft); border-color: var(--rdw-accent); color: var(--rdw-accent); } .rdw-icon-btn:disabled { opacity: 0.55; cursor: not-allowed; } `; function IconButton(props) { const className = [ "rdw-icon-btn", "rdw-kit-focusable", props.className ].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: ICON_BUTTON_CSS }), /* @__PURE__ */ a("button", { type: "button", className, "aria-label": props.label, title: props.label, "aria-pressed": props.pressed, "aria-haspopup": props.menuOpen === void 0 ? void 0 : "menu", "aria-expanded": props.menuOpen, ...props.buttonRef === void 0 ? {} : { ref: props.buttonRef }, disabled: props.disabled, onClick: props.onClick, children: props.children })] }); } var NUMBER_FIELD_CSS = ` ${KIT_FOCUS_CSS} .rdw-num { display: flex; flex-direction: column; gap: 4px; min-width: 0; } .rdw-num__label { font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); } .rdw-num__input { box-sizing: border-box; min-height: ${KIT_CONTROL_HEIGHT}; height: ${KIT_CONTROL_HEIGHT}; width: 100%; padding: 0 8px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); font: inherit; font-size: ${KIT_CONTROL_FONT}; } .rdw-num__input:disabled { opacity: 0.55; cursor: not-allowed; } /* The browser's own arrows are white boxes on a dark field; the arrow keys still change the number. */ .rdw-num__input::-webkit-inner-spin-button, .rdw-num__input::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; } .rdw-num__input { -moz-appearance: textfield; appearance: textfield; } /* The ring of a field lies on its border and does not stand off it. */ .rdw-num__input.rdw-kit-focusable:focus-visible { outline-offset: -1px; border-color: var(--rdw-accent); } `; function NumberField(props) { const autoId = P$1(); const inputId = props.id ?? autoId; const className = ["rdw-num", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: NUMBER_FIELD_CSS }), /* @__PURE__ */ a("div", { className, children: [props.label !== void 0 ? /* @__PURE__ */ a("label", { className: "rdw-num__label", htmlFor: inputId, children: props.label }) : null, /* @__PURE__ */ a("input", { id: inputId, className: "rdw-num__input rdw-kit-focusable", type: "number", value: props.value ?? "", min: props.min, max: props.max, step: props.step, placeholder: props.placeholder, disabled: props.disabled, "aria-label": props.label, onInput: (event) => { const raw = event.currentTarget.value; if (raw.trim() === "") { props.onChange(null); return; } const next = Number(raw); props.onChange(Number.isFinite(next) ? next : null); } })] })] }); } var KEY_ESCAPE$2 = "Escape"; var EVENT_KEYDOWN$2 = "keydown"; var EVENT_MOUSEDOWN$2 = "mousedown"; var EVENT_SCROLL$1 = "scroll"; var EVENT_RESIZE$1 = "resize"; var POPOVER_FIXED_CLASS = "rdw-popover--fixed"; /** Above the header kept at the top, the post panel and the dialogs. */ var POPOVER_FIXED_Z_INDEX = 120; var POPOVER_ANCHOR_GAP_PX = 4; var POPOVER_CSS = ` ${KIT_FOCUS_CSS} .rdw-popover { position: absolute; z-index: 30; min-width: 180px; padding: 8px; display: grid; gap: 4px; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-2); color: var(--rdw-text); font: 12px/1.35 var(--rdw-font); } .rdw-popover.${POPOVER_FIXED_CLASS} { position: fixed; z-index: ${String(POPOVER_FIXED_Z_INDEX)}; min-width: 0; margin: 0; box-sizing: border-box; } `; function computeAnchoredPopoverPosition(anchorLeft, anchorBottom, widthPx, viewportWidthPx) { let left = anchorLeft; if (left + widthPx > viewportWidthPx) left = viewportWidthPx - widthPx; return { top: anchorBottom + POPOVER_ANCHOR_GAP_PX, left }; } function pathIncludesNode(path, node) { if (node === null) return false; for (const entry of path) if (entry === node) return true; return false; } function Popover(props) { const rootRef = T(null); const wasOpenRef = T(false); A(() => { if (!props.open) { if (wasOpenRef.current) { wasOpenRef.current = false; const anchor = props.anchorRef?.current ?? null; if (anchor !== null && typeof anchor.focus === "function") anchor.focus(); } return; } wasOpenRef.current = true; const onKeyDown = (event) => { if (event.key === KEY_ESCAPE$2) { event.preventDefault(); props.onClose(); } }; const onPointerDown = (event) => { const root = rootRef.current; if (root === null) return; const path = event.composedPath(); if (pathIncludesNode(path, root)) return; if (pathIncludesNode(path, props.anchorRef?.current ?? null)) return; props.onClose(); }; document.addEventListener(EVENT_KEYDOWN$2, onKeyDown); document.addEventListener(EVENT_MOUSEDOWN$2, onPointerDown); return () => { document.removeEventListener(EVENT_KEYDOWN$2, onKeyDown); document.removeEventListener(EVENT_MOUSEDOWN$2, onPointerDown); }; }, [ props.open, props.onClose, props.anchorRef ]); const widthPx = props.widthPx; const anchored = widthPx !== void 0; F(() => { if (!props.open || widthPx === void 0) return; const apply = () => { const anchor = props.anchorRef?.current ?? null; const root = rootRef.current; if (anchor === null || root === null) return; const rect = anchor.getBoundingClientRect(); const position = computeAnchoredPopoverPosition(props.alignEnd === true ? Math.max(0, rect.right - widthPx) : rect.left, rect.bottom, widthPx, window.innerWidth); root.style.position = "fixed"; root.style.top = `${String(position.top)}px`; root.style.left = `${String(position.left)}px`; root.style.width = `${String(widthPx)}px`; }; apply(); const onScrollOrResize = () => { apply(); }; window.addEventListener(EVENT_SCROLL$1, onScrollOrResize, true); window.addEventListener(EVENT_RESIZE$1, onScrollOrResize); return () => { window.removeEventListener(EVENT_SCROLL$1, onScrollOrResize, true); window.removeEventListener(EVENT_RESIZE$1, onScrollOrResize); }; }, [ props.open, props.anchorRef, props.alignEnd, widthPx ]); if (!props.open) return null; const className = [ "rdw-popover", anchored ? POPOVER_FIXED_CLASS : void 0, props.className ].filter((part) => part !== void 0 && part.length > 0).join(" "); const body = /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: POPOVER_CSS }), /* @__PURE__ */ a("div", { ref: rootRef, className, role: props.role ?? "dialog", "aria-label": props["aria-label"], children: props.children })] }); if (anchored && document.body !== null) return U(body, document.body); return body; } var PROGRESS_WIDTH_VAR = "--rdw-progress-width"; var PROGRESS_BAR_CSS = ` .rdw-progress { display: grid; gap: 4px; width: 100%; } .rdw-progress__label { font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); } .rdw-progress__track { height: 6px; border-radius: 999px; background: var(--rdw-surface-2); border: 1px solid var(--rdw-border); overflow: hidden; } .rdw-progress__fill { height: 100%; width: var(${PROGRESS_WIDTH_VAR}, 0%); background: var(--rdw-accent); border-radius: inherit; transition: width 0.2s ease; } .rdw-progress__fill--indeterminate { width: 40%; animation: rdw-progress-indeterminate 1.1s ease-in-out infinite; } @keyframes rdw-progress-indeterminate { 0% { transform: translateX(-120%); } 100% { transform: translateX(280%); } } `; function clampUnit(value) { if (!Number.isFinite(value)) return 0; if (value < 0) return 0; if (value > 1) return 1; return value; } function ProgressBar(props) { const fillRef = T(null); const waiting = props.waiting === true; const hasValue = props.value !== void 0 && props.value !== null; const ratio = hasValue ? clampUnit(props.value) : 0; const className = ["rdw-progress", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); A(() => { const fill = fillRef.current; if (fill === null) return; if (waiting || !hasValue) { fill.style.removeProperty(PROGRESS_WIDTH_VAR); return; } fill.style.setProperty(PROGRESS_WIDTH_VAR, `${Math.round(ratio * 100)}%`); }, [ waiting, hasValue, ratio ]); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: PROGRESS_BAR_CSS }), /* @__PURE__ */ a("div", { className, children: [props.label !== void 0 ? /* @__PURE__ */ a("div", { className: "rdw-progress__label", children: props.label }) : null, /* @__PURE__ */ a("div", { className: "rdw-progress__track", role: "progressbar", "aria-label": props.label, "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": hasValue && !waiting ? Math.round(ratio * 100) : void 0, children: /* @__PURE__ */ a("div", { ref: fillRef, className: waiting ? "rdw-progress__fill rdw-progress__fill--indeterminate" : "rdw-progress__fill" }) })] })] }); } var SEARCH_FIELD_CLASS = "rdw-search-field"; var SEARCH_HELP_CLASS = "rdw-search-help"; var ICON_CLASS = "rdw-search-field__icon"; var TOOLS_CLASS = "rdw-search-field__tools"; var TOOL_CLASS = "rdw-search-field__tool"; var NOTE_CLASS$1 = "rdw-search-help__note"; var INPUT_CLASS = "rdw-search-field__input"; var SUGGEST_CLASS = "rdw-suggest"; var SUGGEST_HEADING_CLASS = "rdw-suggest__heading"; var SUGGEST_LIST_CLASS = "rdw-suggest__list"; var SUGGEST_ROW_CLASS = "rdw-suggest__row"; var SUGGEST_ROW_ACTIVE_CLASS = "rdw-suggest__row--active"; var SUGGEST_ROW_DIVIDER_CLASS = "rdw-suggest__row--divider"; var SUGGEST_LABEL_CLASS = "rdw-suggest__label"; var SUGGEST_TRAILING_CLASS = "rdw-suggest__trailing"; var SUGGEST_MIN_WIDTH_PX = 320; var SUGGEST_MAX_WIDTH_PX = 480; var SUGGEST_ROW_HEIGHT_PX = 28; var SUGGEST_GAP_PX = 4; var SUGGEST_EDGE_PX = 8; /** Above the pinned rows and the post panel, as an anchored popover is. */ var SUGGEST_Z_INDEX = 120; var SUGGEST_ACCENT_BAR_PX = 3; var KEY_DOWN = "ArrowDown"; var KEY_UP = "ArrowUp"; var KEY_ENTER$2 = "Enter"; var KEY_TAB = "Tab"; var KEY_ESCAPE$1 = "Escape"; var DEFAULT_CLEAR_LABEL = "Clear"; var DEFAULT_HELP_WIDTH_PX = 320; var ICON_PX$2 = 14; var SEARCH_FIELD_CSS = ` .${SEARCH_FIELD_CLASS} { position: relative; min-width: 0; } .${SEARCH_FIELD_CLASS} .${INPUT_CLASS} { margin: 0; } .${SEARCH_FIELD_CLASS} .${INPUT_CLASS} .rdw-field__input { padding-left: 30px; padding-right: 56px; } .${ICON_CLASS} { position: absolute; left: 9px; top: 50%; transform: translateY(-50%); color: var(--rdw-muted); pointer-events: none; } .${TOOLS_CLASS} { position: absolute; right: 4px; top: 50%; transform: translateY(-50%); display: flex; gap: 2px; } .${TOOL_CLASS} { display: inline-grid; place-items: center; width: 22px; height: 22px; padding: 0; border: 0; border-radius: var(--rdw-radius-s); background: transparent; color: var(--rdw-muted); cursor: pointer; } .${TOOL_CLASS}:hover, .${TOOL_CLASS}[aria-expanded="true"] { color: var(--rdw-text); } .${SEARCH_HELP_CLASS} { display: grid; grid-template-columns: max-content 1fr; gap: 4px 12px; margin: 0; } /* The site styles dt on its own (bold, its own font); a command has to be in a fixed-width font, or the spaces that matter in it cannot be seen. */ .rdw-popover .${SEARCH_HELP_CLASS} dt { margin: 0; font: 400 12px/1.4 ui-monospace, "Cascadia Mono", Consolas, "Courier New", monospace !important; white-space: pre; color: var(--rdw-text); } .${SEARCH_HELP_CLASS} dd { margin: 0; color: var(--rdw-muted); } .${NOTE_CLASS$1} { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rdw-border); color: var(--rdw-muted); line-height: 1.4; } `.trim(); var SEARCH_SUGGEST_CSS = ` .${SUGGEST_CLASS} { position: fixed; z-index: ${String(SUGGEST_Z_INDEX)}; box-sizing: border-box; margin: 0; padding: 4px; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-2); color: var(--rdw-text); font: 12.5px/1.35 var(--rdw-font); } .${SUGGEST_HEADING_CLASS} { padding: 4px 8px 6px; color: var(--rdw-muted); font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; } .${SUGGEST_LIST_CLASS} { margin: 0; padding: 0; list-style: none; max-height: ${String(224)}px; overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--rdw-border) transparent; } .${SUGGEST_ROW_CLASS} { box-sizing: border-box; display: flex; align-items: center; gap: 12px; min-height: ${String(SUGGEST_ROW_HEIGHT_PX)}px; margin: 0; padding: 0 8px 0 ${String(11)}px; border-radius: var(--rdw-radius-s); list-style: none; cursor: pointer; position: relative; } .${SUGGEST_ROW_CLASS}.${SUGGEST_ROW_DIVIDER_CLASS} { margin-top: 9px; } /* The rule between the tags that begin with what was typed and the rest. */ .${SUGGEST_ROW_CLASS}.${SUGGEST_ROW_DIVIDER_CLASS}::after { content: ""; position: absolute; left: 0; right: 0; top: -5px; border-top: 1px solid var(--rdw-border); } .${SUGGEST_ROW_CLASS}:hover, .${SUGGEST_ROW_CLASS}.${SUGGEST_ROW_ACTIVE_CLASS} { background: var(--rdw-surface-2); } /* The line chosen with the keyboard has a bar as well: not told by colour alone. */ .${SUGGEST_ROW_CLASS}.${SUGGEST_ROW_ACTIVE_CLASS}::before { content: ""; position: absolute; left: 0; top: 4px; bottom: 4px; width: ${String(SUGGEST_ACCENT_BAR_PX)}px; border-radius: ${String(SUGGEST_ACCENT_BAR_PX)}px; background: var(--rdw-accent); } .${SUGGEST_LABEL_CLASS} { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rdw-muted); } .${SUGGEST_LABEL_CLASS} b { color: var(--rdw-text); font-weight: 700; } /* On the chosen line the rest of the tag is in the text colour too: muted on the fill of that line passes the contrast limit only just (4.7:1 in Dark). What was typed is still told by its weight. */ .${SUGGEST_ROW_CLASS}.${SUGGEST_ROW_ACTIVE_CLASS} .${SUGGEST_LABEL_CLASS} { color: var(--rdw-text); } .${SUGGEST_TRAILING_CLASS} { flex: none; color: var(--rdw-muted); font-variant-numeric: tabular-nums; text-align: right; } `.trim(); /** Where the list goes: under the field, from its left edge, kept inside the window. */ function suggestBox(fieldLeft, fieldBottom, fieldWidth, viewportWidth) { const room = Math.max(0, viewportWidth - 16); const width = Math.min(room, Math.max(SUGGEST_MIN_WIDTH_PX, Math.min(SUGGEST_MAX_WIDTH_PX, fieldWidth))); const left = Math.max(SUGGEST_EDGE_PX, Math.min(fieldLeft, viewportWidth - SUGGEST_EDGE_PX - width)); return { top: fieldBottom + SUGGEST_GAP_PX, left, width }; } /** The list a "?" opens; also used by the help of the site's own search field. */ function SearchHelpList(props) { return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("style", { children: SEARCH_FIELD_CSS }), /* @__PURE__ */ a("dl", { className: SEARCH_HELP_CLASS, children: props.help.rows.map(([example, meaning]) => /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("dt", { children: example }), /* @__PURE__ */ a("dd", { children: meaning })] })) }), props.help.note === void 0 ? null : /* @__PURE__ */ a("p", { className: NOTE_CLASS$1, children: props.help.note }) ] }); } function SearchField(props) { const [helpOpen, setHelpOpen] = d(false); const helpButtonRef = T(null); const rootRef = T(null); const inputRef = T(null); const listRef = T(null); const listId = P$1(); const [caret, setCaret] = d(0); const [focused, setFocused] = d(false); const [dismissed, setDismissed] = d(false); const [active, setActive] = d(0); const caretAfterPick = T(null); const { help, suggest, onCommit } = props; const clearLabel = props.clearLabel ?? DEFAULT_CLEAR_LABEL; const className = [SEARCH_FIELD_CLASS, props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); const list = suggest !== void 0 && focused && !dismissed ? suggest.list(props.value, caret) : null; const items = list?.items ?? []; const open = items.length > 0; const activeIndex = open ? Math.min(active, items.length - 1) : -1; const readCaret = () => inputRef.current?.selectionStart ?? props.value.length; const change = (value) => { props.onChange(value); const at = inputRef.current?.selectionStart ?? value.length; setCaret(at); setDismissed(false); setActive(0); const next = suggest === void 0 ? null : suggest.list(value, at); if (next === null || next.items.length === 0) onCommit?.(value); }; const pick = (index) => { const done = suggest?.pick(props.value, caret, index) ?? null; if (done === null) return; caretAfterPick.current = done.caret; props.onChange(done.text); setCaret(done.caret); setActive(0); onCommit?.(done.text); }; F(() => { const at = caretAfterPick.current; const input = inputRef.current; if (at !== null && input !== null) { caretAfterPick.current = null; input.setSelectionRange(at, at); } }); F(() => { if (!open) return; const place = () => { const root = rootRef.current; const box = listRef.current; if (root === null || box === null) return; const rect = root.getBoundingClientRect(); const at = suggestBox(rect.left, rect.bottom, rect.width, window.innerWidth); box.style.top = `${String(at.top)}px`; box.style.left = `${String(at.left)}px`; box.style.width = `${String(at.width)}px`; }; place(); window.addEventListener("scroll", place, true); window.addEventListener("resize", place); return () => { window.removeEventListener("scroll", place, true); window.removeEventListener("resize", place); }; }, [open]); A(() => { if (activeIndex < 0) return; const row = listRef.current?.querySelector(`#${CSS.escape(`${listId}-${String(activeIndex)}`)}`); if (row instanceof HTMLElement && typeof row.scrollIntoView === "function") row.scrollIntoView({ block: "nearest" }); }, [activeIndex, listId]); const onKeyDown = (event) => { if (!open) { if (event.key === KEY_ENTER$2) onCommit?.(props.value); return; } if (event.key === KEY_DOWN || event.key === KEY_UP) { event.preventDefault(); const step = event.key === KEY_DOWN ? 1 : -1; setActive((activeIndex + step + items.length) % items.length); } else if (event.key === KEY_ENTER$2 || event.key === KEY_TAB) { event.preventDefault(); pick(activeIndex); } else if (event.key === KEY_ESCAPE$1) { event.preventDefault(); event.stopPropagation(); setDismissed(true); onCommit?.(props.value); } }; const suggestions = open ? /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: SEARCH_SUGGEST_CSS }), /* @__PURE__ */ a("div", { className: SUGGEST_CLASS, ref: listRef, onMouseDown: (event) => { event.preventDefault(); }, children: [list?.heading === null || list?.heading === void 0 ? null : /* @__PURE__ */ a("div", { className: SUGGEST_HEADING_CLASS, "aria-hidden": "true", children: list.heading }), /* @__PURE__ */ a("ul", { className: SUGGEST_LIST_CLASS, id: listId, role: "listbox", "aria-label": list?.heading === null || list?.heading === void 0 ? suggest?.label : `${suggest?.label ?? ""}: ${list.heading}`, children: items.map((item, index) => /* @__PURE__ */ a("li", { id: `${listId}-${String(index)}`, role: "option", "aria-selected": index === activeIndex, "aria-label": item.announce, className: [ SUGGEST_ROW_CLASS, index === activeIndex ? SUGGEST_ROW_ACTIVE_CLASS : "", item.divider ? SUGGEST_ROW_DIVIDER_CLASS : "" ].filter((part) => part.length > 0).join(" "), onClick: () => { pick(index); }, children: [/* @__PURE__ */ a("span", { className: SUGGEST_LABEL_CLASS, children: [ item.label.slice(0, item.matchStart), /* @__PURE__ */ a("b", { children: item.label.slice(item.matchStart, item.matchStart + item.matchLength) }), item.label.slice(item.matchStart + item.matchLength) ] }), item.trailing === null ? null : /* @__PURE__ */ a("span", { className: SUGGEST_TRAILING_CLASS, children: item.trailing })] }, item.key)) })] })] }) : null; const comboAttrs = suggest === void 0 ? {} : { role: "combobox", autocomplete: "off", "aria-autocomplete": "list", "aria-expanded": open, "aria-controls": listId, ...activeIndex >= 0 ? { "aria-activedescendant": `${listId}-${String(activeIndex)}` } : {}, onKeyDown, onKeyUp: () => { setCaret(readCaret()); }, onClick: () => { setCaret(readCaret()); }, onFocus: () => { setFocused(true); setCaret(readCaret()); props.onFocus?.(); }, onBlur: () => { setFocused(false); setDismissed(false); onCommit?.(props.value); } }; return /* @__PURE__ */ a("div", { className, ref: rootRef, children: [ /* @__PURE__ */ a("style", { children: SEARCH_FIELD_CSS }), /* @__PURE__ */ a(IconSearch, { className: ICON_CLASS, size: ICON_PX$2 }), /* @__PURE__ */ a(TextField, { ...props.id === void 0 ? {} : { id: props.id }, className: INPUT_CLASS, value: props.value, placeholder: props.placeholder, "aria-label": props["aria-label"], inputRef, inputAttrs: comboAttrs, onChange: change }), suggestions !== null && document.body !== null ? U(suggestions, document.body) : null, /* @__PURE__ */ a("span", { className: TOOLS_CLASS, children: [props.value.length > 0 ? /* @__PURE__ */ a("button", { type: "button", className: `${TOOL_CLASS} rdw-kit-focusable`, "aria-label": clearLabel, title: clearLabel, onClick: () => { props.onChange(""); onCommit?.(""); rootRef.current?.querySelector("input")?.focus(); }, children: /* @__PURE__ */ a(IconX, { size: ICON_PX$2 }) }) : null, help === void 0 ? null : /* @__PURE__ */ a("button", { type: "button", ref: helpButtonRef, className: `${TOOL_CLASS} rdw-kit-focusable`, "aria-label": help.label, title: help.label, "aria-expanded": helpOpen, onClick: () => { setHelpOpen(!helpOpen); }, children: /* @__PURE__ */ a(IconHelp, { size: ICON_PX$2 }) })] }), help === void 0 ? null : /* @__PURE__ */ a(Popover, { open: helpOpen, onClose: () => { setHelpOpen(false); }, anchorRef: helpButtonRef, widthPx: help.widthPx ?? DEFAULT_HELP_WIDTH_PX, alignEnd: true, "aria-label": help.label, children: /* @__PURE__ */ a(SearchHelpList, { help }) }) ] }); } var SECTION_LABEL_CSS = ` .rdw-section-label { display: block; font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); margin: 0 0 4px; } `; function SectionLabel(props) { const className = ["rdw-section-label", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); if (props.htmlFor !== void 0) return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: SECTION_LABEL_CSS }), /* @__PURE__ */ a("label", { className, htmlFor: props.htmlFor, children: props.children })] }); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: SECTION_LABEL_CSS }), /* @__PURE__ */ a("div", { className, children: props.children })] }); } var SEGMENTED_CSS = ` ${KIT_FOCUS_CSS} .rdw-seg { display: grid; grid-auto-flow: column; grid-auto-columns: 1fr; background: var(--rdw-seg-track, transparent); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); padding: 2px; gap: 2px; /* The whole control is as tall as a button or a field beside it. */ box-sizing: border-box; height: ${KIT_CONTROL_HEIGHT}; } .rdw-seg__btn { min-height: 0; height: 100%; display: grid; place-items: center; border: 0; border-radius: var(--rdw-radius-s); background: transparent; color: var(--rdw-seg-text, var(--rdw-muted)); font: inherit; font-size: ${KIT_CONTROL_FONT}; cursor: pointer; padding: 0 8px; } .rdw-seg__btn[aria-checked="true"] { background: var(--rdw-seg-on, var(--rdw-surface)); color: var(--rdw-seg-on-text, var(--rdw-text)); font-weight: 600; } /* Not to be changed: the chosen option is still read, the others are faint. */ .rdw-seg[aria-disabled="true"] .rdw-seg__btn { cursor: not-allowed; } .rdw-seg[aria-disabled="true"] .rdw-seg__btn[aria-checked="false"] { opacity: 0.4; } .rdw-seg[aria-disabled="true"] .rdw-seg__btn[aria-checked="true"] { opacity: 0.75; } `; function Segmented(props) { const className = ["rdw-seg", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); const disabled = props.disabled === true; return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: SEGMENTED_CSS }), /* @__PURE__ */ a("div", { className, role: "radiogroup", "aria-label": props.label, "aria-disabled": disabled ? true : void 0, children: props.options.map((option) => { const selected = option.value === props.value; return /* @__PURE__ */ a("button", { type: "button", role: "radio", className: "rdw-seg__btn rdw-kit-focusable", "aria-checked": selected, "aria-disabled": disabled ? true : void 0, tabIndex: selected ? 0 : -1, onClick: () => { if (!disabled) props.onChange(option.value); }, onKeyDown: (event) => { if (disabled) return; if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return; event.preventDefault(); const index = props.options.findIndex((item) => item.value === props.value); if (index < 0) return; const delta = event.key === "ArrowRight" ? 1 : -1; const next = props.options[(index + delta + props.options.length) % props.options.length]; if (next !== void 0) props.onChange(next.value); }, children: option.label }, option.value); }) })] }); } var CLASS_ROOT$1 = "rdw-selbar"; var CLASS_ROW = "rdw-selbar--row"; var CLASS_STACK = "rdw-selbar--stack"; var CLASS_COUNT = "rdw-selbar__count"; var CLASS_HEAD = "rdw-selbar__head"; var CLASS_PICK = "rdw-selbar__pick"; var CLASS_SPACER = "rdw-selbar__spacer"; var CLASS_ACTIONS$2 = "rdw-selbar__actions"; var CLASS_RULE = "rdw-selbar__rule"; var SELECTION_BAR_LABEL = "Selection"; var SELECTION_CLEAR = "Clear"; var SELECTION_CANCEL = "Cancel"; var SELECTED_SUFFIX = " selected"; /** In the hint of the button of select all: the key that does the same (Kaze, 18.11.2026). */ var SELECT_ALL_KEY_HINT = " (Ctrl+A)"; var EVENT_KEYDOWN$1$1 = "keydown"; var SELECT_ALL_KEY_CODE = "KeyA"; /** Where Ctrl+A selects the text of a field or belongs to what is open. */ var OWN_SELECT_ALL_SELECTOR = "input, textarea, select, [contenteditable], [role=\"dialog\"]"; var OPEN_DIALOG_SELECTOR$1 = "[role=\"dialog\"]"; var ROW_SPREAD_PX = 5; var SELECTION_BAR_CSS = ` .${CLASS_ROOT$1} { box-sizing: border-box; color: var(--rdw-text); font-size: ${KIT_CONTROL_FONT}; } .${CLASS_ROW} { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-height: ${KIT_CONTROL_HEIGHT}; margin-inline: ${String(ROW_SPREAD_PX)}px; border-radius: var(--rdw-radius-m); background: var(--rdw-accent-soft); box-shadow: 0 0 0 ${String(ROW_SPREAD_PX)}px var(--rdw-accent-soft); } .${CLASS_STACK} { display: flex; flex-direction: column; gap: 8px; padding: 10px; border: 1px solid var(--rdw-accent); border-radius: var(--rdw-radius-l); background: var(--rdw-accent-soft); } .${CLASS_COUNT} { font-weight: 600; white-space: nowrap; } .${CLASS_ROW} > .${CLASS_COUNT} { padding-inline: 4px 8px; } .${CLASS_HEAD}, .${CLASS_PICK} { display: flex; align-items: center; gap: 8px; } .${CLASS_HEAD} { justify-content: space-between; } .${CLASS_SPACER} { flex: 1 1 0; min-width: 0; } .${CLASS_ACTIONS$2} { display: flex; align-items: center; gap: 8px; } .${CLASS_STACK} .${CLASS_ACTIONS$2} { flex-direction: column; align-items: stretch; } .${CLASS_STACK} .${CLASS_ACTIONS$2} > .rdw-btn { width: 100%; } .${CLASS_RULE} { flex: none; align-self: stretch; background: var(--rdw-border); } .${CLASS_ROW} > .${CLASS_RULE} { width: 1px; margin-block: 4px; } .${CLASS_STACK} > .${CLASS_RULE} { height: 1px; } `; function ownSelectAll(event) { if (document.querySelector(OPEN_DIALOG_SELECTOR$1) !== null) return true; const origin = event.composedPath()[0]; if (!(origin instanceof Element)) return false; if (origin.closest(OWN_SELECT_ALL_SELECTOR) !== null) return true; const root = origin.getRootNode(); return root instanceof ShadowRoot && root.querySelector(OPEN_DIALOG_SELECTOR$1) !== null; } function SelectionBar(props) { const layout = props.layout ?? "row"; const none = props.count === 0; const latestSelectAll = T(props.onSelectAll); latestSelectAll.current = props.onSelectAll; A(() => { const onKeyDown = (event) => { if (event.code !== SELECT_ALL_KEY_CODE || !(event.ctrlKey || event.metaKey) || event.altKey || event.shiftKey || event.defaultPrevented || ownSelectAll(event)) return; event.preventDefault(); latestSelectAll.current(); }; document.addEventListener(EVENT_KEYDOWN$1$1, onKeyDown); return () => { document.removeEventListener(EVENT_KEYDOWN$1$1, onKeyDown); }; }, []); const count = /* @__PURE__ */ a("span", { className: CLASS_COUNT, "aria-live": "polite", children: `${String(props.count)}${SELECTED_SUFFIX}` }); const selectAllLabel = props.selectAllLabel ?? "Select all"; const selectAll = props.selectAll ?? /* @__PURE__ */ a(Button, { variant: "ghost", title: `${selectAllLabel}${SELECT_ALL_KEY_HINT}`, onClick: props.onSelectAll, children: selectAllLabel }); const clear = /* @__PURE__ */ a(Button, { variant: "ghost", disabled: none, onClick: props.onClear, children: SELECTION_CLEAR }); const cancel = /* @__PURE__ */ a(Button, { variant: "secondary", onClick: props.onCancel, children: SELECTION_CANCEL }); const hasActions = props.children !== void 0 && props.children !== null; const hasDanger = props.danger !== void 0 && props.danger !== null; const rule = hasActions && hasDanger ? /* @__PURE__ */ a("span", { className: CLASS_RULE, "aria-hidden": "true" }) : null; if (layout === "stack") return /* @__PURE__ */ a("div", { className: `${CLASS_ROOT$1} ${CLASS_STACK}`, role: "toolbar", "aria-label": SELECTION_BAR_LABEL, "aria-orientation": "vertical", children: [ /* @__PURE__ */ a("style", { children: SELECTION_BAR_CSS }), /* @__PURE__ */ a("div", { className: CLASS_HEAD, children: [count, cancel] }), /* @__PURE__ */ a("div", { className: CLASS_PICK, children: [selectAll, clear] }), hasActions ? /* @__PURE__ */ a("div", { className: CLASS_ACTIONS$2, children: props.children }) : null, rule, hasDanger ? /* @__PURE__ */ a("div", { className: CLASS_ACTIONS$2, children: props.danger }) : null ] }); return /* @__PURE__ */ a("div", { className: `${CLASS_ROOT$1} ${CLASS_ROW}`, role: "toolbar", "aria-label": SELECTION_BAR_LABEL, children: [ /* @__PURE__ */ a("style", { children: SELECTION_BAR_CSS }), count, selectAll, clear, /* @__PURE__ */ a("span", { className: CLASS_SPACER, "aria-hidden": "true" }), hasActions ? /* @__PURE__ */ a("div", { className: CLASS_ACTIONS$2, children: props.children }) : null, rule, hasDanger ? /* @__PURE__ */ a("div", { className: CLASS_ACTIONS$2, children: props.danger }) : null, cancel ] }); } var LIST_CLASS$1 = "rdw-select__list"; var LIST_FLOATING_CLASS = "rdw-select__list--floating"; var LIST_GAP_PX = 4; var TICK_ICON_PX = 14; var LIST_MAX_HEIGHT_PX$1 = 220; var LIST_EDGE_PX = 8; /** A list drawn over the page may be wider than its trigger, up to this. */ var LIST_FLOATING_MAX_WIDTH_PX = 360; var EVENT_SCROLL = "scroll"; var EVENT_RESIZE = "resize"; var SELECT_CSS = ` ${KIT_FOCUS_CSS} .rdw-select { position: relative; display: inline-flex; flex-direction: column; gap: 4px; min-width: 0; } .rdw-select__label { font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); } .rdw-select__trigger { box-sizing: border-box; display: flex; align-items: center; justify-content: space-between; gap: 8px; min-height: ${KIT_CONTROL_HEIGHT}; height: ${KIT_CONTROL_HEIGHT}; width: 100%; padding: 0 8px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); font: inherit; font-size: ${KIT_CONTROL_FONT}; cursor: pointer; } .rdw-select__trigger:disabled { opacity: 0.55; cursor: not-allowed; } .${LIST_CLASS$1} { position: absolute; z-index: 20; top: calc(100% + ${String(LIST_GAP_PX)}px); left: 0; right: 0; margin: 0; padding: 4px; list-style: none; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); box-shadow: var(--rdw-shadow-2); max-height: ${String(LIST_MAX_HEIGHT_PX$1)}px; overflow: auto; } /* On a page of the site the list is drawn in and placed by the trigger. */ .${LIST_CLASS$1}.${LIST_FLOATING_CLASS} { position: fixed; z-index: ${String(120)}; right: auto; box-sizing: border-box; max-width: ${String(LIST_FLOATING_MAX_WIDTH_PX)}px; font: 12.5px/1.4 var(--rdw-font); text-align: left; } .rdw-select__option { min-height: ${KIT_CONTROL_HEIGHT}; display: flex; align-items: center; padding: 0 8px; border-radius: var(--rdw-radius-s); font-size: ${KIT_CONTROL_FONT}; color: var(--rdw-text); cursor: pointer; } .rdw-select__option { justify-content: space-between; gap: 12px; } /* The chosen option has a tick and a heavier text; the fill is for the option under the pointer or the keyboard. One fill for both made them one. */ .rdw-select__option:hover, .rdw-select__option:focus-visible { background: var(--rdw-surface-2); } .rdw-select__option[aria-selected="true"] { font-weight: 600; } .rdw-select__tick { flex: none; color: var(--rdw-accent); } `; function Select(props) { const listId = P$1(); const rootRef = T(null); const triggerRef = T(null); const listRef = T(null); const [open, setOpen] = d(false); const floating = !j(OverlayInPlace) && !(rootRef.current?.getRootNode() instanceof ShadowRoot); const selected = props.options.find((option) => option.value === props.value) ?? props.options[0]; const className = ["rdw-select", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); A(() => { if (!open) return; const onKeyDown = (event) => { if (event.key === "Escape") setOpen(false); }; const onPointerDown = (event) => { const root = rootRef.current; if (root === null) return; const path = event.composedPath(); const list = listRef.current; if (!path.includes(root) && (list === null || !path.includes(list))) setOpen(false); }; document.addEventListener("keydown", onKeyDown); document.addEventListener("mousedown", onPointerDown); return () => { document.removeEventListener("keydown", onKeyDown); document.removeEventListener("mousedown", onPointerDown); }; }, [open]); F(() => { if (!open || !floating) return; const place = () => { const trigger = triggerRef.current; const list = listRef.current; if (trigger === null || list === null) return; const rect = trigger.getBoundingClientRect(); const height = Math.min(list.scrollHeight, LIST_MAX_HEIGHT_PX$1); const below = rect.bottom + LIST_GAP_PX; const fitsBelow = below + height <= window.innerHeight - LIST_EDGE_PX; const above = rect.top - LIST_GAP_PX - height; list.style.top = `${String(fitsBelow || above < LIST_EDGE_PX ? below : above)}px`; list.style.left = `${String(rect.left)}px`; list.style.minWidth = `${String(rect.width)}px`; }; place(); window.addEventListener(EVENT_SCROLL, place, true); window.addEventListener(EVENT_RESIZE, place); return () => { window.removeEventListener(EVENT_SCROLL, place, true); window.removeEventListener(EVENT_RESIZE, place); }; }, [open, floating]); const list = open ? /* @__PURE__ */ a("ul", { className: floating ? `${LIST_CLASS$1} ${LIST_FLOATING_CLASS}` : LIST_CLASS$1, role: "listbox", id: listId, tabIndex: -1, ref: listRef, children: props.options.map((option) => /* @__PURE__ */ a("li", { role: "option", className: "rdw-select__option rdw-kit-focusable", "aria-selected": option.value === props.value, tabIndex: 0, onClick: () => { props.onChange(option.value); setOpen(false); }, onKeyDown: (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); props.onChange(option.value); setOpen(false); triggerRef.current?.focus(); } }, children: [/* @__PURE__ */ a("span", { children: option.label }), option.value === props.value ? /* @__PURE__ */ a(IconCheck, { size: TICK_ICON_PX, className: "rdw-select__tick" }) : null] }, option.value)) }) : null; return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("style", { children: SELECT_CSS }), /* @__PURE__ */ a("div", { className, ref: rootRef, children: [ props.label !== void 0 ? /* @__PURE__ */ a("span", { className: "rdw-select__label", id: `${listId}-label`, children: props.label }) : null, /* @__PURE__ */ a("button", { type: "button", className: "rdw-select__trigger rdw-kit-focusable", "aria-haspopup": "listbox", "aria-expanded": open, "aria-controls": listId, "aria-labelledby": props.label !== void 0 ? `${listId}-label` : void 0, disabled: props.disabled, ref: triggerRef, onClick: () => { setOpen((prev) => !prev); }, children: [/* @__PURE__ */ a("span", { children: selected?.label ?? props.value }), /* @__PURE__ */ a(IconChevronDown, { size: 14 })] }), floating ? null : list ] }), floating && list !== null ? U(list, document.body) : null ] }); } var SITE_THEME_SELECTOR = `[${RDW_THEME_ATTR}="${APPEARANCE_THEME_SITE}"]`; var SITE_DARK_THEME_SELECTOR = `[${RDW_THEME_ATTR}="${APPEARANCE_THEME_SITE_DARK}"]`; var SWITCH_CSS = ` ${KIT_FOCUS_CSS} .rdw-switch-row { display: inline-flex; align-items: center; gap: 8px; min-height: ${KIT_CONTROL_HEIGHT}; } .rdw-switch { position: relative; box-sizing: border-box; width: 36px; height: ${KIT_CONTROL_HEIGHT}; min-width: 36px; min-height: ${KIT_CONTROL_HEIGHT}; border: 0; padding: 0; background: transparent; cursor: pointer; } .rdw-switch__track { display: block; width: 30px; height: 17px; margin: 0 auto; border-radius: 9px; background: var(--rdw-border); /* Off, the track was dark on a dark card: an outline tells it from the card. */ box-shadow: inset 0 0 0 1px var(--rdw-muted); position: relative; transition: background 0.15s ease; } .rdw-switch__thumb { position: absolute; top: 2px; left: 2px; width: 13px; height: 13px; border-radius: 50%; /* Lighter than the track it lies on while off. */ background: var(--rdw-muted); transition: left 0.15s ease; } .rdw-switch[aria-checked="true"] .rdw-switch__track { background: var(--rdw-accent); box-shadow: none; } .rdw-switch[aria-checked="true"] .rdw-switch__thumb { left: 15px; background: var(--rdw-surface); } .rdw-switch:disabled { opacity: 0.55; cursor: not-allowed; } .rdw-switch__label { font-size: 12.5px; color: var(--rdw-text); } /* Site default: green ON (not link blue); OFF stays border; thumb contrast-checked. */ html${SITE_THEME_SELECTOR} .rdw-switch[aria-checked="true"] .rdw-switch__track, :host-context(${SITE_THEME_SELECTOR}) .rdw-switch[aria-checked="true"] .rdw-switch__track { background: ${SITE_DEFAULT_SWITCH_ON}; } html${SITE_THEME_SELECTOR} .rdw-switch[aria-checked="true"] .rdw-switch__thumb, :host-context(${SITE_THEME_SELECTOR}) .rdw-switch[aria-checked="true"] .rdw-switch__thumb { background: ${resolveSwitchThumbOn(SITE_DEFAULT_SWITCH_ON, SITE_DEFAULT_SWITCH_THUMB_ON, [SITE_LIGHT_C_BG_ALT, "#ffffff"])}; } html${SITE_THEME_SELECTOR} .rdw-switch:not([aria-checked="true"]) .rdw-switch__track, :host-context(${SITE_THEME_SELECTOR}) .rdw-switch:not([aria-checked="true"]) .rdw-switch__track { background: var(--rdw-border); } /* Site dark: ON = accent; OFF = border; thumb contrast-checked vs accent. */ html${SITE_DARK_THEME_SELECTOR} .rdw-switch[aria-checked="true"] .rdw-switch__track, :host-context(${SITE_DARK_THEME_SELECTOR}) .rdw-switch[aria-checked="true"] .rdw-switch__track { background: ${SITE_DARK_C_ACCENT}; } html${SITE_DARK_THEME_SELECTOR} .rdw-switch[aria-checked="true"] .rdw-switch__thumb, :host-context(${SITE_DARK_THEME_SELECTOR}) .rdw-switch[aria-checked="true"] .rdw-switch__thumb { background: ${resolveSwitchThumbOn(SITE_DARK_C_ACCENT, SITE_DARK_C_BG, ["#16181c", "#ffffff"])}; } html${SITE_DARK_THEME_SELECTOR} .rdw-switch:not([aria-checked="true"]) .rdw-switch__track, :host-context(${SITE_DARK_THEME_SELECTOR}) .rdw-switch:not([aria-checked="true"]) .rdw-switch__track { background: ${SITE_DARK_C_BORDER}; } `; function Switch(props) { const className = ["rdw-switch-row", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: SWITCH_CSS }), /* @__PURE__ */ a("div", { className, children: [/* @__PURE__ */ a("button", { type: "button", id: props.id, className: "rdw-switch rdw-kit-focusable", role: "switch", "aria-checked": props.checked, "aria-label": props.label, disabled: props.disabled, onClick: () => { props.onChange(!props.checked); }, children: /* @__PURE__ */ a("span", { className: "rdw-switch__track", children: /* @__PURE__ */ a("span", { className: "rdw-switch__thumb" }) }) }), props.label !== void 0 ? /* @__PURE__ */ a("span", { className: "rdw-switch__label", children: props.label }) : null] })] }); } var TAB_ID_PREFIX = "rdw-tab-"; var TAB_PANEL_ID_PREFIX = "rdw-tabpanel-"; var KEY_ARROW_RIGHT = "ArrowRight"; var KEY_ARROW_LEFT = "ArrowLeft"; function kitTabId(id) { return `${TAB_ID_PREFIX}${id}`; } function kitTabPanelId(id) { return `${TAB_PANEL_ID_PREFIX}${id}`; } var TABS_CSS = ` ${KIT_FOCUS_CSS} .rdw-tabs { display: flex; gap: 2px; border-bottom: 1px solid var(--rdw-border); padding: 0 8px; } .rdw-tabs__tab { box-sizing: border-box; min-height: ${KIT_CONTROL_HEIGHT}; padding: 7px 10px; border: 0; border-bottom: 2px solid transparent; background: transparent; color: var(--rdw-muted); font: inherit; font-size: 12.5px; cursor: pointer; margin-bottom: -1px; } .rdw-tabs__tab[aria-selected="true"] { color: var(--rdw-text); font-weight: 600; border-bottom-color: var(--rdw-accent); } `; function Tabs(props) { const className = ["rdw-tabs", props.className].filter((part) => part !== void 0 && part.length > 0).join(" "); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: TABS_CSS }), /* @__PURE__ */ a("div", { className, role: "tablist", "aria-label": props["aria-label"], children: props.items.map((item) => { const selected = item.id === props.value; return /* @__PURE__ */ a("button", { type: "button", role: "tab", id: kitTabId(item.id), className: "rdw-tabs__tab rdw-kit-focusable", "aria-selected": selected, "aria-controls": kitTabPanelId(item.id), tabIndex: selected ? 0 : -1, onClick: () => { props.onChange(item.id); }, onKeyDown: (event) => { if (event.key !== KEY_ARROW_RIGHT && event.key !== KEY_ARROW_LEFT) return; event.preventDefault(); const index = props.items.findIndex((entry) => entry.id === props.value); if (index < 0) return; const delta = event.key === KEY_ARROW_RIGHT ? 1 : -1; const next = props.items[(index + delta + props.items.length) % props.items.length]; if (next === void 0) return; props.onChange(next.id); const nextTab = event.currentTarget.parentElement?.querySelector(`#${kitTabId(next.id)}`); if (nextTab instanceof HTMLElement) nextTab.focus(); }, children: item.label }, item.id); }) })] }); } /** How long a toast stays visible before it dismisses itself. */ var TOAST_AUTO_HIDE_MS = 6e3; var TOAST_Z_INDEX = 45; var TOAST_BOTTOM_PX = 16; var TOAST_MAX_WIDTH_PX = 420; var TOAST_PADDING_X_PX = 12; var TOAST_PADDING_Y_PX = 8; var TOAST_GAP_PX = 12; var nextToastSlotId = 0; var activeToastSlot = null; function clearSlotTimer(slot) { if (slot.timerId === null) return; window.clearTimeout(slot.timerId); slot.timerId = null; } function takeToastSlot(close) { nextToastSlotId += 1; const slot = { id: nextToastSlotId, close, timerId: null }; const previous = activeToastSlot; activeToastSlot = slot; if (previous !== null) { clearSlotTimer(previous); previous.close(); } return slot; } function dismissToast(id) { if (activeToastSlot === null || activeToastSlot.id !== id) return; const slot = activeToastSlot; clearSlotTimer(slot); activeToastSlot = null; slot.close(); } function releaseToastSlot(id) { if (activeToastSlot !== null && activeToastSlot.id === id) activeToastSlot = null; } var TOAST_CSS = ` ${KIT_FOCUS_CSS} .rdw-toast { position: fixed; z-index: ${String(TOAST_Z_INDEX)}; left: 50%; bottom: ${String(TOAST_BOTTOM_PX)}px; transform: translateX(-50%); box-sizing: border-box; display: flex; align-items: center; gap: ${String(TOAST_GAP_PX)}px; width: max-content; max-width: min(${String(TOAST_MAX_WIDTH_PX)}px, calc(100% - ${String(32)}px)); padding: ${String(TOAST_PADDING_Y_PX)}px ${String(TOAST_PADDING_X_PX)}px; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-2); color: var(--rdw-text); font: 12.5px/1.4 var(--rdw-font); } .rdw-toast__message { margin: 0; } `; function Toast(props) { const [slotId, setSlotId] = d(null); F(() => { if (!props.open) { setSlotId(null); return; } let alive = true; const slot = takeToastSlot(() => { if (alive) setSlotId(null); props.onClose(); }); setSlotId(slot.id); slot.timerId = window.setTimeout(() => { dismissToast(slot.id); }, TOAST_AUTO_HIDE_MS); return () => { alive = false; clearSlotTimer(slot); releaseToastSlot(slot.id); }; }, [ props.open, props.message, props.onClose ]); if (!props.open || slotId === null) return null; if (activeToastSlot === null || activeToastSlot.id !== slotId) return null; return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: TOAST_CSS }), /* @__PURE__ */ a("div", { className: "rdw-toast", role: "status", children: [/* @__PURE__ */ a("p", { className: "rdw-toast__message", children: props.message }), props.action !== void 0 ? /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: props.action.onClick, children: props.action.label }) : null] })] }); } /** * The settings page is opened at one of its sections. A section has an * address of its own, "#rdw/settings/video" (the designer, 19.11.2026), and * that is how the script's own links lead to it. The older way is kept for a * link that has only the address of the page: the caller names the section * before going there, and the page takes the name once when it is drawn. */ var FOCUS_KEY = "ruledesk-web.settings-focus"; /** The id of the Favorites block of the settings page. */ var SETTINGS_SECTION_FAVORITES = exports("aN","favorites"); /** "#rdw/settings/video" */ function settingsSectionHash(id) { return `${RDW_HASH_SETTINGS}/${encodeURIComponent(id)}`; } /** The section an address of the settings page names, or null when it names none. */ function settingsSectionFromHash(hash) { const prefix = `${RDW_HASH_SETTINGS}/`; if (!hash.startsWith(prefix)) return null; const raw = hash.slice(prefix.length).split("/")[0] ?? ""; if (raw.length === 0) return null; try { return decodeURIComponent(raw); } catch { return raw; } } function requestSettingsSection(id) { try { window.sessionStorage.setItem(FOCUS_KEY, id); } catch {} } /** The block asked for, or null; asking again gives null. */ function takeSettingsSection() { try { const id = window.sessionStorage.getItem(FOCUS_KEY); window.sessionStorage.removeItem(FOCUS_KEY); return id; } catch { return null; } } /** Opens the settings page at one of its blocks. */ function openSettingsAt(id) { window.location.hash = settingsSectionHash(id); } /** * The sticky header and sidebar: the site's header stays at the top of the * window while the page scrolls, and the sidebar of Posts and of a post stays * beside the content. On by default; one setting switches both off. * * Whatever else sticks to the top (the Favorites header, the toolbars of * Collections and Following) then has to sit under it, so the header's height * is kept in a custom property on that those bars read. * * No imports: used before the first paint as well as from settings. */ var STICKY_HEADER_SETTING_ID = exports("cj","sticky-header"); var STICKY_HEADER_SETTING_LABEL = exports("bd","Keep the header and the sidebar in place while scrolling"); var STICKY_HEADER_SWITCH_ID = exports("be","rdw-sticky-header"); var STICKY_HEADER_CLASS = "rdw-sticky-header"; /** Height of the sticky header; absent while the header is not sticky. */ var HEADER_HEIGHT_VAR = "--rdw-header-h"; /** Where a bar that sticks to the top of the window goes. */ var STICKY_TOP = exports("aV",`var(${HEADER_HEIGHT_VAR}, 0px)`); var HEADER_SELECTOR$2 = "div#header"; var HEADER_Z_INDEX$1 = 25; /** The class of the skin on ; the same as RDW_SKIN_CLASS (no imports here). */ var SKIN_CLASS = "rdw-skin"; /** * The sidebar of a search page and of a post page. It is taller than the * window (the tag list), so it scrolls inside itself once it is held. */ var SIDEBAR_SELECTORS = ["div#post-list > div.sidebar", "div#post-view > div.sidebar"]; var SIDEBAR_GAP_PX = 8; var SIDEBAR_SELECTOR$1 = SIDEBAR_SELECTORS.join(", "); /** * How far the bottom of the sidebar's block is above the bottom of the window * right now, in px; 0 while the block reaches the window's bottom. A sticky * element cannot leave its block: at the end of the page the block ends above * the bottom of the window (the footer is under it), and a sidebar as tall as * the window would be pushed up under the header. Instead it gets shorter by * this much, so it is full height everywhere but at the very end of a page. */ var SIDEBAR_FOOT_VAR = "--rdw-sidebar-foot"; /** On the sidebar while it has more content below what is shown. */ var SIDEBAR_MORE_CLASS = "rdw-sidebar-more"; var SIDEBAR_FADE_PX = 32; var SCROLL_END_SLACK_PX$1 = 2; var STICKY_HEADER_CSS = ` html.${STICKY_HEADER_CLASS} ${HEADER_SELECTOR$2} { position: sticky; top: 0; z-index: ${String(HEADER_Z_INDEX$1)}; } /* The site's header has no background of its own: held at the top it would let the page show through. The skin gives its header one; without the skin (Site default, Site dark) it gets the colour of the page. */ html.${STICKY_HEADER_CLASS}:not(.${SKIN_CLASS}) ${HEADER_SELECTOR$2} { background: var(--rdw-bg); } html.${STICKY_HEADER_CLASS} ${SIDEBAR_SELECTORS[0]}, html.${STICKY_HEADER_CLASS} ${SIDEBAR_SELECTORS[1]} { position: sticky; top: calc(${STICKY_TOP} + ${String(SIDEBAR_GAP_PX)}px); max-height: calc(100vh - ${STICKY_TOP} - ${String(16)}px - var(${SIDEBAR_FOOT_VAR}, 0px)); overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--rdw-border) transparent; } /* A strip that stays at the bottom edge of the sidebar and fades its last lines into the page. Not a mask on the sidebar: a mask hides everything drawn from inside it that lies outside its box, and a dialog opened from the search panel is drawn in the middle of the window. */ html.${STICKY_HEADER_CLASS} div.sidebar.${SIDEBAR_MORE_CLASS}::after { content: ""; position: sticky; bottom: 0; display: block; height: ${String(SIDEBAR_FADE_PX)}px; margin-top: -${String(SIDEBAR_FADE_PX)}px; background: linear-gradient(to bottom, transparent, var(--rdw-bg)); pointer-events: none; } `.trim(); var observer = null; function writeHeight() { const header = document.querySelector(HEADER_SELECTOR$2); const root = document.documentElement; if (header === null || !root.classList.contains("rdw-sticky-header")) { root.style.removeProperty(HEADER_HEIGHT_VAR); return; } const height = Math.round(header.getBoundingClientRect().height); root.style.setProperty(HEADER_HEIGHT_VAR, `${String(height)}px`); writeSidebarFoot(); } function findSidebar() { const sidebar = document.querySelector(SIDEBAR_SELECTOR$1); return sidebar instanceof HTMLElement ? sidebar : null; } function writeSidebarFoot() { const root = document.documentElement; const sidebar = findSidebar(); const block = sidebar?.parentElement; if (sidebar === null || block === null || block === void 0) { root.style.removeProperty(SIDEBAR_FOOT_VAR); return; } if (boundSidebar$1 !== sidebar && document.documentElement.classList.contains("rdw-sticky-header")) { boundSidebar$1?.removeEventListener("scroll", scheduleSidebarFoot); boundSidebar$1 = sidebar; sidebar.addEventListener("scroll", scheduleSidebarFoot, { passive: true }); } let tallestOther = 0; for (const child of block.children) if (child !== sidebar && child instanceof HTMLElement) tallestOther = Math.max(tallestOther, child.offsetHeight); const foot = tallestOther < window.innerHeight ? 0 : Math.max(0, Math.round(window.innerHeight - block.getBoundingClientRect().bottom)); root.style.setProperty(SIDEBAR_FOOT_VAR, `${String(foot)}px`); const hidden = sidebar.scrollHeight - sidebar.scrollTop - sidebar.clientHeight; sidebar.classList.toggle(SIDEBAR_MORE_CLASS, hidden > SCROLL_END_SLACK_PX$1); } /** * Runs on every scroll event. Browsers deliver those once per frame, and the * work is one rectangle read, so there is no throttle of its own (one made of * requestAnimationFrame would also stall while the tab is in the background). */ function scheduleSidebarFoot() { writeSidebarFoot(); } var boundSidebar$1 = null; function bindScroll(enabled) { window.removeEventListener("scroll", scheduleSidebarFoot); window.removeEventListener("resize", scheduleSidebarFoot); boundSidebar$1?.removeEventListener("scroll", scheduleSidebarFoot); boundSidebar$1?.classList.remove(SIDEBAR_MORE_CLASS); boundSidebar$1 = null; if (!enabled) return; window.addEventListener("scroll", scheduleSidebarFoot, { passive: true }); window.addEventListener("resize", scheduleSidebarFoot, { passive: true }); boundSidebar$1 = findSidebar(); boundSidebar$1?.addEventListener("scroll", scheduleSidebarFoot, { passive: true }); } /** Switches the sticky header on or off and keeps the height property in step. */ function applyStickyHeader(enabled) { document.documentElement.classList.toggle(STICKY_HEADER_CLASS, enabled); if (observer !== null) { observer.disconnect(); observer = null; } const header = document.querySelector(HEADER_SELECTOR$2); if (enabled && header !== null && typeof ResizeObserver === "function") { observer = new ResizeObserver(writeHeight); observer.observe(header); if (document.body !== null) observer.observe(document.body); } bindScroll(enabled); writeHeight(); } /** Under featureState: "a:tag", the first letter is the kind. */ var TAG_TYPES_STATE_ID = "tag-types"; /** The oldest are dropped past this many. */ var TAG_TYPES_MAX = 3e3; var CODE_OF = { artist: "a", character: "c", copyright: "p", metadata: "m" }; var CODE_SEPARATOR = ":"; function kindOfCode(code) { for (const kind of [ "artist", "character", "copyright", "metadata" ]) if (CODE_OF[kind] === code) return kind; return null; } function kindOfName(name) { return name === "artist" || name === "character" || name === "copyright" || name === "metadata" ? name : null; } /** A tag as it is kept and looked up: lower case, underscores for spaces. */ function tagKey(tag) { return tag.trim().toLowerCase().replaceAll(" ", "_"); } var known = null; function load() { if (known !== null) return known; const map = /* @__PURE__ */ new Map(); let kept = null; try { kept = getFeatureState(TAG_TYPES_STATE_ID); } catch {} if (Array.isArray(kept)) for (const item of kept) { if (typeof item !== "string") continue; const at = item.indexOf(CODE_SEPARATOR); const kind = at > 0 ? kindOfCode(item.slice(0, at)) : null; if (kind !== null) map.set(item.slice(at + 1), kind); } known = map; return map; } /** The kind of a tag when it was seen before, or null. */ function tagKindOf(tag) { return load().get(tagKey(tag)) ?? null; } /** * Remembers the kinds of the tags given, each as the site named it ("artist", * "general", …). Written to the storage only when something new came. */ function rememberTagKinds(entries) { const map = load(); let changed = false; for (const [tag, name] of entries) { const kind = name === void 0 ? null : kindOfName(name); const key = tagKey(tag); if (kind === null || key.length === 0 || map.get(key) === kind) continue; map.delete(key); map.set(key, kind); changed = true; } if (!changed) return; while (map.size > TAG_TYPES_MAX) { const oldest = map.keys().next(); if (oldest.done === true) break; map.delete(oldest.value); } try { setFeatureState(TAG_TYPES_STATE_ID, [...map].map(([tag, kind]) => `${CODE_OF[kind]}${CODE_SEPARATOR}${tag}`)); } catch {} } /** * The site's switch for AI posts. * * The site keeps it in the cookie `filter_ai` (`1` hidden, `0` shown) and the * server leaves AI posts out of a list itself, so the pages stay full. Its own * checkbox writes the cookie and reloads the page. The script writes the same * cookie, with Kaze's consent (17.11.2026): it is the third cookie the script * touches, after `tag_blacklist` and `theme`, and the only way to hide AI * posts in one part of the site and show them in another. */ var MS_PER_DAY$3 = 864e5; var COOKIE_PAIR_SEPARATOR$1 = ";"; var COOKIE_NAME_VALUE_SEPARATOR$2 = "="; /** True when the site hides AI posts now, false when it shows them, null when it was never set. */ function readSiteAiFilter() { const prefix = `${SITE_AI_FILTER_COOKIE_NAME}${COOKIE_NAME_VALUE_SEPARATOR$2}`; for (const pair of document.cookie.split(COOKIE_PAIR_SEPARATOR$1)) { const trimmed = pair.trim(); if (!trimmed.startsWith(prefix)) continue; const value = trimmed.slice(prefix.length); if (value === "1") return true; if (value === "0") return false; } return null; } /** Tells the site to hide or to show AI posts from the next request on. */ function writeSiteAiFilter(hide) { const expires = new Date(Date.now() + 365 * MS_PER_DAY$3); document.cookie = [ `${SITE_AI_FILTER_COOKIE_NAME}${COOKIE_NAME_VALUE_SEPARATOR$2}${hide ? "1" : "0"}`, `expires=${expires.toUTCString()}`, `path=/` ].join("; "); } /** * AI posts, shown or hidden, by the part of the site. * * Posts, Feed, what is opened from Following and what is opened from * Collections are all the site's list of posts, and the site has one switch * for it. The script remembers a choice for each of them and puts the site's * switch (the cookie `filter_ai`) the way the part you are in wants it. * Favorites is not filtered by the site at all: there the script leaves the * posts tagged `ai_generated` out itself. * * "Hide AI posts everywhere" in the settings overrides every one of them. */ var AI_SCOPE_POSTS = "posts"; var AI_SCOPE_FEED = "feed"; var AI_SCOPE_FOLLOWING = exports("A","following"); var AI_SCOPE_COLLECTIONS = exports("B","collections"); var AI_SCOPES = [ AI_SCOPE_POSTS, AI_SCOPE_FEED, AI_SCOPE_FOLLOWING, AI_SCOPE_COLLECTIONS, AI_SCOPE_FAVORITES ]; /** The tag the site puts on an AI post; Favorites is narrowed by it. */ var AI_TAG = "ai_generated"; var STATE_ALL = "all"; var STATE_HIDE = AI_STATE_HIDE; var AI_MODE_SHOW = "show"; var AI_MODE_HIDE = "hide"; var AI_LABEL = "AI posts"; var AI_MODE_OPTIONS = [{ value: AI_MODE_SHOW, label: "Show" }, { value: AI_MODE_HIDE, label: "Hide" }]; function isRecord$2(value) { return value !== null && typeof value === "object" && !Array.isArray(value); } function readState() { const raw = getFeatureState(AI_STATE_ID); const hide = {}; if (!isRecord$2(raw)) return { all: false, hide }; const stored = raw[STATE_HIDE]; if (isRecord$2(stored)) for (const scope of AI_SCOPES) { const value = stored[scope]; if (typeof value === "boolean") hide[scope] = value; } return { all: raw[STATE_ALL] === true, hide }; } function writeState(state) { setFeatureState(AI_STATE_ID, { [STATE_ALL]: state.all, [STATE_HIDE]: state.hide }); } /** True when the settings hide AI posts in every part of the site. */ function aiHiddenEverywhere() { return readState().all; } function setAiHiddenEverywhere(hide) { writeState({ ...readState(), all: hide }); } /** * The choice remembered for one part, whatever the settings say. Every part * starts with AI posts shown; Posts starts from what the site's own switch was * set to (see {@link adoptSiteAiChoice}). */ function aiChoiceIn(scope) { return readState().hide[scope] ?? false; } /** * Keeps what the site's switch was set to as the choice of Posts, once, before * the script starts moving the switch for the other parts. */ function adoptSiteAiChoice() { const state = readState(); if (state.hide["posts"] === void 0) writeState({ ...state, hide: { ...state.hide, [AI_SCOPE_POSTS]: readSiteAiFilter() === true } }); } /** True when AI posts are hidden in this part: by the settings, or by its own choice. */ function aiHiddenIn(scope) { return aiHiddenEverywhere() || aiChoiceIn(scope); } function setAiHiddenIn(scope, hide) { const state = readState(); writeState({ ...state, hide: { ...state.hide, [scope]: hide } }); } function aiModeIn(scope) { return aiHiddenIn(scope) ? AI_MODE_HIDE : AI_MODE_SHOW; } var SORT_PREFIX$1 = "sort:"; var SCORE_PREFIX = "score:"; var MEDIA_TOKENS = /* @__PURE__ */ new Set(["video", "-video"]); /** The query without what the controls of the sidebar add to it: order, least score, type. */ function withoutToolTokens(tagsParam) { return tagsParam.trim().toLowerCase().split(/\s+/).filter((token) => token.length > 0 && !token.startsWith(SORT_PREFIX$1) && !token.startsWith(SCORE_PREFIX) && !MEDIA_TOKENS.has(token)); } function sameTokens(left, right) { if (left.length !== right.length) return false; const set = new Set(left); return right.every((token) => set.has(token)); } /** * The part of the site a list of posts belongs to, by its query: the feed, one * followed tag (what a card of Following opens), a saved search, or Posts. A * saved search opened from its card carries a mark in the address; the mark is * gone on the next page of the result, so the query is compared too. */ function listScope(tagsParam, hash, data) { if (readDynamicCollectionMark(hash) !== null) return AI_SCOPE_COLLECTIONS; const tokens = withoutToolTokens(tagsParam); if (tokens.length === 0) return AI_SCOPE_POSTS; const query = tokens.join(" "); const artists = [...data.artistTags]; if (isFullUpdatesQuery(query, artists) || isPartialUpdatesQuery(query, artists) || findFeedGroupIndex(query, artists, data.groupSize) >= 0) return AI_SCOPE_FEED; const only = tokens[0]; if (tokens.length === 1 && only !== void 0) { const followed = /* @__PURE__ */ new Set(); for (const raw of artists) { const tag = normalizeArtistTag(raw); if (tag !== null) followed.add(tag); } if (followed.has(only)) return AI_SCOPE_FOLLOWING; } for (const saved of data.savedQueries) { const savedTokens = withoutToolTokens(saved); if (savedTokens.length > 0 && sameTokens(savedTokens, tokens)) return AI_SCOPE_COLLECTIONS; } return AI_SCOPE_POSTS; } function scopeData() { const data = loadRecent(); return { artistTags: data.artists.map((entry) => entry.tag), groupSize: getUpdatesGroupSize(), savedQueries: data.collections.filter((collection) => collection.kind === COLLECTION_KIND_SEARCH).map((collection) => serialize(collection.tags)) }; } /** The part a list address belongs to, or null when the address is not a list of posts. */ function scopeOfListUrl(url) { if (detectPageKind(url.search) !== "list") return null; return listScope(url.searchParams.get("tags") ?? "", url.hash, scopeData()); } /** The part the page being shown belongs to, when it is a list of posts. */ function currentListScope() { return scopeOfListUrl(new URL(window.location.href)); } /** * Puts the site's switch the way `scope` wants it. Returns true when it had * to be changed: a list already on the page was then given with the other * setting. Favorites is not the site's to filter, and is left alone. */ function alignSiteAiFilter(scope) { if (scope === "favorites") return false; try { const want = aiHiddenIn(scope); const have = readSiteAiFilter(); if (have === want || have === null && !want) return false; writeSiteAiFilter(want); return true; } catch (error) { log.warn("ai-scope: the site's AI switch was not set", error); return false; } } /** * Runs one request to the site with its switch set for `scope`, then puts the * switch back. For a request made from a page of another part: the counter * beside Feed is read from any page. The switch is put back only when the * answer has come, because the browser reads the cookie after `fetch` returns. */ async function withSiteAiFilter(scope, run) { const before = readSiteAiFilter(); const changed = alignSiteAiFilter(scope); try { return await run(); } finally { if (changed) writeSiteAiFilter(before === true); } } var TOGGLE_CLASS$1 = "rdw-ai-toggle"; var TOGGLE_LABEL_CLASS = "rdw-ai-toggle__label"; var NOTE_CLASS$2 = "rdw-ai-note"; var NOTE_LINK_CLASS = "rdw-ai-note__link"; /** Short, before the two options: the toolbar it stands in has no room for a caption. */ var TOGGLE_PREFIX = "AI"; var TOGGLE_ARIA = "AI posts"; var NOTE_TEXT = "Hidden everywhere."; var NOTE_LINK = "Change in Settings"; var AI_CONTROL_CSS = ` .${TOGGLE_CLASS$1} { display: inline-flex; align-items: center; gap: 6px; } .${TOGGLE_LABEL_CLASS} { font: 600 10.5px var(--rdw-font); letter-spacing: 0.06em; text-transform: uppercase; color: var(--rdw-muted); } .${NOTE_CLASS$2} { margin: 4px 0 0; color: var(--rdw-muted); font: 11.5px/1.35 var(--rdw-font); } .${NOTE_CLASS$2}[data-inline="true"] { margin: 0; white-space: nowrap; } .${NOTE_LINK_CLASS} { padding: 0; border: 0; background: none; color: var(--rdw-accent); font: inherit; text-decoration: underline; cursor: pointer; } `; /** * Says why the "AI posts" control beside it cannot be changed, and takes the * user to where it can: the Page block of the settings. */ function AiEverywhereNote(props) { return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: AI_CONTROL_CSS }), /* @__PURE__ */ a("p", { className: NOTE_CLASS$2, "data-inline": props.inline === true ? "true" : void 0, children: [ NOTE_TEXT, " ", /* @__PURE__ */ a("button", { type: "button", className: `${NOTE_LINK_CLASS} rdw-kit-focusable`, onClick: () => { openSettingsAt("ai"); }, children: NOTE_LINK }) ] })] }); } /** * The choice of one part of the site for AI posts, for the toolbar of an own * page: what is opened from this page, and what the page reads from the site, * is given with AI posts shown or hidden. The same two options as everywhere * else, with "AI" before them in place of a caption. */ function AiPostsToggle(props) { const everywhere = aiHiddenEverywhere(); const [mode, setMode] = d(() => aiModeIn(props.scope)); return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("style", { children: AI_CONTROL_CSS }), /* @__PURE__ */ a("span", { className: TOGGLE_CLASS$1, children: [/* @__PURE__ */ a("span", { className: TOGGLE_LABEL_CLASS, "aria-hidden": "true", children: TOGGLE_PREFIX }), /* @__PURE__ */ a(Segmented, { label: TOGGLE_ARIA, options: AI_MODE_OPTIONS, value: everywhere ? AI_MODE_HIDE : mode, disabled: everywhere, onChange: (value) => { if (value !== "show" && value !== "hide") return; setAiHiddenIn(props.scope, value === AI_MODE_HIDE); alignSiteAiFilter(props.scope); setMode(value); } })] }), everywhere ? /* @__PURE__ */ a(AiEverywhereNote, { inline: true }) : null ] }); } /** * Readers for a results page (`page=post&s=list`): the live document or one * parsed from a fetched page. They only read; nothing here makes a request. */ var QUERY_MARK = "?"; var PID_PATTERN = /^\d+$/; var EXCLUDE_MARK = "-"; var FILTER_MARK$1 = ":"; var OR_MARKS = [ "(", ")", "~" ]; var NON_DIGITS = /\D/g; var TOKEN_SPLIT$3 = /\s+/; var SCORE_TOKEN_PREFIX$4 = "score:"; var RATING_TOKEN_PREFIX$3 = "rating:"; /** Thumb URLs of the first `limit` posts in the grid, in page order. */ function readFirstThumbUrls(root, limit) { const imageList = root.querySelector(SITE_SELECTORS.imageList); if (imageList === null) return []; const urls = []; const images = imageList.querySelectorAll(`${SITE_SELECTORS.thumb} ${SITE_SELECTORS.previewImage}`); for (const image of images) { const src = image.getAttribute("src"); if (src === null || src.trim().length === 0) continue; urls.push(src.trim()); if (urls.length === limit) break; } return urls; } /** Largest post id among the thumbs of the grid, or 0 without thumbs. */ function readNewestPostId(root) { let newest = 0; for (const thumb of root.querySelectorAll(SITE_SELECTORS.thumb)) { const raw = extractPostIdFromThumb(thumb); const id = raw === null ? NaN : Number(raw); if (Number.isFinite(id) && id > newest) newest = id; } return newest; } /** Tags of a thumb, from its preview image title, without score and rating. */ function readThumbTags(thumb) { const image = thumb.querySelector(SITE_SELECTORS.previewImage); const title = image?.getAttribute("title")?.trim() ?? ""; const text = title.length > 0 ? title : image?.getAttribute("alt")?.trim() ?? ""; const tags = []; for (const token of text.split(TOKEN_SPLIT$3)) { const lower = token.toLowerCase(); if (token.length === 0 || lower.startsWith(SCORE_TOKEN_PREFIX$4) || lower.startsWith(RATING_TOKEN_PREFIX$3)) continue; tags.push(lower); } return tags; } function readPidFromLink(link) { const href = link.getAttribute("href"); if (href === null) return null; const query = href.slice(href.indexOf(QUERY_MARK) + 1); const raw = new URLSearchParams(query).get("pid"); if (raw === null || !PID_PATTERN.test(raw)) return null; return Number(raw); } /** The tag of a search that is exactly one plain tag, else null. */ function readSingleTag(tagsParam) { const tokens = withoutSortRandom(tagsParam).split(" "); const tag = tokens[0]; if (tokens.length !== 1 || tag === void 0 || tag.length === 0) return null; if (tag.startsWith(EXCLUDE_MARK) || tag.includes(FILTER_MARK$1) || OR_MARKS.includes(tag)) return null; return tag.toLowerCase(); } function rowLinksToTag(row, tag) { for (const link of row.querySelectorAll("a[href]")) { const href = link.getAttribute("href") ?? ""; const mark = href.indexOf(QUERY_MARK); if (mark < 0) continue; const linked = new URLSearchParams(href.slice(mark + 1)).get(SEARCH_PARAM_TAGS); if (linked !== null && linked.trim().toLowerCase() === tag) return true; } return false; } /** * For a search of one tag the sidebar row of that tag shows the site's own * total, which is exact. Null when the row or its number is not on the page. */ function readSingleTagCount(root, tagsParam) { const tag = readSingleTag(tagsParam); if (tag === null) return null; for (const row of root.querySelectorAll(SITE_SELECTORS.tagSidebarRow)) { if (!rowLinksToTag(row, tag)) continue; const digits = (row.querySelector(SITE_SELECTORS.tagCount)?.textContent ?? "").replace(NON_DIGITS, ""); if (digits.length === 0) return null; return { value: Number(digits), exact: true }; } return null; } /** * Size of the search a first results page shows. * A search of one tag takes the exact total from the tag's sidebar row. * With a last-page link: at least its offset (`pid`), so the count is a lower * bound. With other page links only: the largest offset among them. With no * page links: the number of thumbs on the page, exact. No grid: null. */ function readResultCount(root, tagsParam) { const tagCount = readSingleTagCount(root, tagsParam); if (tagCount !== null) return tagCount; const last = root.querySelector(SITE_SELECTORS.paginationLastPage); if (last !== null) { const pid = readPidFromLink(last); if (pid !== null) return { value: pid, exact: false }; } let largest = null; for (const link of root.querySelectorAll(SITE_SELECTORS.paginationPageLink)) { const pid = readPidFromLink(link); if (pid !== null && (largest === null || pid > largest)) largest = pid; } if (largest !== null) return { value: largest, exact: false }; const imageList = root.querySelector(SITE_SELECTORS.imageList); if (imageList === null) return null; return { value: imageList.querySelectorAll(SITE_SELECTORS.thumb).length, exact: true }; } var EVENT_KEYDOWN$4 = "keydown"; var KEY_ESCAPE$5 = "Escape"; var ARIA_TRUE = "true"; /** Where Escape belongs to what is under the caret or open, not to the page. */ var OWN_ESCAPE_SELECTOR = [ "input", "textarea", "select", "[role=\"dialog\"]", "[role=\"listbox\"]", "[role=\"menu\"]" ].join(", "); /** True when Escape was pressed in something that takes it itself: a field, an open list, a dialog. */ function takenElsewhere(event) { if (event.defaultPrevented) return true; const origin = event.composedPath()[0]; if (!(origin instanceof Element)) return false; return origin.closest(OWN_ESCAPE_SELECTOR) !== null || origin.getAttribute("aria-expanded") === ARIA_TRUE; } /** * Runs `onEscape` when Escape is pressed while `active`: the way out of a * mode of the page, such as selecting posts. A dialog takes the key before it * gets here; a field, an open list or a menu keep it too. */ function useEscape(active, onEscape) { const latest = T(onEscape); latest.current = onEscape; A(() => { if (!active) return; const onKeyDown = (event) => { if (event.key !== KEY_ESCAPE$5 || takenElsewhere(event)) return; latest.current(); }; document.addEventListener(EVENT_KEYDOWN$4, onKeyDown); return () => { document.removeEventListener(EVENT_KEYDOWN$4, onKeyDown); }; }, [active]); } var AUTOCOMPLETE_PATH = "/public/autocomplete.php"; var AUTOCOMPLETE_TAG_TYPE_ARTIST = exports("cW","artist"); var HTTP_TOO_MANY_REQUESTS$1 = 429; var ABORT_ERROR_NAME = "AbortError"; var AutocompleteResponseSchema = /* @__PURE__ */ array(/* @__PURE__ */ object({ label: /* @__PURE__ */ string(), value: /* @__PURE__ */ string(), type: /* @__PURE__ */ optional(/* @__PURE__ */ nullable(/* @__PURE__ */ string())) })); function buildAutocompleteUrl(query) { const params = new URLSearchParams(); params.set("q", query); return `${SITE_ORIGIN}${AUTOCOMPLETE_PATH}?${params.toString()}`; } function isAbortError$2(error) { if (error instanceof DOMException && error.name === ABORT_ERROR_NAME) return true; if (typeof error !== "object" || error === null || !("name" in error)) return false; return error.name === ABORT_ERROR_NAME; } function normalizeItems(raw) { rememberTagKinds(raw.map((item) => [item.value, item.type ?? void 0])); const result = []; for (const item of raw) { const type = item.type === null || item.type === void 0 ? void 0 : item.type; if (type === void 0) result.push({ label: item.label, value: item.value }); else result.push({ label: item.label, value: item.value, type }); } return result; } /** Artists (or another preferred type) first; relative order otherwise preserved. */ function preferSuggestionType(items, preferType) { const preferred = []; const rest = []; for (const item of items) if (item.type === preferType) preferred.push(item); else rest.push(item); return [...preferred, ...rest]; } /** * GET /public/autocomplete.php?q=… (site redirects to ac.rule34.xxx). * Short queries and failed/429 responses return []. Aborts are silent. */ async function fetchAutocomplete(query, signal) { const trimmed = query.trim(); if (trimmed.length < 2) return []; let response; try { const init = { method: "GET", credentials: FETCH_CREDENTIALS }; if (signal !== void 0) init.signal = signal; response = await fetch(buildAutocompleteUrl(trimmed), init); } catch (error) { if (isAbortError$2(error) || signal?.aborted === true) return []; log.error("autocomplete: fetch failed", error); return []; } if (response.status === HTTP_TOO_MANY_REQUESTS$1) { log.warn("autocomplete: rate limited", response.status); return []; } if (!response.ok) { log.warn("autocomplete: HTTP error", response.status); return []; } let json; try { json = await response.json(); } catch (error) { if (isAbortError$2(error) || signal?.aborted === true) return []; log.error("autocomplete: invalid JSON", error); return []; } const parsed = AutocompleteResponseSchema.safeParse(json); if (!parsed.success) { log.error("autocomplete: schema mismatch", parsed.error); return []; } return normalizeItems(parsed.data); } /** * Debounced autocomplete with AbortController cancellation of the prior request. * Queries shorter than {@link AUTOCOMPLETE_MIN_CHARS} resolve to [] without a network call. */ function createAutocompleteQuerier(options = {}) { let timer = null; let controller = null; const preferType = options.preferType; const cancel = () => { if (timer !== null) { clearTimeout(timer); timer = null; } if (controller !== null) { controller.abort(); controller = null; } }; const query = (text, onResult) => { cancel(); const trimmed = text.trim(); if (trimmed.length < 2) { onResult([]); return; } timer = setTimeout(() => { timer = null; const next = new AbortController(); controller = next; fetchAutocomplete(trimmed, next.signal).then((items) => { if (next.signal.aborted) return; if (controller === next) controller = null; onResult(preferType === void 0 ? items : preferSuggestionType(items, preferType)); }); }, 300); }; return { query, cancel }; } /** `sort:random`, `score:>=10`, `id:>5`: a filter, not a tag name. */ var FILTER_MARK$2 = ":"; var TRAILING_SPACE = /\s$/; var LAST_TOKEN = /(\S+)$/; var SYNTAX_TOKENS = [ "(", ")", "~" ]; /** * The tag the caret is on, taken as the last token of the query. * Null when the query ends with whitespace or the token is search syntax * (`(`, `)`, `~`) or a filter such as `sort:random`. */ function readLastQueryToken(query) { if (query.length === 0 || TRAILING_SPACE.test(query)) return null; const match = LAST_TOKEN.exec(query); const token = match?.[1]; if (match === null || token === void 0) return null; if (SYNTAX_TOKENS.includes(token) || token.includes(FILTER_MARK$2)) return null; const prefix = token.startsWith("-") && token.length > 1 ? "-" : ""; const stem = token.slice(prefix.length); if (stem === "-") return null; return { head: query.slice(0, match.index), prefix, stem }; } /** Query with its last token replaced by `tag`, ready for the next token. */ function completeLastQueryToken(query, tag) { const last = readLastQueryToken(query); if (last === null) return `${query}${tag} `; return `${last.head}${last.prefix}${tag} `; } /** * Search-query input with the site tag autocomplete on the token being typed. * Requests go out only while the user types, debounced, one at a time * (see {@link createAutocompleteQuerier}). */ function QueryField(props) { const querierRef = T(createAutocompleteQuerier()); const [suggestions, setSuggestions] = d([]); A(() => { const querier = querierRef.current; return () => { querier.cancel(); }; }, []); const clearSuggestions = () => { querierRef.current.cancel(); setSuggestions([]); }; const onTyped = (value) => { props.onChange(value); const last = readLastQueryToken(value); if (last === null) { clearSuggestions(); return; } querierRef.current.query(last.stem, setSuggestions); }; const onPicked = (option) => { props.onChange(completeLastQueryToken(props.value, option.value)); clearSuggestions(); }; return /* @__PURE__ */ a(AutocompleteField, { ...props.label === void 0 ? {} : { label: props.label }, ...props.placeholder === void 0 ? {} : { placeholder: props.placeholder }, ...props.id === void 0 ? {} : { id: props.id }, value: props.value, suggestions, replaceOnSelect: false, onChange: onTyped, onSelect: onPicked }); }var COOKIE_PAIR_SEPARATOR = ";"; var COOKIE_NAME_VALUE_SEPARATOR$1 = "="; var BLACKLIST_SPLIT_PATTERN = /[, ]|%20+/g; var USER_ENTRY_PREFIX = "user:"; var RATING_ENTRY_PREFIX = "rating:"; var MS_PER_DAY$2 = 864e5; var DAYS_PER_YEAR = 365; var BLACKLIST_TAG_SEPARATOR = " "; var changeListeners = /* @__PURE__ */ new Set(); /** Subscribe to writes of the site `tag_blacklist` cookie. */ function onSiteBlacklistChange(cb) { changeListeners.add(cb); return () => { changeListeners.delete(cb); }; } function readCookieValue(name) { const pairs = document.cookie.split(COOKIE_PAIR_SEPARATOR); const prefix = `${name}${COOKIE_NAME_VALUE_SEPARATOR$1}`; for (const pair of pairs) { const trimmed = pair.trim(); if (!trimmed.startsWith(prefix)) continue; return trimmed.slice(prefix.length); } return null; } function normalizeBlacklistTags(tags) { const seen = /* @__PURE__ */ new Set(); const result = []; for (const raw of tags) { const normalized = raw.trim().toLowerCase().replaceAll(" ", "_"); if (normalized.length === 0 || seen.has(normalized)) continue; seen.add(normalized); result.push(normalized); } return result; } function encodeBlacklistCookieValue(tags) { if (tags.length === 0) return ""; return encodeURIComponent(encodeURIComponent(tags.join(BLACKLIST_TAG_SEPARATOR))); } function writeBlacklistCookie(value, expires) { document.cookie = [ `${SITE_BLACKLIST_COOKIE_NAME}${COOKIE_NAME_VALUE_SEPARATOR$1}${value}`, `expires=${expires.toUTCString()}`, `path=/` ].join("; "); } /** * Reads the site `tag_blacklist` cookie using the site's decode + split rule. * Empty tokens are dropped; entries are lowercased. */ function readSiteBlacklist() { const raw = readCookieValue(SITE_BLACKLIST_COOKIE_NAME); if (raw === null || raw.length === 0) return []; let decoded; try { decoded = decodeURIComponent(decodeURI(raw)); } catch { return []; } const result = []; for (const part of decoded.split(BLACKLIST_SPLIT_PATTERN)) { const trimmed = part.trim().toLowerCase(); if (trimmed.length === 0) continue; result.push(trimmed); } return result; } /** * Writes the site `tag_blacklist` cookie (browser cookie only; account list untouched). * Value encoding matches the live site: encodeURIComponent twice over space-joined tags. */ function writeSiteBlacklist(tags) { const normalized = normalizeBlacklistTags(tags); const expires = new Date(Date.now() + 5 * DAYS_PER_YEAR * MS_PER_DAY$2); writeBlacklistCookie(encodeBlacklistCookieValue(normalized), expires); for (const listener of changeListeners) listener(normalized); } /** * True when any blacklist entry matches a post tag or `rating:x`. * Entries starting with `user:` are ignored. `score` is reserved for callers. */ function isBlacklisted(tags, score, rating, list) { if (list.length === 0) return false; const tagSet = /* @__PURE__ */ new Set(); for (const tag of tags) { const normalized = tag.trim().toLowerCase(); if (normalized.length > 0) tagSet.add(normalized); } const ratingNorm = rating.trim().toLowerCase(); for (const entry of list) { if (entry.startsWith(USER_ENTRY_PREFIX)) continue; if (entry.startsWith(RATING_ENTRY_PREFIX)) { const value = entry.slice(7); if (value.length > 0 && value === ratingNorm) return true; continue; } if (tagSet.has(entry)) return true; } return false; } var FEATURE_ID$20 = "blacklist-hide"; var FEATURE_LABEL$20 = "Hide blacklisted posts"; var FEATURE_PAGES$14 = ["list"]; var BODY_FEATURE_CLASS$3 = featureBodyClass(FEATURE_ID$20); var CLASS_BLACKLISTED$1 = "rdw-blacklisted"; var SCORE_TOKEN_PREFIX$3 = "score:"; var RATING_TOKEN_PREFIX$2 = "rating:"; var WHITESPACE_SPLIT = /\s+/; var FEATURE_CSS$17 = ` body.${BODY_FEATURE_CLASS$3} span.thumb.${CLASS_BLACKLISTED$1} { display: none !important; } `.trim(); var unsubscribeThumbsAdded$5; var unsubscribeBlacklistChange; function parseAltTags(alt) { const tags = []; for (const token of alt.trim().split(WHITESPACE_SPLIT)) { if (token.length === 0) continue; const lower = token.toLowerCase(); if (lower.startsWith(SCORE_TOKEN_PREFIX$3) || lower.startsWith(RATING_TOKEN_PREFIX$2)) continue; tags.push(token); } return tags; } function parseTitleRating(title) { for (const token of title.trim().split(WHITESPACE_SPLIT)) { if (token.length === 0) continue; if (token.toLowerCase().startsWith(RATING_TOKEN_PREFIX$2)) return token.slice(7); } return ""; } function applyBlacklistToThumb(thumb, list) { if (!(thumb instanceof HTMLElement)) return; const img = thumb.querySelector(SITE_SELECTORS.previewImage); const alt = img?.getAttribute("alt") ?? ""; const title = img?.getAttribute("title") ?? ""; const matched = isBlacklisted(parseAltTags(alt), 0, parseTitleRating(title), list); thumb.classList.toggle(CLASS_BLACKLISTED$1, matched); } function applyBlacklistToRoot(root, list = readSiteBlacklist()) { const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) applyBlacklistToThumb(thumb, list); } function ensureSubscriptions() { if (unsubscribeThumbsAdded$5 === void 0) unsubscribeThumbsAdded$5 = onThumbsAdded((root) => { applyBlacklistToRoot(root); }); if (unsubscribeBlacklistChange === void 0) unsubscribeBlacklistChange = onSiteBlacklistChange((list) => { applyBlacklistToRoot(document, list); }); } function mountBlacklistHide(ctx) { if (ctx.pageKind !== "list") return; applyBlacklistToRoot(document); ensureSubscriptions(); } var blacklistHideFeature = { id: FEATURE_ID$20, label: FEATURE_LABEL$20, pages: [...FEATURE_PAGES$14], defaultEnabled: true, cssOnly: true, css: FEATURE_CSS$17, mount: mountBlacklistHide }; /** * When the image of a post fails to load, tries the same file on the site's * other image servers, one after another. * * The host list comes from the desktop RuleDesk, where it served API file * addresses. A retry happens only after a real load error, at most once per * host, and only for an address on one of these hosts. */ var FEATURE_ID$19 = "cdn-fallback"; var FEATURE_LABEL$19 = "Retry a failed post image on other servers"; var FEATURE_PAGES$13 = ["post"]; var POST_IMAGE_SELECTOR$1 = "img#image"; var EVENT_ERROR = "error"; /** Image servers, in the order they are tried. */ var CDN_IMAGE_HOSTS = [ "wimg.rule34.xxx", "img.rule34.xxx", "us.rule34.xxx", "api-cdn.rule34.xxx" ]; /** * The same address on the next server that was not tried yet, or null when * the address is not on a known server or every server was tried. */ function nextCdnUrl(current, tried) { let url; try { url = new URL(current, window.location.href); } catch { return null; } if (!CDN_IMAGE_HOSTS.includes(url.hostname)) return null; for (const host of CDN_IMAGE_HOSTS) { if (host === url.hostname || tried.has(host)) continue; url.hostname = host; return url.href; } return null; } function hostOf(address) { try { return new URL(address, window.location.href).hostname; } catch { return ""; } } function mountCdnFallback(_ctx) { const image = document.querySelector(POST_IMAGE_SELECTOR$1); if (!(image instanceof HTMLImageElement)) return; const tried = /* @__PURE__ */ new Set(); image.addEventListener(EVENT_ERROR, () => { const current = image.getAttribute("src") ?? ""; tried.add(hostOf(current)); const next = nextCdnUrl(current, tried); if (next !== null) image.setAttribute("src", next); }); } var cdnFallbackFeature = { id: FEATURE_ID$19, label: FEATURE_LABEL$19, pages: [...FEATURE_PAGES$13], defaultEnabled: true, css: "", mount: mountCdnFallback }; var DEFAULT_EXTENSION = "jpg"; var EXTENSION_PATTERN = /\.([a-z0-9]{2,5})$/i; var UNKNOWN_ERROR = "unknown error"; var TIMEOUT_ERROR = "timeout"; var FOLDER_FALLBACK = "downloads"; var FOLDER_MAX_LENGTH = 60; /** Characters a file system does not take in a folder name. */ var FOLDER_FORBIDDEN = /[\\/:*?"<>|]+/g; var FOLDER_SPACES = /\s+/g; var FOLDER_EDGE = /^[. ]+|[. ]+$/g; /** * Where a job's files go, relative to the browser's download folder: a folder * named after the job (a collection name or a search), made safe for a folder * name. Where that download folder is, is the browser's own setting. */ function downloadFolder(label) { const safe = label.replace(FOLDER_FORBIDDEN, " ").replace(FOLDER_SPACES, " ").slice(0, FOLDER_MAX_LENGTH).replace(FOLDER_EDGE, ""); return safe.length > 0 ? safe : FOLDER_FALLBACK; } /** The name a file gets when no mask is set: `rule34-`. */ var DEFAULT_FILE_MASK = exports("bR","rule34-[id]"); /** What a mask may hold, in square brackets. */ var FILE_MASK_TOKENS = exports("bS",[ "id", "md5", "rating", "score", "width", "height", "owner", "date" ]); var MASK_TOKEN = /\[([a-z0-9]+)\]/gi; var NAME_FORBIDDEN = /[\\/:*?"<>|\u0000-\u001f]+/g; /** A run of separators left where a token had no value. */ var NAME_SEPARATOR_RUN = /([-_. ])[-_. ]+/g; var NAME_EDGE = /^[-_. ]+|[-_. ]+$/g; var NAME_MAX_LENGTH = 120; var DATE_LENGTH = 10; var PATH_TAIL = /([^/]+?)(?:\.[a-z0-9]{2,5})?$/i; function isFileMaskToken(value) { return FILE_MASK_TOKENS.some((token) => token === value); } function filePath(url) { try { return new URL(url, window.location.href).pathname; } catch { return url; } } function fileExtension(url) { return EXTENSION_PATTERN.exec(filePath(url))?.[1]?.toLowerCase() ?? DEFAULT_EXTENSION; } /** The site names a file by its MD5: the name in the address is the hash. */ function fileHash(url) { return PATH_TAIL.exec(filePath(url))?.[1] ?? ""; } function tokenValue(token, info, now) { switch (token) { case "id": return String(info.postId); case "md5": return fileHash(info.url); case "rating": return info.rating ?? ""; case "score": return info.score === void 0 ? "" : String(info.score); case "width": return info.width === void 0 ? "" : String(info.width); case "height": return info.height === void 0 ? "" : String(info.height); case "owner": return info.owner ?? ""; case "date": return new Date(now).toISOString().slice(0, DATE_LENGTH); } } /** * The file name a mask gives: every `[token]` is replaced by its value, what * a file system does not take is dropped, and the extension of the file is * added. A token without a value leaves nothing behind, not a stray * separator; an unknown one is dropped. A mask that comes out empty falls * back to the default name. */ function buildFileName(mask, info, now = Date.now()) { const fill = (text) => text.replace(MASK_TOKEN, (_whole, raw) => { const token = raw.toLowerCase(); return isFileMaskToken(token) ? tokenValue(token, info, now) : ""; }).replace(NAME_FORBIDDEN, " ").replace(FOLDER_SPACES, " ").replace(NAME_SEPARATOR_RUN, "$1").replace(NAME_EDGE, "").slice(0, NAME_MAX_LENGTH).replace(NAME_EDGE, ""); const base = fill(mask); return `${base.length > 0 ? base : fill(DEFAULT_FILE_MASK)}.${fileExtension(info.url)}`; } /** True when the mask holds `[token]`, in any case. */ function maskHasToken(mask, token) { return mask.toLowerCase().includes(`[${token}]`); } /** * The mask with `[token]` switched: taken out everywhere when it is there, * added at the end when it is not. A token is of use once in a name, so a * mask never ends up with two of the same. The spaces left by a token that * was taken out are closed up. */ function toggleMaskToken(mask, token) { if (!maskHasToken(mask, token)) { const text = mask.trim(); return text.length > 0 ? `${text} [${token}]` : `[${token}]`; } const pattern = new RegExp(`\\[${token}\\]`, "gi"); return mask.replace(pattern, "").replace(FOLDER_SPACES, " ").trim(); } var MEDIA_EXTENSION = /\.(?:jpe?g|png|gif|webp|avif|bmp|mp4|webm|mov|m4v)$/i; /** True when the address ends like a picture or a video, not like a page. */ function isMediaFileUrl(url) { return MEDIA_EXTENSION.test(filePath(url)); } /** False when the script manager gives no download function. */ function canDownload() { return typeof GM_download === "function"; } /** * Starts one download. Resolves when the manager reports the file saved, * rejects with a readable reason when it reports an error or a timeout. */ function downloadFile(url, name) { return new Promise((resolve, reject) => { GM_download({ url, name, headers: { Referer: `${window.location.origin}/` }, onload: () => { resolve(); }, onerror: (event) => { const reason = typeof event.error === "string" ? event.error : UNKNOWN_ERROR; reject(new Error(reason)); }, ontimeout: () => { reject(/* @__PURE__ */ new Error(TIMEOUT_ERROR)); } }); }); } /** * The user's own API credentials for the download manager. * * They are typed in by the user in settings (generated on the site's account * options page) and kept under their own key in the script manager's storage, * apart from the main data, so they never get into an export file. * Nothing else in the script uses the API. */ var API_CREDENTIALS_KEY = "ruledesk-web.api"; var ApiCredentialsSchema = object({ userId: string().check(_minLength(1)), apiKey: string().check(_minLength(1)) }); function getApiCredentials() { const parsed = ApiCredentialsSchema.safeParse(GM_getValue(API_CREDENTIALS_KEY)); return parsed.success ? parsed.data : null; } function hasApiCredentials() { return getApiCredentials() !== null; } /** Stores trimmed credentials. Returns false when either part is empty. */ function setApiCredentials(userId, apiKey) { const parsed = ApiCredentialsSchema.safeParse({ userId: userId.trim(), apiKey: apiKey.trim() }); if (!parsed.success) return false; GM_setValue(API_CREDENTIALS_KEY, parsed.data); return true; } function clearApiCredentials() { GM_setValue(API_CREDENTIALS_KEY, null); } var USER_ID_PARAM = /(?:^|[?&\s])user_id=([^&\s#]+)/i; var API_KEY_PARAM = /(?:^|[?&\s])api_key=([^&\s#]+)/i; function decodePart(raw) { try { return decodeURIComponent(raw); } catch { return raw; } } /** * Splits the line the site shows on its account options page, * `&api_key=KEY&user_id=123`, into its two parts. The order of the parts and * anything around them (a full address, spaces) do not matter. * Null when either part is missing. */ function parseApiCredentials(text) { const userId = USER_ID_PARAM.exec(text)?.[1]; const apiKey = API_KEY_PARAM.exec(text)?.[1]; if (userId === void 0 || apiKey === void 0) return null; const parsed = ApiCredentialsSchema.safeParse({ userId: decodePart(userId).trim(), apiKey: decodePart(apiKey).trim() }); return parsed.success ? parsed.data : null; } /** Id of the download manager among the page tweaks. */ var DOWNLOADS_FEATURE_ID = "downloads"; /** * True when download buttons may be shown: the manager is switched on, the * script manager can download, and the user has put an API key into settings. Without a key there is no download manager at all. */ function downloadsAvailable() { return getTweaksEnabled() && getFeatureEnabled("downloads", true) && canDownload() && hasApiCredentials(); } var EVENT_MOUSEDOWN = "mousedown"; var EVENT_CLICK$3 = "click"; var EVENT_DRAGSTART = "dragstart"; var MAIN_BUTTON = 0; /** `detail` of a click that no press of the mouse made: Enter on a link, a script. */ var NO_PRESS = 0; /** * Marks a post at the press of the mouse button, not at its release. * * A click is a press and a release on the same element with no drag between * them. A thumbnail is a picture in a link, and both drag: a pointer that * moves a little while the button is down starts a drag, and the click never * comes. So posts clicked in passing were not marked. The press marks the * post at once and does not let a drag start; the click that follows is only * kept from opening the post. A click that no press made (the keyboard) marks. * * Returns the function that takes the listeners away. */ function bindPressSelect(resolve) { const actionFor = (event) => { const target = event.target; return target instanceof Element ? resolve(target) : null; }; const onMouseDown = (event) => { if (event.button !== MAIN_BUTTON) return; const action = actionFor(event); if (action === null) return; event.preventDefault(); event.stopPropagation(); action(); }; const onClick = (event) => { const action = actionFor(event); if (action === null) return; event.preventDefault(); event.stopPropagation(); if (event.detail === NO_PRESS) action(); }; const onDragStart = (event) => { if (actionFor(event) !== null) event.preventDefault(); }; document.addEventListener(EVENT_MOUSEDOWN, onMouseDown, true); document.addEventListener(EVENT_CLICK$3, onClick, true); document.addEventListener(EVENT_DRAGSTART, onDragStart, true); return () => { document.removeEventListener(EVENT_MOUSEDOWN, onMouseDown, true); document.removeEventListener(EVENT_CLICK$3, onClick, true); document.removeEventListener(EVENT_DRAGSTART, onDragStart, true); }; } /** * Picking posts on a results page, to add them to a collection or to download * them. While it is on, a click on a thumbnail marks the post instead of opening it. Only a class on * `span.thumb` changes; nothing inside the post link is touched. */ var GRID_SELECT_BODY_CLASS = "rdw-dl-select"; var GRID_SELECTED_CLASS = "rdw-dl-selected"; var GRID_SELECT_CSS = ` body.${GRID_SELECT_BODY_CLASS} ${SITE_SELECTORS.thumb} { cursor: pointer; } /* While posts are being marked a thumbnail does not lift under the pointer ("Motion" in the settings): lifted, it stands out of the frame of a marked post. */ body.${GRID_SELECT_BODY_CLASS} ${SITE_SELECTORS.thumb}:hover img { transform: none !important; } body.${GRID_SELECT_BODY_CLASS} ${SITE_SELECTORS.thumb}.${GRID_SELECTED_CLASS} { outline: 3px solid var(--rdw-accent); outline-offset: -3px; border-radius: var(--rdw-radius-m); } /* A tick as well: the outline alone would mark a post by colour only. */ body.${GRID_SELECT_BODY_CLASS} ${SITE_SELECTORS.thumb}.${GRID_SELECTED_CLASS} { position: relative; } body.${GRID_SELECT_BODY_CLASS} ${SITE_SELECTORS.thumb}.${GRID_SELECTED_CLASS}::after { content: "✓"; position: absolute; left: 6px; bottom: 6px; z-index: 2; display: grid; place-items: center; width: 20px; height: 20px; border-radius: 999px; background: var(--rdw-accent); color: var(--rdw-surface); font: 700 12px/1 var(--rdw-font); pointer-events: none; } `.trim(); var STYLE_ID$2 = "rdw-grid-select-style"; /** * Selecting works without the download manager too, so the styles are put in * when selecting starts and do not depend on that feature's stylesheet. */ function ensureStyle$2() { if (document.getElementById(STYLE_ID$2) !== null) return; const style = document.createElement("style"); style.id = STYLE_ID$2; style.textContent = GRID_SELECT_CSS; document.head.append(style); } var onCountChange = null; /** Ids of the marked posts, in page order. */ function readSelectedPostIds() { const ids = []; for (const thumb of document.querySelectorAll(`${SITE_SELECTORS.thumb}.${GRID_SELECTED_CLASS}`)) { const raw = extractPostIdFromThumb(thumb); const id = raw === null ? NaN : Number(raw); if (Number.isFinite(id)) ids.push(id); } return ids; } /** What a press does: marks the post under it; a press on a button of the thumb is the button's. */ function pressOnGrid(target) { const thumb = target.closest(SITE_SELECTORS.thumb); if (thumb === null || target.closest("button") !== null) return null; return () => { thumb.classList.toggle(GRID_SELECTED_CLASS); onCountChange?.(readSelectedPostIds().length); }; } var unbindPress = null; /** The marked posts with the address of their preview, in page order. */ function readSelectedPosts(readThumbUrl) { const posts = []; for (const thumb of document.querySelectorAll(`${SITE_SELECTORS.thumb}.${GRID_SELECTED_CLASS}`)) { const raw = extractPostIdFromThumb(thumb); const id = raw === null ? NaN : Number(raw); if (raw !== null && Number.isFinite(id) && thumb instanceof HTMLElement) posts.push({ id, thumbUrl: readThumbUrl(thumb, raw) }); } return posts; } /** Marks every post of the page. */ function selectGridPage() { for (const thumb of document.querySelectorAll(SITE_SELECTORS.thumb)) if (extractPostIdFromThumb(thumb) !== null) thumb.classList.add(GRID_SELECTED_CLASS); onCountChange?.(readSelectedPostIds().length); } /** Takes every mark off; picking stays on. */ function clearGridSelection() { for (const thumb of document.querySelectorAll(`.${GRID_SELECTED_CLASS}`)) thumb.classList.remove(GRID_SELECTED_CLASS); onCountChange?.(0); } function isGridSelecting() { return document.body.classList.contains(GRID_SELECT_BODY_CLASS); } /** Turns picking on. `onChange` gets the number of marked posts after each click. */ function startGridSelect(onChange) { if (isGridSelecting()) return; ensureStyle$2(); onCountChange = onChange; document.body.classList.add(GRID_SELECT_BODY_CLASS); unbindPress = bindPressSelect(pressOnGrid); } /** Turns picking off and clears the marks. */ function stopGridSelect() { unbindPress?.(); unbindPress = null; document.body.classList.remove(GRID_SELECT_BODY_CLASS); for (const thumb of document.querySelectorAll(`.${GRID_SELECTED_CLASS}`)) thumb.classList.remove(GRID_SELECTED_CLASS); onCountChange = null; } /** * Which addresses belong to the site. Addresses that come from outside the * script (an API answer, an imported file) are checked with this before the * browser is asked to load or save them. */ var SITE_DOMAIN = "rule34.xxx"; var HTTPS_PROTOCOL$1 = "https:"; /** True for an `https` address on the site's domain or one of its subdomains. */ function isSiteUrl(address) { let url; try { url = new URL(address); } catch { return false; } return url.protocol === HTTPS_PROTOCOL$1 && (url.hostname === SITE_DOMAIN || url.hostname.endsWith(`.${SITE_DOMAIN}`)); } /** * The site API, used for one thing only: finding the original files of posts * for the download manager. It works with the user's own key from settings * and is never called without one. * * A search is answered a thousand posts a request. A list of posts is not: * the API has no "or" for ids (docs/site.md has what was tried), so posts * named by id cost one request each. */ var API_URL = "https://api.rule34.xxx/index.php"; var POSTS_PER_REQUEST = 1e3; /** Pause between two API requests of one collection run. */ var API_REQUEST_INTERVAL_MS = 1e3; var FETCH_NO_CREDENTIALS = "omit"; var ERROR_TEXT_LIMIT = 120; var SORT_TOKEN_PREFIX$1 = "sort:"; var ID_BELOW_PREFIX = "id:<"; var TOKEN_SPLIT$2 = /\s+/; var ALL_QUERY = "all"; function sleep$3(ms) { return new Promise((resolve) => { window.setTimeout(resolve, ms); }); } var ApiPostSchema = object({ id: int(), file_url: string().check(_minLength(1)), rating: optional(unknown()), score: optional(unknown()), width: optional(unknown()), height: optional(unknown()), owner: optional(unknown()) }); function textOf(value) { return typeof value === "string" && value.length > 0 ? value : void 0; } function numberOf(value) { const number = typeof value === "string" ? Number(value) : value; return typeof number === "number" && Number.isFinite(number) ? number : void 0; } function buildApiUrl(query, credentials) { const params = new URLSearchParams(); params.set("page", "dapi"); params.set("s", "post"); params.set("q", "index"); params.set("json", "1"); params.set("limit", String(POSTS_PER_REQUEST)); params.set("pid", "0"); if ("id" in query) params.set("id", String(query.id)); else if (query.tags.length > 0 && query.tags !== ALL_QUERY) params.set("tags", query.tags); params.set("user_id", credentials.userId); params.set("api_key", credentials.apiKey); return `${API_URL}?${params.toString()}`; } /** * The limit of the API is per key: 60 requests in 60 seconds (its own page * says so; Kaze, 17.11.2026). Every request of the script goes through * `requestText`, and that is where the limit is kept, whatever asks and from * whichever tab: * * - requests of one tab go one after another, never two at once; * - a request starts no sooner than {@link API_MIN_INTERVAL_MS} after the * one before it, counted across the tabs of the browser through a time * kept in localStorage (downloads in two tabs share the key); * - an answer of "too many requests" is waited out and asked again a few * times before the run fails. */ var API_MIN_INTERVAL_MS = 1100; /** How long to wait after "too many requests" before asking again. */ var API_LIMIT_PAUSE_MS = 15e3; var HTTP_TOO_MANY_REQUESTS = 429; /** When the last API request of any tab started, ms since epoch. */ var API_LAST_REQUEST_KEY = "ruledesk-web.api-last"; var lastRequestAt = 0; var turn = Promise.resolve(); function readSharedLast() { try { const stored = Number(window.localStorage.getItem(API_LAST_REQUEST_KEY)); return Number.isFinite(stored) ? stored : 0; } catch { return 0; } } function writeSharedLast(at) { try { window.localStorage.setItem(API_LAST_REQUEST_KEY, String(at)); } catch {} } /** Resolves when this request may start; the requests of the tab queue up here. */ function takeTurn() { const mine = turn.then(async () => { const now = Date.now(); const shared = Math.min(readSharedLast(), now); const wait = Math.max(lastRequestAt, shared) + API_MIN_INTERVAL_MS - now; if (wait > 0) await sleep$3(wait); lastRequestAt = Date.now(); writeSharedLast(lastRequestAt); }); turn = mine.catch(() => void 0); return mine; } /** * One API request. The API allows requests from any page * (`access-control-allow-origin: *`), so a plain `fetch` does it; no cookies * are sent, the key in the address is the whole authentication. */ async function requestText(query, credentials) { for (let attempt = 0;; attempt += 1) { await takeTurn(); const response = await fetch(buildApiUrl(query, credentials), { method: "GET", credentials: FETCH_NO_CREDENTIALS }); if (response.status === HTTP_TOO_MANY_REQUESTS && attempt < 3) { await sleep$3(API_LIMIT_PAUSE_MS); continue; } if (!response.ok) throw new Error(`API HTTP ${String(response.status)}`); return response.text(); } } /** * Posts of one API answer. An empty body is an empty result. A body that is * not a list (the API answers a wrong key with a sentence) is an error whose * text is shown to the user. */ function parseApiPosts(body) { const text = body.trim(); if (text.length === 0) return []; let raw; try { raw = JSON.parse(text); } catch { throw new Error(`API: ${text.slice(0, ERROR_TEXT_LIMIT)}`); } if (typeof raw === "string") throw new Error(`API: ${raw.slice(0, ERROR_TEXT_LIMIT)}`); if (!Array.isArray(raw)) throw new Error(`API: ${text.slice(0, ERROR_TEXT_LIMIT)}`); const files = []; for (const item of raw) { const parsed = ApiPostSchema.safeParse(item); if (parsed.success && isSiteUrl(parsed.data.file_url)) files.push({ postId: parsed.data.id, url: parsed.data.file_url, rating: textOf(parsed.data.rating), score: numberOf(parsed.data.score), width: numberOf(parsed.data.width), height: numberOf(parsed.data.height), owner: textOf(parsed.data.owner) }); } return files; } /** The search without sort tokens: the walk below needs newest-first order. */ function queryForWalk(tags) { return tags.trim().split(TOKEN_SPLIT$2).filter((token) => token.length > 0 && !token.startsWith(SORT_TOKEN_PREFIX$1)).join(" "); } /** * Every post of a search. The API stops answering deep page numbers, so the * walk asks for the first page again and again with `id: part.length > 0).join(" ") }, options.credentials)); if (batch.length === 0) return files; let lowest = batch[0]?.postId ?? 0; for (const file of batch) { files.push(file); lowest = Math.min(lowest, file.postId); } options.onProgress(files.length); if (below !== null && lowest >= below) return files; below = lowest; await sleep$3(API_REQUEST_INTERVAL_MS); } } /** * The given posts, in the order of `ids`, one request a post through the `id` * parameter. (They used to be asked for a hundred at a time as one * `( id:1 ~ id:2 … )` search first; the API answers such a search with * nothing, so that was one wasted request in every hundred.) A post the API * does not return, a deleted one, is left out. */ async function collectIds(ids, options) { const files = []; for (const id of ids) { if (options.isCancelled()) break; const found = parseApiPosts(await requestText({ id }, options.credentials)); const file = found.find((item) => item.postId === id) ?? found[0]; if (file !== void 0) files.push(file); options.onProgress(files.length); } return files; } /** Finds the original files of everything a source names. */ function collectPostFiles(source, options) { return source.kind === "query" ? collectQuery(source.tags, options) : collectIds(source.ids, options); } /** * The mask saved files are named by (RuleDesk → Downloads → File name), kept * with the settings. See `buildFileName` for what a mask may hold. */ var FILE_MASK_STATE_ID = "download-name"; function readFileMask() { const stored = getFeatureState(FILE_MASK_STATE_ID); return typeof stored === "string" && stored.trim().length > 0 ? stored : DEFAULT_FILE_MASK; } /** Saves the mask; an empty one returns to the default name. */ function writeFileMask(mask) { const clean = mask.trim(); setFeatureState(FILE_MASK_STATE_ID, clean.length > 0 ? clean : DEFAULT_FILE_MASK); } /** * The download queue. One job at a time: first the files of the job are found * through the API, then they are saved one after another. * * The job is stored, so it survives a page change: the site reloads the page * on every navigation, and the tab that was downloading picks the job up * again by itself. A stored job in another tab, or after the browser was * closed, waits paused until Resume is pressed. */ var DOWNLOADS_JOB_KEY = "ruledesk-web.downloads"; var DOWNLOADS_POSITION_KEY = "ruledesk-web.downloads.position"; /** Set in the tab that runs the queue, so only that tab resumes by itself. */ var RUNNING_TAB_KEY = "ruledesk-web.downloads.running"; var RUNNING_TAB_VALUE = "1"; /** Wait before the one retry of a failed file. */ var RETRY_DELAY_MS = 5e3; var NO_FILES_MESSAGE = "The API returned no files for this. Deleted posts have none."; var JobSchema = object({ label: string(), folder: string(), selected: optional(int()), files: array(object({ postId: int(), url: string(), rating: optional(string()), score: optional(number()), width: optional(number()), height: optional(number()), owner: optional(string()) })) }); var PositionSchema = object({ next: int(), failed: array(int()) }); /** * The one pause the queue makes by itself: a stored job found in a tab that * was not the one downloading it. A tab opened after the browser was closed * is such a tab too, and the two cannot be told apart, so the words cover both. */ var PAUSED_ELSEWHERE = "started in another tab or session"; var DEFAULT_SCOPE = "all"; var IDLE = { phase: "idle", label: "", selected: null, expected: null, total: 0, done: 0, failed: 0, message: "" }; var state = IDLE; var job = null; var next = 0; var failed = []; /** Bumped on every start, pause and cancel: a loop of an older run stops. */ var runToken = 0; var listeners = /* @__PURE__ */ new Set(); function emit(nextState) { state = nextState; for (const listener of listeners) listener(state); } function sleep$2(ms) { return new Promise((resolve) => { window.setTimeout(resolve, ms); }); } function markRunningTab(running) { try { if (running) window.sessionStorage.setItem(RUNNING_TAB_KEY, RUNNING_TAB_VALUE); else window.sessionStorage.removeItem(RUNNING_TAB_KEY); } catch (error) { log.warn("downloads: session storage unavailable", error); } } function isRunningTab() { try { return window.sessionStorage.getItem(RUNNING_TAB_KEY) === RUNNING_TAB_VALUE; } catch { return false; } } function savePosition() { GM_setValue(DOWNLOADS_POSITION_KEY, { next, failed }); } function clearStored() { GM_setValue(DOWNLOADS_JOB_KEY, null); GM_setValue(DOWNLOADS_POSITION_KEY, null); markRunningTab(false); } function progress(phase, message = "") { return { phase, label: job?.label ?? state.label, selected: job === null ? state.selected : job.selected ?? null, expected: null, total: job?.files.length ?? state.total, done: next - failed.length, failed: failed.length, message }; } async function saveOne(file, folder) { const name = `${folder}/${buildFileName(readFileMask(), file)}`; try { await downloadFile(file.url, name); return true; } catch (first) { log.warn("downloads: file failed, retrying once", file.postId, first); } await sleep$2(RETRY_DELAY_MS); try { await downloadFile(file.url, name); return true; } catch (second) { log.warn("downloads: file failed", file.postId, second); return false; } } async function run() { const current = job; if (current === null) return; runToken += 1; const token = runToken; markRunningTab(true); emit(progress("running")); while (next < current.files.length) { const file = current.files[next]; if (file === void 0) break; const saved = await saveOne(file, current.folder); if (token !== runToken) return; if (!saved) failed.push(file.postId); next += 1; savePosition(); emit(progress("running")); if (next < current.files.length) { await sleep$2(400); if (token !== runToken) return; } } clearStored(); emit(progress("done")); } function getDownloadState() { return state; } function subscribeDownloads(listener) { listeners.add(listener); return () => { listeners.delete(listener); }; } /** True while a job is being collected, saved, or waits paused. */ function isDownloadBusy() { return state.phase === "collecting" || state.phase === "running" || state.phase === "paused"; } /** * Starts a job: asks the API for the files, then saves them into * the job's folder (see `downloadFolder`). Does nothing while another job is busy or when no API * key is stored. */ async function startDownload(label, source, scope = DEFAULT_SCOPE) { const credentials = getApiCredentials(); if (credentials === null || isDownloadBusy()) return; runToken += 1; const token = runToken; job = null; next = 0; failed = []; const selected = scope === "selection" && source.kind === "ids" ? source.ids.length : null; const expected = source.kind === "ids" ? source.ids.length : null; const collecting = { ...IDLE, phase: "collecting", label, selected, expected }; emit(collecting); let files; try { files = await collectPostFiles(source, { credentials, onProgress: (found) => { if (token === runToken) emit({ ...collecting, total: found }); }, isCancelled: () => token !== runToken }); } catch (error) { if (token !== runToken) return; const reason = error instanceof Error ? error.message : String(error); log.warn("downloads: collecting failed", reason); emit({ ...IDLE, phase: "error", label, selected, message: reason }); return; } if (token !== runToken) return; if (files.length === 0) { emit({ ...IDLE, phase: "error", label, selected, message: NO_FILES_MESSAGE }); return; } job = { label, folder: downloadFolder(label), files, ...selected === null ? {} : { selected } }; GM_setValue(DOWNLOADS_JOB_KEY, job); savePosition(); await run(); } /** Stops after the file in flight; the job stays stored. */ function pauseDownload() { if (state.phase !== "running") return; runToken += 1; markRunningTab(false); emit(progress("paused")); } function resumeDownload() { if (state.phase !== "paused" || job === null) return; run(); } /** Drops the job, or closes the finished one. Saved files stay. */ function cancelDownload() { runToken += 1; job = null; next = 0; failed = []; clearStored(); emit(IDLE); } /** * Call once per page load. Picks a stored job up: the tab that was running * it continues, any other tab shows it paused. */ function restoreDownloads() { if (state.phase !== "idle") return; const storedJob = JobSchema.safeParse(GM_getValue(DOWNLOADS_JOB_KEY)); if (!storedJob.success) return; const position = PositionSchema.safeParse(GM_getValue(DOWNLOADS_POSITION_KEY)); job = storedJob.data; next = position.success ? Math.min(position.data.next, job.files.length) : 0; failed = position.success ? [...position.data.failed] : []; if (isRunningTab()) { run(); return; } emit(progress("paused", PAUSED_ELSEWHERE)); } /** * The download manager's panel: a small box in the corner of every page * while a job exists. It shows what is being saved and holds Pause, Resume * and Cancel. It can be minimised into a chip with the percent, so that it * does not lie over the last column of a grid for the whole of a long job. */ var FEATURE_ID$18 = DOWNLOADS_FEATURE_ID; var FEATURE_LABEL$18 = "Download manager"; var FEATURE_PAGES$12 = [ "list", "post", "favorites", "other" ]; var DOWNLOADS_PANEL_ID = RDW_DOWNLOADS_PANEL_ID; var HEAD_CLASS = "rdw-downloads-head"; var TITLE_CLASS$4 = "rdw-downloads-title"; var TEXT_CLASS$1 = "rdw-downloads-text"; var ACTIONS_CLASS$2 = "rdw-downloads-actions"; /** On the host while the panel is a chip: the box around the chip is taken off. */ var DOWNLOADS_MINIMISED_CLASS = "rdw-downloads-minimised"; var CHIP_CLASS$1 = "rdw-downloads-chip"; /** The kit's parts of the progress bar, restyled inside the panel only. */ var PROGRESS_LABEL_CLASS = "rdw-progress__label"; var PROGRESS_WAITING_CLASS = "rdw-progress__fill--indeterminate"; /** * Kept for the tab, as the mark of the running tab is (queue.ts): the site * reloads the page on every navigation, and a panel minimised on one page * would be back over the grid on the next. */ var DOWNLOADS_MINIMISED_KEY = "ruledesk-web.downloads.minimised"; var MINIMISED_VALUE = "1"; var PANEL_WIDTH_PX$2 = 280; var PANEL_INSET_PX = 16; var PANEL_Z_INDEX$2 = 30; var MINIMISE_ICON_PX = 14; var PERCENT = 100; var TITLE_RUNNING = "Downloading"; var TITLE_DONE = "Downloaded"; var TITLE_ERROR = "Couldn’t download"; var QUOTE_OPEN = "“"; var QUOTE_CLOSE = "”"; var SELECTED_ONE = "selected post"; var SELECTED_MANY = "selected posts"; var TEXT_COLLECTING = "Looking up files…"; var TEXT_FOUND = "found"; var TEXT_OF = "of"; var TEXT_FILE = "file"; var TEXT_FILES = "files"; var TEXT_PAUSED = "Paused"; var TEXT_DONE = "Finished"; var TEXT_FAILED$1 = "failed"; var TEXT_SEPARATOR = " · "; var CHIP_COLLECTING = "Looking up…"; var CHIP_DONE = "Done"; var CHIP_ERROR = "Failed"; var LABEL_PAUSE = "Pause"; var LABEL_RESUME = "Resume"; var LABEL_CANCEL = "Cancel"; var LABEL_CLOSE$1 = "Close"; var LABEL_MINIMISE = "Minimize"; var TITLE_EXPAND = "Show the download"; var WARN_SESSION = "downloads: session storage unavailable"; var FEATURE_CSS$16 = ` #${DOWNLOADS_PANEL_ID} { position: fixed; right: ${String(PANEL_INSET_PX)}px; bottom: ${String(PANEL_INSET_PX)}px; z-index: ${String(PANEL_Z_INDEX$2)}; width: ${String(PANEL_WIDTH_PX$2)}px; max-width: calc(100vw - ${String(32)}px); box-sizing: border-box; display: flex; flex-direction: column; gap: 8px; padding: 12px; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-2); color: var(--rdw-text); font: 12.5px/1.4 var(--rdw-font); } #${DOWNLOADS_PANEL_ID}:empty { display: none; } #${DOWNLOADS_PANEL_ID}.${DOWNLOADS_MINIMISED_CLASS} { width: auto; padding: 0; background: transparent; border: 0; box-shadow: none; } #${DOWNLOADS_PANEL_ID} .${CHIP_CLASS$1} { box-shadow: var(--rdw-shadow-2); font-variant-numeric: tabular-nums; } #${DOWNLOADS_PANEL_ID} .${HEAD_CLASS} { display: flex; align-items: center; gap: 8px; } #${DOWNLOADS_PANEL_ID} .${TITLE_CLASS$4} { flex: 1 1 auto; min-width: 0; margin: 0; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } #${DOWNLOADS_PANEL_ID} .${TEXT_CLASS$1} { margin: 0; color: var(--rdw-muted); word-break: break-word; } #${DOWNLOADS_PANEL_ID} .${PROGRESS_LABEL_CLASS} { font: 12.5px/1.4 var(--rdw-font); letter-spacing: 0; text-transform: none; word-break: break-word; } #${DOWNLOADS_PANEL_ID} .${ACTIONS_CLASS$2} { display: flex; justify-content: flex-end; gap: 8px; } @media (prefers-reduced-motion: reduce) { #${DOWNLOADS_PANEL_ID} .${PROGRESS_WAITING_CLASS} { animation: none; } } `.trim(); function readMinimised() { try { return window.sessionStorage.getItem(DOWNLOADS_MINIMISED_KEY) === MINIMISED_VALUE; } catch { return false; } } function storeMinimised(minimised) { try { if (minimised) window.sessionStorage.setItem(DOWNLOADS_MINIMISED_KEY, MINIMISED_VALUE); else window.sessionStorage.removeItem(DOWNLOADS_MINIMISED_KEY); } catch (error) { log.warn(WARN_SESSION, error); } } /** * What the job is, with a verb: "Downloading “test”", and for posts picked by * hand "Downloading 3 selected posts" instead of the name of their folder. */ function downloadTitle(state) { const verb = state.phase === "done" ? TITLE_DONE : state.phase === "error" ? TITLE_ERROR : TITLE_RUNNING; if (state.selected !== null) { const noun = state.selected === 1 ? SELECTED_ONE : SELECTED_MANY; return `${verb} ${String(state.selected)} ${noun}`; } return `${verb} ${QUOTE_OPEN}${state.label}${QUOTE_CLOSE}`; } /** "12 of 340 files" with ", 2 failed" when some files did not save. */ function downloadCountText(state) { const noun = state.total === 1 ? TEXT_FILE : TEXT_FILES; const counted = `${String(state.done)} ${TEXT_OF} ${String(state.total)} ${noun}`; return state.failed > 0 ? `${counted}, ${String(state.failed)} ${TEXT_FAILED$1}` : counted; } function downloadStatusText(state) { if (state.phase === "collecting") return state.expected === null ? `${TEXT_COLLECTING} ${String(state.total)} ${TEXT_FOUND}` : `${TEXT_COLLECTING} ${String(state.total)} ${TEXT_OF} ${String(state.expected)}`; if (state.phase === "error") return state.message; if (state.phase === "paused") return `${state.message.length > 0 ? `${TEXT_PAUSED}: ${state.message}` : TEXT_PAUSED}${TEXT_SEPARATOR}${downloadCountText(state)}`; if (state.phase === "done") return `${TEXT_DONE}${TEXT_SEPARATOR}${downloadCountText(state)}`; return downloadCountText(state); } /** The share of the files already gone through, saved or failed: 0–1. */ function savedShare(state) { return state.total === 0 ? 0 : (state.done + state.failed) / state.total; } /** The few words of the minimised panel: the percent while there is one. */ function downloadChipText(state) { if (state.phase === "collecting") return CHIP_COLLECTING; if (state.phase === "error") return CHIP_ERROR; if (state.phase === "done") return CHIP_DONE; const percent = `${String(Math.round(savedShare(state) * PERCENT))}%`; return state.phase === "paused" ? `${TEXT_PAUSED}${TEXT_SEPARATOR}${percent}` : percent; } function DownloadsPanel(props) { const { host } = props; const [state, setState] = d(() => getDownloadState()); const [minimised, setMinimised] = d(readMinimised); A(() => { const unsubscribe = subscribeDownloads(setState); setState(getDownloadState()); return unsubscribe; }, []); const idle = state.phase === "idle"; A(() => { host.classList.toggle(DOWNLOADS_MINIMISED_CLASS, minimised && !idle); }, [ host, minimised, idle ]); const changeMinimised = (next) => { storeMinimised(next); setMinimised(next); }; if (idle) return null; const title = downloadTitle(state); const status = downloadStatusText(state); if (minimised) return /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", className: CHIP_CLASS$1, title: `${TITLE_EXPAND}: ${title}${TEXT_SEPARATOR}${status}`, onClick: () => { changeMinimised(false); }, children: downloadChipText(state) }); const finished = state.phase === "done" || state.phase === "error"; return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("div", { className: HEAD_CLASS, children: [/* @__PURE__ */ a("p", { className: TITLE_CLASS$4, title, children: title }), /* @__PURE__ */ a(IconButton, { label: LABEL_MINIMISE, onClick: () => { changeMinimised(true); }, children: /* @__PURE__ */ a(IconChevronDown, { size: MINIMISE_ICON_PX }) })] }), state.phase === "collecting" ? state.expected === null ? /* @__PURE__ */ a(ProgressBar, { waiting: true, label: status }) : /* @__PURE__ */ a(ProgressBar, { value: state.expected === 0 ? 0 : state.total / state.expected, label: status }) : state.phase === "error" ? /* @__PURE__ */ a("p", { className: TEXT_CLASS$1, role: "alert", children: status }) : /* @__PURE__ */ a(ProgressBar, { value: savedShare(state), label: status }), /* @__PURE__ */ a("div", { className: ACTIONS_CLASS$2, children: [ state.phase === "running" ? /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: pauseDownload, children: LABEL_PAUSE }) : null, state.phase === "paused" ? /* @__PURE__ */ a(Button, { variant: "primary", size: "s", onClick: resumeDownload, children: LABEL_RESUME }) : null, /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: cancelDownload, children: finished ? LABEL_CLOSE$1 : LABEL_CANCEL }) ] }) ] }); } function mountDownloads(_ctx) { if (document.getElementById(DOWNLOADS_PANEL_ID) !== null) return; const host = document.createElement("div"); host.id = DOWNLOADS_PANEL_ID; document.body.append(host); Q$1(/* @__PURE__ */ a(DownloadsPanel, { host }), host); restoreDownloads(); } var downloadsFeature = { id: FEATURE_ID$18, label: FEATURE_LABEL$18, pages: [...FEATURE_PAGES$12], defaultEnabled: true, css: `${FEATURE_CSS$16} ${GRID_SELECT_CSS}`, mount: mountDownloads }; /** * The colour of a tag's chip: by what the site called the tag where it was * seen, and for a followed tag by the kind it is followed as. "default" when * nothing is known, and for what is not a tag at all ("rating:safe"). */ function chipKindOfTag(tag) { const key = tagKey(tag); if (key.length === 0 || key.includes(":")) return "default"; const seen = tagKindOf(key); if (seen !== null) return seen; try { const followed = load$1().artists.find((entry) => tagKey(entry.tag) === key); return followed === void 0 ? "default" : followKindOf(followed); } catch { return "default"; } } function buildAddFavUrl(postId) { const params = new URLSearchParams(); params.set("id", postId); return `${SITE_ORIGIN}${ADDFAV_PATH}?${params.toString()}`; } function buildVoteUrl(postId) { const params = new URLSearchParams(); params.set(VOTE_PARAM_PAGE, VOTE_PAGE); params.set("s", VOTE_SECTION); params.set("id", postId); params.set(VOTE_PARAM_TYPE, "up"); return `${SITE_ORIGIN}${VOTE_PATH}?${params.toString()}`; } /** Favorites delete URL used by single-remove and bulk-remove (same request kind). */ function buildRemoveFavUrl(postId) { const params = new URLSearchParams(); params.set(SEARCH_PARAM_PAGE, FAVORITES_PAGE); params.set("s", FAVORITES_SECTION_DELETE); params.set("id", postId); params.set(FAVORITES_PARAM_RETURN_PID, "0"); return `${SITE_ORIGIN}${SEARCH_PATH}?${params.toString()}`; } async function fetchText(url) { const response = await fetch(url, { method: "GET", credentials: FETCH_CREDENTIALS }); if (!response.ok) throw new Error(`HTTP ${String(response.status)}`); return (await response.text()).trim(); } function parseVoteScore(raw) { if (raw.length === 0) return; const score = Number(raw); if (!Number.isFinite(score)) return; return score; } async function addFavorite(postId) { let addResponse; try { addResponse = await fetchText(buildAddFavUrl(postId)); } catch (error) { log.warn("addfav request failed", postId, error); return { status: "error" }; } if (addResponse === "1") return { status: "already" }; if (addResponse === "2") return { status: "not_logged_in" }; if (addResponse !== "3") { log.warn("Unexpected addfav response", postId, addResponse); return { status: "error" }; } try { const score = await voteUp(postId); if (score === null) return { status: "added" }; return { status: "added", score }; } catch (error) { log.warn("vote request failed after addfav", postId, error); return { status: "added" }; } } /** GET vote-up endpoint; returns the new score number, or null if unparseable/failed. */ async function voteUp(postId) { try { const score = parseVoteScore(await fetchText(buildVoteUrl(postId))); return score === void 0 ? null : score; } catch (error) { log.warn("vote request failed", postId, error); return null; } } async function removeFavorite(postId, options = {}) { try { const init = { method: "GET", credentials: FETCH_CREDENTIALS }; if (options.signal !== void 0) init.signal = options.signal; const response = await fetch(buildRemoveFavUrl(postId), init); if (!response.ok) { log.warn("remove favorite HTTP error", postId, response.status); return { status: "error" }; } return { status: "removed" }; } catch (error) { if (options.signal?.aborted === true || error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError") return { status: "error" }; log.warn("remove favorite request failed", postId, error); return { status: "error" }; } } /** * What the Favorites page needs to search and show every favorite without * asking the site: the tags and the preview address of each post. * * "Sync favorites" fills it while it walks the site's favorites pages. It is * kept in IndexedDB, apart from the main storage: a library of twelve * thousand favorites is several megabytes. It is not part of the Data export; * a full resync builds it again. */ var DB_NAME = "ruledesk-web.favorites-index"; var DB_VERSION = 1; var STORE_NAME = "posts"; var KEY_PATH = "id"; var FavoriteIndexEntrySchema = object({ id: int(), /** The tag list as the site prints it on the preview, space separated. */ tags: string(), /** Address of the preview image. */ thumb: string(), /** When the sync run that saw the post started, ms since epoch. */ run: number(), /** Place of the post in the site's list during that run, 0 is the newest favorite. */ pos: int(), /** * True when the tag list was read from a favorites page, where the site * cuts one character off each end of it; false when it was read whole. * Absent on entries written before 0.40.11 (see features/favorites-tags.ts). */ cut: optional(boolean()) }); /** False where the browser gives no IndexedDB (and in tests without a stub). */ function favoritesIndexAvailable() { return typeof indexedDB !== "undefined"; } function openDb() { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); request.onerror = () => { reject(request.error ?? /* @__PURE__ */ new Error("favorites-index: open failed")); }; request.onsuccess = () => { resolve(request.result); }; request.onupgradeneeded = () => { const db = request.result; if (!db.objectStoreNames.contains(STORE_NAME)) db.createObjectStore(STORE_NAME, { keyPath: KEY_PATH }); }; }); } function whenDone(tx) { return new Promise((resolve, reject) => { tx.oncomplete = () => { resolve(); }; tx.onerror = () => { reject(tx.error ?? /* @__PURE__ */ new Error("favorites-index: transaction failed")); }; tx.onabort = () => { reject(tx.error ?? /* @__PURE__ */ new Error("favorites-index: transaction aborted")); }; }); } /** Adds or replaces entries. Does nothing without IndexedDB. */ async function putFavoriteIndexEntries(entries) { if (entries.length === 0 || !favoritesIndexAvailable()) return; const db = await openDb(); try { const tx = db.transaction(STORE_NAME, "readwrite"); const store = tx.objectStore(STORE_NAME); for (const entry of entries) store.put(entry); await whenDone(tx); } finally { db.close(); } } /** Every stored entry that still has the expected shape. */ async function readFavoriteIndex() { if (!favoritesIndexAvailable()) return []; const db = await openDb(); try { const request = db.transaction(STORE_NAME, "readonly").objectStore(STORE_NAME).getAll(); const rows = await new Promise((resolve, reject) => { request.onerror = () => { reject(request.error ?? /* @__PURE__ */ new Error("favorites-index: read failed")); }; request.onsuccess = () => { const result = request.result; resolve(Array.isArray(result) ? result : []); }; }); const entries = []; for (const row of rows) { const parsed = FavoriteIndexEntrySchema.safeParse(row); if (parsed.success) entries.push(parsed.data); } return entries; } finally { db.close(); } } /** Like {@link putFavoriteIndexEntries}, but a failure is logged, not thrown. */ function putFavoriteIndexEntriesQuietly(entries) { putFavoriteIndexEntries(entries).catch((error) => { log.warn("favorites-index: write failed", error); }); } /** * The tags of the favorites index, put right as far as they can be. * * An entry read from a favorites page has a damaged tag list: the site cuts * one character off each end of it, so the first tag lacks its first letter * and the last tag its last (`ai_generated … zootopia` is kept as * `i_generated … zootopi`). Not every list: some come whole, which is told * only by the tags. An entry made when a post was made a favorite * from the grid or from its own page has the list whole. * * The damaged ends are restored from what is whole: the tags of whole * entries, and the tags that stand inside a cut list. A cut `zootopi` becomes * `zootopia` when that is the only known tag one letter longer at that end. * When there are several such tags, or none, the end stays as it is and is * marked: the search then tries the cut spellings on it, and the counts of * tags leave it out. Pure: no storage, no page. Nothing is written back: the * index keeps what was read, and the next "Full resync" flags every entry. * * `cut: false` on an entry says its list was read whole. Any other entry may * be cut, and its ends are judged by the tags themselves: the site does not * cut every list, so an end that is a known tag is left as it is. */ var TAG_SEPARATOR$1 = /\s+/; var CUT_LENGTH = 1; /** * What is known of a tag at an end of the list: it is whole (as read, or * restored); it is no known tag and could not be restored, so most likely * cut; or it is a known tag with a longer one beside it, and may be either. */ var END_WHOLE = "whole"; var END_UNKNOWN = "unknown"; function splitTags(text) { return text.trim().split(TAG_SEPARATOR$1).filter((tag) => tag.length > 0); } function addTo(map, key, tag) { const known = map.get(key); if (known === void 0) map.set(key, /* @__PURE__ */ new Set([tag])); else known.add(tag); } function only(tags) { if (tags?.size !== 1) return null; for (const tag of tags) return tag; return null; } /** * @param stored the tag as the entry holds it * @param candidates the whole tags that are `stored` plus one character at this end * @param knownWhole whether `stored` is itself a known whole tag * @param flagged the entry's own word on it: true cut, false whole, undefined unknown */ function restoreEnd(stored, candidates, knownWhole, flagged) { if (flagged === false) return { tag: stored, state: END_WHOLE }; if (knownWhole) return { tag: stored, state: candidates === void 0 ? END_WHOLE : END_UNKNOWN }; const single = only(candidates); return single === null ? { tag: stored, state: "cut" } : { tag: single, state: END_WHOLE }; } function restore(entries) { const lists = entries.map((entry) => splitTags(entry.tags)); const whole = /* @__PURE__ */ new Set(); const byNoFirst = /* @__PURE__ */ new Map(); const byNoLast = /* @__PURE__ */ new Map(); const learn = (tag) => { if (whole.has(tag)) return; whole.add(tag); if (tag.length > CUT_LENGTH) { addTo(byNoFirst, tag.slice(CUT_LENGTH), tag); addTo(byNoLast, tag.slice(0, -1), tag); } }; entries.forEach((entry, at) => { const tags = lists[at] ?? []; const from = entry.cut === false ? 0 : 1; const to = entry.cut === false ? tags.length : tags.length - 1; for (let index = from; index < to; index += 1) { const tag = tags[index]; if (tag !== void 0) learn(tag); } }); return entries.map((entry, at) => { const tags = lists[at] ?? []; const first = tags[0]; const last = tags[tags.length - 1]; if (first === void 0 || last === void 0 || entry.cut === false) return { ...entry, tagList: tags, firstEnd: END_WHOLE, lastEnd: END_WHOLE }; if (tags.length === 1) { const state = whole.has(first) ? END_UNKNOWN : "cut"; return { ...entry, tagList: tags, firstEnd: state, lastEnd: state }; } const head = restoreEnd(first, byNoFirst.get(first), whole.has(first), entry.cut); const tail = restoreEnd(last, byNoLast.get(last), whole.has(last), entry.cut); const tagList = [ head.tag, ...tags.slice(1, -1), tail.tag ]; return { ...entry, tagList, firstEnd: head.state, lastEnd: tail.state }; }); } var RESTORED = /* @__PURE__ */ new WeakMap(); /** * The entries with their tags restored. The work is done once for a list of * entries and kept while that list is alive: the search asks on every key. */ function restoreFavoriteTags(entries) { const known = RESTORED.get(entries); if (known !== void 0) return known; const restored = restore(entries); RESTORED.set(entries, restored); return restored; } var MEDIA_IMAGES$1 = "images"; var MEDIA_VIDEOS = "videos"; var SORT_ID_ASC = "id-asc"; var SORT_ID_DESC = "id-desc"; var TERM_SEPARATOR = /\s+/; var EXCLUDE_PREFIX$1 = "-"; var WILDCARD$1 = "*"; var GROUP_OPEN$1 = "("; var GROUP_CLOSE$1 = ")"; var GROUP_OR$1 = "~"; var FUZZY_SUFFIX = "~"; var META_SEPARATOR$1 = ":"; var SORT_PREFIX = "sort"; var SORTS = /* @__PURE__ */ new Map([ ["sort:id:asc", SORT_ID_ASC], ["sort:id:desc", SORT_ID_DESC], ["sort:id", SORT_ID_DESC] ]); /** * The names of the site's metatags. Only these are taken for metatags: a * colon alone does not make one, tags such as `re:zero` have it too. */ var META_NAMES = /* @__PURE__ */ new Set([ SORT_PREFIX, "user", "md5", "rating", "parent", "width", "height", "score", "aspectratio", "aspectratiof", "sourcedomains", "source", "id" ]); var REGEXP_SPECIAL = /[.+?^${}()|[\]\\]/g; function wholeTag(term) { const body = term.split(WILDCARD$1).map((part) => part.replace(REGEXP_SPECIAL, "\\$&")).join(".*"); return new RegExp(`^${body}$`); } /** A star at an end already stands for the cut character: nothing is taken off there. */ function termPattern(term) { const first = term.startsWith(WILDCARD$1) ? term : term.slice(1); const last = term.endsWith(WILDCARD$1) ? term : term.slice(0, -1); const ends = term.endsWith(WILDCARD$1) ? first : first.slice(0, -1); return { whole: wholeTag(term), noFirst: wholeTag(first), noLast: wholeTag(last), noEnds: wholeTag(ends) }; } function isFavoritesMedia(value) { return value === "all" || value === "images" || value === "videos"; } function isMetatag(term) { const at = term.indexOf(META_SEPARATOR$1); return at > 0 && META_NAMES.has(term.slice(0, at)); } /** Parses what was typed. Case does not matter: the site's tags are lower case. */ function parseFavoritesQuery(text) { const include = []; const exclude = []; const anyOf = []; const unsupported = []; let sort = null; let group = null; for (const raw of text.toLowerCase().split(TERM_SEPARATOR)) { if (raw.length === 0) continue; if (group !== null) { if (raw === GROUP_CLOSE$1) { if (group.length > 0) anyOf.push(group); group = null; } else if (raw !== GROUP_OR$1) group.push(termPattern(raw)); continue; } if (raw === GROUP_OPEN$1) { group = []; continue; } const negated = raw.startsWith(EXCLUDE_PREFIX$1); const term = negated ? raw.slice(1) : raw; if (term.length === 0) continue; if (isMetatag(term)) { const known = negated ? void 0 : SORTS.get(term); if (known === void 0) unsupported.push(raw); else sort = known; continue; } if (term.endsWith(FUZZY_SUFFIX)) { unsupported.push(raw); continue; } (negated ? exclude : include).push(termPattern(term)); } if (group !== null && group.length > 0) anyOf.push(group); return { include, exclude, anyOf, sort, unsupported }; } /** True when the query neither narrows the list nor orders it. */ function isEmptyFavoritesQuery(query) { return query.include.length === 0 && query.exclude.length === 0 && query.anyOf.length === 0 && query.sort === null; } function hasTag(entry, pattern) { const tags = entry.tagList; const lastAt = tags.length - 1; return tags.some((tag, at) => { if (pattern.whole.test(tag)) return true; const firstOpen = at === 0 && entry.firstEnd !== "whole"; const lastOpen = at === lastAt && entry.lastEnd !== "whole"; return firstOpen && pattern.noFirst.test(tag) || lastOpen && pattern.noLast.test(tag) || firstOpen && lastOpen && pattern.noEnds.test(tag); }); } function matchesQuery(entry, query) { return query.include.every((pattern) => hasTag(entry, pattern)) && !query.exclude.some((pattern) => hasTag(entry, pattern)) && query.anyOf.every((group) => group.some((pattern) => hasTag(entry, pattern))); } function matchesMedia(entry, media) { if (media === "all") return true; return titleSaysVideo(entry.tags) === (media === MEDIA_VIDEOS); } /** * The favorites that match, in the site's order (the newest favorite first) * or by post id when the query asks for that. A post that is no longer a * favorite is left out even while the index still holds it. */ function filterFavoriteIndex(entries, favoriteIds, query, media) { const matched = restoreFavoriteTags(entries).filter((entry) => favoriteIds.has(entry.id) && matchesMedia(entry, media) && matchesQuery(entry, query)); if (query.sort === "id-asc") return matched.sort((a, b) => a.id - b.id); if (query.sort === "id-desc") return matched.sort((a, b) => b.id - a.id); return matched.sort((a, b) => b.run - a.run || a.pos - b.pos || b.id - a.id); } function topFavoriteTags(entries, favoriteIds, limit) { const counts = /* @__PURE__ */ new Map(); for (const entry of restoreFavoriteTags(entries)) { if (!favoriteIds.has(entry.id)) continue; const lastAt = entry.tagList.length - 1; const whole = entry.tagList.filter((_tag, at) => !(at === 0 && entry.firstEnd === "cut") && !(at === lastAt && entry.lastEnd === "cut")); for (const tag of new Set(whole)) counts.set(tag, (counts.get(tag) ?? 0) + 1); } return [...counts].map(([tag, count]) => ({ tag, count })).sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag)).slice(0, limit); } var SEED_STEP = 1831565813; var UINT32_RANGE = 4294967296; /** A repeatable random order: the same seed gives the same order. */ function shuffleBySeed(items, seed) { let state = seed >>> 0; const next = () => { state = state + SEED_STEP >>> 0; let mixed = state; mixed = Math.imul(mixed ^ mixed >>> 15, mixed | 1); mixed ^= mixed + Math.imul(mixed ^ mixed >>> 7, mixed | 61); return ((mixed ^ mixed >>> 14) >>> 0) / UINT32_RANGE; }; const shuffled = [...items]; for (let index = shuffled.length - 1; index > 0; index -= 1) { const other = Math.floor(next() * (index + 1)); const held = shuffled[index]; const swapped = shuffled[other]; if (held !== void 0 && swapped !== void 0) { shuffled[index] = swapped; shuffled[other] = held; } } return shuffled; } /** A word of the query grammar, not a tag: nothing is offered for it. */ var GRAMMAR_WORDS = /* @__PURE__ */ new Set([ "(", ")", "~" ]); var EXCLUDE_PREFIX = "-"; var WILDCARD = "*"; var SPACE = /\s/; var GROUP_STARTS = "starts"; var GROUP_INSIDE = "inside"; var EXCLUDE_HEADING = "Exclude"; /** The word the caret stands in or right after; null between words. */ function wordAtCaret(text, caret) { const at = Math.max(0, Math.min(caret, text.length)); let start = at; while (start > 0 && !SPACE.test(text.charAt(start - 1))) start -= 1; let end = at; while (end < text.length && !SPACE.test(text.charAt(end))) end += 1; if (start === end) return null; const raw = text.slice(start, end).toLowerCase(); const negated = raw.startsWith(EXCLUDE_PREFIX); return { start, end, body: negated ? raw.slice(1) : raw, negated }; } /** * What to offer for the word. An exact tag stands first, then the tags that * begin with what was typed, then those that hold it inside; within each, the * tag more favorites have comes first. `tags` is every tag with its count. */ function suggestFor(tags, word) { if (word === null || word.body.length === 0) return null; const { body, negated } = word; if (GRAMMAR_WORDS.has(body) || body.includes(WILDCARD)) return null; const prefix = negated ? EXCLUDE_PREFIX : ""; const items = []; const starts = []; const inside = []; let exact = null; for (const item of tags) if (item.tag === body) exact = item; else if (item.tag.startsWith(body)) starts.push(item); else if (item.tag.includes(body)) inside.push(item); const byCount = (a, b) => b.count - a.count || a.tag.localeCompare(b.tag); starts.sort(byCount); inside.sort(byCount); const toSuggestion = (item, group) => ({ insert: `${prefix}${item.tag}`, label: `${prefix}${item.tag}`, matchStart: prefix.length + item.tag.indexOf(body), matchLength: body.length, count: item.count, caption: null, group }); for (const item of exact === null ? starts : [exact, ...starts]) items.push(toSuggestion(item, GROUP_STARTS)); for (const item of inside) items.push(toSuggestion(item, GROUP_INSIDE)); if (items.length === 0 || items.length === 1 && exact !== null) return null; return { heading: negated ? EXCLUDE_HEADING : null, items: items.slice(0, 20) }; } /** The query with the word replaced by the suggestion, ready for the next word. */ function completeWord(text, word, insert) { const before = text.slice(0, word.start); const after = text.slice(word.end); const gap = after.length === 0 || !SPACE.test(after.charAt(0)) ? " " : ""; const head = `${before}${insert}${gap}`; const caret = gap.length > 0 ? head.length : head.length + 1; return { text: `${head}${after}`, caret: Math.min(caret, head.length + after.length) }; } /** * The plain words of a query that are no tag of any favorite, in the order * typed: what an empty result is most likely owed to. */ function unknownWords(text, tags) { const known = new Set(tags.map((item) => item.tag)); const unknown = []; for (const raw of text.toLowerCase().split(/\s+/)) { if (raw.length === 0 || raw.startsWith(EXCLUDE_PREFIX) || GRAMMAR_WORDS.has(raw) || raw.includes(WILDCARD) || raw.includes(":") || known.has(raw)) continue; unknown.push(raw); } return unknown; } /** * The tag to offer in place of a word that is no tag: the one with the least * added to the word. A tag that begins with the word is taken before one * that holds it inside; of two as long, the one more favorites have. */ function closestTag(tags, word) { let best = null; let bestStarts = false; for (const item of tags) { if (item.tag === word || !item.tag.includes(word)) continue; const starts = item.tag.startsWith(word); if (best === null || starts && !bestStarts || starts === bestStarts && (item.tag.length < best.tag.length || item.tag.length === best.tag.length && item.count > best.count)) { best = item; bestStarts = starts; } } return best; } var GROUP_OPEN = "("; var GROUP_CLOSE = ")"; var GROUP_OR = "~"; var WORD = /\S+/g; /** "Any of 3 tags": what a group reads as on its chip. */ function groupChipLabel(count) { return `Any of ${String(count)} ${count === 1 ? "tag" : "tags"}`; } /** The query as chips, in the order typed. A group that is not closed yet is still one chip. */ function queryChips(text) { const chips = []; let groupStart = null; let groupCount = 0; let lastEnd = 0; for (const match of text.matchAll(WORD)) { const word = match[0]; const start = match.index; const end = start + word.length; lastEnd = end; if (groupStart !== null) { if (word === GROUP_CLOSE) { chips.push({ start: groupStart, end, label: groupChipLabel(groupCount), excluded: false, group: true }); groupStart = null; } else if (word !== GROUP_OR) groupCount += 1; continue; } if (word === GROUP_OPEN) { groupStart = start; groupCount = 0; continue; } const excluded = word.startsWith(EXCLUDE_PREFIX) && word.length > 1; chips.push({ start, end, label: excluded ? word.slice(1) : word, excluded, group: false }); } if (groupStart !== null) chips.push({ start: groupStart, end: lastEnd, label: groupChipLabel(groupCount), excluded: false, group: true }); return chips; } function tidy(text) { return text.replace(/\s+/g, " ").trim(); } /** The query without the chip. */ function removeChip(text, chip) { return tidy(`${text.slice(0, chip.start)} ${text.slice(chip.end)}`); } /** The query with the chip's word excluded, or included again; a group is left as it is. */ function toggleChip(text, chip) { if (chip.group) return text; const word = chip.excluded ? chip.label : `${EXCLUDE_PREFIX}${chip.label}`; return tidy(`${text.slice(0, chip.start)}${word}${text.slice(chip.end)}`); } /** The collection filter of Favorites: the favorites that are in no collection yet. */ var COLLECTION_NONE = "none"; /** Before a collection's id in the value of the filter, so that no id reads as "any" or "none". */ var COLLECTION_VALUE_PREFIX = "id:"; var COLLECTION_ANY_LABEL = "Any"; var COLLECTION_NONE_LABEL = "Not in any collection"; function hasPosts(collection) { return collection.kind === COLLECTION_KIND_POSTS; } /** The choices of the collection filter: any, none, then the collections of posts by name. */ function collectionChoices(collections) { const named = collections.filter(hasPosts).map((collection) => ({ value: `${COLLECTION_VALUE_PREFIX}${collection.id}`, label: collection.name })).sort((a, b) => a.label.localeCompare(b.label)); return [ { value: "any", label: COLLECTION_ANY_LABEL }, { value: COLLECTION_NONE, label: COLLECTION_NONE_LABEL }, ...named ]; } /** * Says whether a post passes the collection filter, or null where the filter * lets everything through: "any", or a collection that is no longer there. */ function collectionScope(collections, choice) { if (choice === "none") { const taken = /* @__PURE__ */ new Set(); for (const collection of collections) if (hasPosts(collection)) for (const id of collection.postIds ?? []) taken.add(id); return (postId) => !taken.has(postId); } if (!choice.startsWith(COLLECTION_VALUE_PREFIX)) return null; const id = choice.slice(3); const picked = collections.find((collection) => hasPosts(collection) && collection.id === id); if (picked === void 0) return null; const inside = new Set(picked.postIds ?? []); return (postId) => inside.has(postId); } /** * The entries of Following found among the favorites, with the number of * favorites each has: the most favorited first, equal ones by name. */ function followedInFavorites(followed, tags) { const counts = /* @__PURE__ */ new Map(); for (const item of tags) counts.set(item.tag, item.count); const found = []; const seen = /* @__PURE__ */ new Set(); for (const entry of followed) { const tag = entry.tag.toLowerCase(); const count = counts.get(tag); if (count === void 0 || count === 0 || seen.has(tag)) continue; seen.add(tag); found.push({ tag, kind: entry.kind ?? "artist", count }); } return found.sort((a, b) => b.count - a.count || a.tag.localeCompare(b.tag)); } /** True when the query names the tag as it is, not excluded and not inside a group. */ function queryHasTag(text, tag) { return queryChips(text).some((chip) => !chip.group && !chip.excluded && chip.label.toLowerCase() === tag); } /** * The query with the tag added at its end, or taken out when it is there * already. A tag the query excludes is included instead: both at once would * find nothing. */ function toggleQueryTag(text, tag) { const chip = queryChips(text).find((item) => !item.group && item.label.toLowerCase() === tag); if (chip !== void 0) return chip.excluded ? toggleChip(text, chip) : removeChip(text, chip); const base = text.trim(); return base.length === 0 ? tag : `${base} ${tag}`; } var MORE_CLASS = "rdw-fav-more"; var CONTROLS_CLASS = "rdw-fav-controls"; /** On the block the grid is in, once the column of filters is put beside it. */ var FAVORITES_LAYOUT_CLASS = "rdw-fav-layout"; var FAVORITES_SIDE_ID = "rdw-favorites-side"; var FAVORITES_SIDE_CLASS = "rdw-fav-side"; /** The child of the laid-out block that holds the column and gives it its place. */ var FAVORITES_SIDE_SLOT_CLASS = "rdw-fav-side-slot"; /** The width of the sidebar of Posts in the skin: the same column here. */ var FAVORITES_SIDE_WIDTH_PX = 228; /** The column spans every row of the block: more than the block will ever have. */ var SIDE_ROW_SPAN = 60; var STATUS_CLASS$2 = "rdw-fav-status"; var SEARCH_BOX_CLASS = "rdw-fav-search-box"; var GROUP_LABEL_CLASS = "rdw-fav-group-label"; var COUNT_CLASS$2 = "rdw-favorites-count"; /** The right end of the row: the buttons the bulk bar puts there. */ var ACTIONS_CLASS$1 = "rdw-favorites-head-actions"; var SYNTAX_POPOVER_WIDTH_PX = 340; var VIEW_STATE_ID = FAVORITES_VIEW_STATE_ID; var VIEW_PAGES = "pages"; var VIEW_SCROLL = FAVORITES_VIEW_SCROLL; var TYPING_PAUSE_MS = 250; var EMPTY_CLASS = "rdw-fav-empty"; var SUGGEST_LABEL = "Tags in your favorites"; var EMPTY_NO_MATCH = "No favorites match this search"; var EMPTY_NO_TAG_PREFIX = "No favorites tagged “"; var EMPTY_NO_TAG_SUFFIX = "”"; var EMPTY_NOTE_CLOSEST = "Tags match whole words. Closest tag in your favorites:"; var EMPTY_NOTE_NONE = "Tags match whole words, and no tag in your favorites has this in it."; var EMPTY_SHOW_PREFIX = "Show "; var MORE_ROOT_MARGIN = "600px"; var SEARCH_FIELD_ID = "rdw-fav-search"; var SEARCH_PLACEHOLDER = "Search your favorites"; var SEARCH_ARIA_LABEL = "Search favorites"; var CLEAR_LABEL$1 = "Clear search"; var SEARCH_HELP = { label: "Search syntax", rows: [ ["cat dog", "posts with both tags"], ["( cat ~ dog )", "posts with either tag; keep the spaces"], ["-sketch", "posts without the tag"], ["cat*", "tags that start with cat"], ["ca*t", "tags like ca…t"] ], note: "Favorites search uses tags only. rating:, score:, width:, height:, user: and the other metatags, and fuzzy tag~, work only in Posts search. The order is set with Sort.", widthPx: SYNTAX_POPOVER_WIDTH_PX }; /** Shown while Shuffle is on and the query asks for an order: one of them has to give way. */ var SHUFFLE_OVER_SORT_NOTICE = "Shuffle is on: the order in the search is not applied."; var UNSUPPORTED_ONE = " doesn’t work in Favorites."; var UNSUPPORTED_MANY = " don’t work in Favorites."; var UNSUPPORTED_TAIL = " Favorites search uses tags only."; var META_SEPARATOR = ":"; var RESET_LABEL$1 = "Reset search"; var COLLECTION_LABEL = "Collection"; var UNSYNCED_NOTE = "Favorites aren’t synced yet. Search, filters and Scroll need a one-time sync (about 1.5 s per page)."; var UNSYNCED_BUTTON = "Sync favorites…"; var SYNC_NOW = "Sync now"; var SYNC_LINK_CLASS = "rdw-fav-sync-link"; /** Added to the typed query while AI posts are hidden here. */ var NO_AI_TERM = `-${AI_TAG}`; var NO_AI_SUMMARY = "no AI posts"; var EMPTY_COLLECTION = "No favorites here"; var EMPTY_COLLECTION_NOTE = "None of your favorites pass the Collection filter. Choose Any to see them all."; /** Not "Following": that is the page of the header, and this is a filter of the favorites. */ /** * The designer's name (18.11.2026). "Following" is the item of the header and * read as a link to that page; "Followed in favorites" named the filter, not * what is in the card; "artists" is wrong, a followed tag can be a copyright. */ var FOLLOWED_TITLE = "Followed tags"; var FOLLOWED_SHOW_ALL = "Show all"; var FOLLOWED_SHOW_LESS = "Show less"; var EXCLUDE_SIGN = "-"; var MEDIA_LABEL = "Type"; var VIEW_LABEL = "View"; var SORT_LABEL = "Sort"; /** * The order of the list, by when a post was made a favorite. Newest first is * the site's own order and the page as it comes; oldest first is the same * list turned over. (A third option, by the age of the post itself, was * taken out: beside "Newest" it read as the same thing. Kaze, 17.11.2026.) */ var ORDER_NEWEST = "newest"; var ORDER_OLDEST = "oldest"; /** * A random order is the third option of the same switch (the designer, * 17.11.2026): as a button of its own it could be on while the switch still * said "Newest". A click on it while it is chosen shuffles again. */ var ORDER_SHUFFLE = "shuffle"; var SORT_OPTIONS$1 = [ { value: ORDER_NEWEST, label: "Newest" }, { value: ORDER_OLDEST, label: "Oldest" }, { value: ORDER_SHUFFLE, label: "Shuffle" } ]; var SIDE_TITLE = "Search"; var RESHUFFLE_HINT = "Click Shuffle again for another order."; var LOCKED_NOTICE = "Finish selecting to change filters."; var CHIPS_LABEL = "Search terms"; var CHIP_EXCLUDE_TITLE = "Click to exclude, click again to include"; var SIDE_GAP_PX = 12; var SIDE_FADE_PX = 28; var SCROLL_END_SLACK_PX = 2; var SIDE_MORE_CLASS = "rdw-fav-side--more"; var SIDE_LOCKED_CLASS = "rdw-fav-side--locked"; var SIDE_BODY_CLASS = "rdw-fav-side__body"; var SIDE_HEAD_CLASS = "rdw-fav-side__head"; var WARNING_CLASS = "rdw-fav-warning"; /** The foot of the card: the bulk bar draws the buttons of the page into it. */ var FAVORITES_SIDE_ACTIONS_CLASS = "rdw-fav-side__actions"; var SIDE_ACTIONS_CLASS = FAVORITES_SIDE_ACTIONS_CLASS; /** In the column, over the card: the selection bar is drawn into it. */ var FAVORITES_SIDE_BAR_CLASS = "rdw-fav-side__bar"; /** In the column: the card of filters is drawn into it. */ var FAVORITES_SIDE_CARD_CLASS = "rdw-fav-side__card"; var SIDE_GROUP_CLASS = "rdw-fav-side__group"; var SIDE_LOCK_CLASS = "rdw-fav-side__lock"; var SIDE_HINT_CLASS = "rdw-fav-side__hint"; var FOLLOWED_CARD_CLASS = "rdw-fav-followed"; var FOLLOWED_LIST_CLASS = "rdw-fav-followed__list"; var FOLLOWED_ROW_CLASS = "rdw-fav-followed__row"; var FOLLOWED_DOT_CLASS = "rdw-fav-followed__dot"; var FOLLOWED_NAME_CLASS = "rdw-fav-followed__name"; var FOLLOWED_COUNT_CLASS = "rdw-fav-followed__count"; var FOLLOWED_KIND_ATTR = "data-kind"; var CHIPS_CLASS$1 = "rdw-fav-chips"; var CHIP_BUTTON_CLASS = "rdw-fav-chip"; function isFavoritesOrder(value) { return value === "newest" || value === "oldest"; } var MORE_LABEL$1 = "Show more"; var LOCALE$2 = "en-US"; var NO_INDEX_STATUS = "No index yet: run Full resync in RuleDesk → Favorites to search and scroll here."; var REMOVE_FAILED_STATUS = "Could not remove the favorite. Try again."; var MEDIA_OPTIONS$1 = [ { value: "all", label: "All" }, { value: MEDIA_IMAGES$1, label: "Images" }, { value: MEDIA_VIDEOS, label: "Videos" } ]; var VIEW_OPTIONS = [{ value: VIEW_PAGES, label: "Pages" }, { value: VIEW_SCROLL, label: "Scroll" }]; /** The site's own inline style of a favorites cell. */ var CELL_STYLE = "align-self: flex-start; display: grid; grid-template-rows: auto 10px;"; var POST_HREF_PREFIX = "index.php?page=post&s=view&id="; var IMAGE_ALT = "image_thumb"; var REMOVE_TEXT = "Remove"; var FAVORITES_BROWSER_CSS = ` body.${FAVORITES_BROWSING_BODY_CLASS} ${SITE_SELECTORS.imageList}:not(.${FAVORITES_RESULTS_CLASS}), body.${FAVORITES_BROWSING_BODY_CLASS} #paginator { display: none !important; } body:not(.${FAVORITES_BROWSING_BODY_CLASS}) .${FAVORITES_RESULTS_CLASS}, body:not(.${FAVORITES_BROWSING_BODY_CLASS}) .${MORE_CLASS} { display: none; } /* The strip over the grid: the count, how the list is paged, the buttons. */ .${CONTROLS_CLASS} { display: flex; flex: 1 1 auto; flex-wrap: wrap; align-items: center; gap: 0.35rem 0.75rem; min-width: 0; } .${CONTROLS_CLASS} .rdw-btn { font-weight: 500; } .${GROUP_LABEL_CLASS} { font: 12px var(--rdw-font); color: var(--rdw-muted); } /* The page in two columns: the filters, and everything the site put there. Nothing of the site's is wrapped or moved; the block the grid is in becomes a grid of its own, and the column of filters is one more child of it. */ .${FAVORITES_LAYOUT_CLASS} { display: grid !important; grid-template-columns: ${String(FAVORITES_SIDE_WIDTH_PX)}px minmax(0, 1fr); column-gap: 16px; row-gap: 0; align-items: start; /* The grid and the card start the same way off the header. The site and the skin set the padding of this block themselves: this has to win. */ padding-top: ${String(SIDE_GAP_PX)}px !important; } .${FAVORITES_LAYOUT_CLASS} > * { grid-column: 2; min-width: 0; } /* The place of the column: the first column, every row. It takes no part in the sizing of the rows (a child that spans rows makes them taller by its own height), so its size is its place and nothing else. */ .${FAVORITES_LAYOUT_CLASS} > .${FAVORITES_SIDE_SLOT_CLASS} { grid-column: 1; grid-row: 1 / span ${String(SIDE_ROW_SPAN)}; align-self: stretch; contain: size; } /* Held beside the grid; taller than the window, it scrolls inside itself. */ .${FAVORITES_SIDE_CLASS} { box-sizing: border-box; position: sticky; top: calc(${STICKY_TOP} + ${String(SIDE_GAP_PX)}px); max-height: calc(100vh - ${STICKY_TOP} - ${String(24)}px); overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--rdw-border) transparent; color: var(--rdw-text); font: 12px/1.4 var(--rdw-font); } .${FAVORITES_SIDE_CLASS} * { font-family: var(--rdw-font); } /* A strip that fades the last lines while there is more below. Not a mask: the suggestions and the "?" open from inside the column. */ .${FAVORITES_SIDE_CLASS}.${SIDE_MORE_CLASS}::after { content: ""; position: sticky; bottom: 0; display: block; height: ${String(SIDE_FADE_PX)}px; margin-top: -${String(SIDE_FADE_PX)}px; background: linear-gradient(to bottom, transparent, var(--rdw-bg)); pointer-events: none; } /* A card, as the search panel of Posts is: the filters read as one block and not as controls lying on the page. */ .${SIDE_BODY_CLASS} { display: flex; flex-direction: column; gap: 12px; padding: 12px; background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); box-shadow: var(--rdw-shadow-1); } /* A condition that does not work here: said in a plate, not in a grey line that is taken for nothing (the owner took one for a broken filter). */ .${WARNING_CLASS} { margin: 0; padding: 6px 8px; border-radius: var(--rdw-radius-m); background: var(--rdw-warn-soft); color: var(--rdw-warn); font-size: 12px; line-height: 1.4; overflow-wrap: anywhere; } /* The rare actions are quieter than the two used all the time. */ .${SIDE_BODY_CLASS} .${SIDE_ACTIONS_CLASS} > .rdw-btn--ghost { color: var(--rdw-muted); } .${SIDE_BODY_CLASS} .${SIDE_ACTIONS_CLASS} > .rdw-btn--ghost:hover { color: var(--rdw-text); } .${SIDE_HEAD_CLASS} { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; } /* The buttons at the foot of the card, as "Reset" and "Select posts" are on Posts. */ .${SIDE_BODY_CLASS} .${SIDE_ACTIONS_CLASS} { display: flex; flex-wrap: wrap; gap: 6px; padding-top: 12px; border-top: 1px solid var(--rdw-border); } .${SIDE_BODY_CLASS} .${SIDE_ACTIONS_CLASS}:empty { display: none; } /* Each on a row of its own: the column has the room, and nothing is tucked away in a menu. */ .${SIDE_BODY_CLASS} .${SIDE_ACTIONS_CLASS} > .rdw-btn { flex: 1 1 100%; white-space: nowrap; font-weight: 500; } .${SIDE_GROUP_CLASS} { display: flex; flex-direction: column; gap: 4px; min-width: 0; } /* The collection filter fills the card, as the switches above it do. */ .${SIDE_GROUP_CLASS} > .rdw-select { display: flex; } .${SIDE_GROUP_CLASS} > .rdw-select .rdw-select__trigger > span { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .${SYNC_LINK_CLASS} { padding: 0; border: 0; background: none; color: var(--rdw-accent); font: inherit; text-decoration: underline; cursor: pointer; } /* The followed among the favorites: a card of its own under the filters. */ .${FOLLOWED_CARD_CLASS} { margin-top: 12px; } .${FOLLOWED_LIST_CLASS} { display: flex; flex-direction: column; gap: 2px; margin: 0; padding: 0; list-style: none; } .${FOLLOWED_LIST_CLASS} > li { margin: 0; padding: 0; list-style: none; } .${FOLLOWED_ROW_CLASS} { box-sizing: border-box; display: flex; align-items: center; gap: 6px; width: 100%; min-height: 26px; padding: 0 6px; border: 1px solid transparent; border-radius: var(--rdw-radius-s); background: none; color: var(--rdw-text); font: inherit; text-align: left; cursor: pointer; } .${FOLLOWED_ROW_CLASS}:hover { background: var(--rdw-surface-2); } .${FOLLOWED_ROW_CLASS}[aria-pressed="true"] { background: var(--rdw-accent-soft); border-color: var(--rdw-accent); } .${FOLLOWED_DOT_CLASS} { flex: none; width: 7px; height: 7px; border-radius: 50%; background: var(--rdw-tag-artist); } .${FOLLOWED_ROW_CLASS}[${FOLLOWED_KIND_ATTR}="character"] .${FOLLOWED_DOT_CLASS} { background: var(--rdw-tag-character); } .${FOLLOWED_ROW_CLASS}[${FOLLOWED_KIND_ATTR}="copyright"] .${FOLLOWED_DOT_CLASS} { background: var(--rdw-tag-copyright); } .${FOLLOWED_NAME_CLASS} { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .${FOLLOWED_COUNT_CLASS} { flex: none; color: var(--rdw-muted); font-variant-numeric: tabular-nums; } .${SIDE_HINT_CLASS} { margin: 0; color: var(--rdw-muted); font-size: 11.5px; } .${CHIPS_CLASS$1} { display: flex; flex-wrap: wrap; gap: 4px; } .${CHIP_BUTTON_CLASS} { display: inline-flex; max-width: 100%; margin: 0; padding: 0; border: 0; background: none; color: inherit; font: inherit; cursor: pointer; } /* While posts are being selected the filters cannot be changed. */ .${SIDE_LOCK_CLASS} { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; margin: 0 0 8px; padding: 8px 10px; border: 1px solid var(--rdw-accent); border-radius: var(--rdw-radius-m); background: var(--rdw-accent-soft); color: var(--rdw-text); } .${FAVORITES_SIDE_CLASS}.${SIDE_LOCKED_CLASS} .${SIDE_BODY_CLASS} { opacity: 0.45; pointer-events: none; } /* In place of the grid when nothing matches. */ .${EMPTY_CLASS} { flex: 1 1 100%; box-sizing: border-box; display: grid; justify-items: center; gap: 6px; margin: 12px 0; padding: 28px 16px; border: 1px dashed var(--rdw-border); border-radius: var(--rdw-radius-l); color: var(--rdw-muted); font: 13px/1.5 var(--rdw-font); text-align: center; } .${EMPTY_CLASS} strong { color: var(--rdw-text); font-weight: 700; } .${EMPTY_CLASS} button { margin-top: 6px; } .${STATUS_CLASS$2} { flex: 0 0 100%; font: 12px var(--rdw-font); color: var(--rdw-muted); } .${COUNT_CLASS$2} { font: 12px var(--rdw-font); color: var(--rdw-muted); white-space: nowrap; } /* The buttons stand at the right end of the strip. */ .${CONTROLS_CLASS} .${ACTIONS_CLASS$1} { display: flex; align-items: center; gap: 0.35rem 0.5rem; margin-left: auto; } .${CONTROLS_CLASS} .${ACTIONS_CLASS$1}:empty { display: none; } .${MORE_CLASS} { display: block; margin: 12px auto 24px; padding: 6px 14px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); font: 600 12px var(--rdw-font); cursor: pointer; } .${MORE_CLASS}[hidden] { display: none; } `.trim(); function isFavoritesView(value) { return value === "pages" || value === VIEW_SCROLL; } function readView() { const stored = getFeatureState(VIEW_STATE_ID); return isFavoritesView(stored) ? stored : VIEW_PAGES; } /** Where the favorites cells on screen are: the results grid while it is shown. */ function favoritesGridRoot() { if (document.body.classList.contains("rdw-fav-browsing")) { const results = document.querySelector(`.${FAVORITES_RESULTS_CLASS}`); if (results !== null) return results; } return document; } /** A cell with the markup of the site's favorites grid. */ function buildFavoriteCell(entry) { const id = String(entry.id); const cell = document.createElement("span"); cell.setAttribute("style", CELL_STYLE); const thumb = document.createElement("span"); thumb.className = "thumb"; const link = document.createElement("a"); link.id = `p${id}`; link.href = `${POST_HREF_PREFIX}${id}`; const img = document.createElement("img"); img.src = entry.thumb; img.title = entry.tags; img.alt = IMAGE_ALT; img.loading = "lazy"; link.append(img); thumb.append(link); const remove = document.createElement("a"); remove.href = "#"; remove.setAttribute("onclick", `document.location='index.php?page=favorites&s=delete&id=${id}&return_pid=0'; return false;`); const bold = document.createElement("b"); bold.textContent = REMOVE_TEXT; remove.append(bold); cell.append(thumb, document.createElement("br"), remove); return cell; } var grid = null; var onRemoveFailed = null; function appendChunk(target) { const next = target.results.slice(target.shown, target.shown + 100); for (const entry of next) target.container.append(buildFavoriteCell(entry)); target.shown += next.length; target.more.hidden = target.shown >= target.results.length; if (next.length > 0) notifyThumbsAdded(target.container); } /** * The bin of a cell removes the favorite in place, on the site's own grid as * well as on the results. The site's own link would leave for the delete * address and come back to the top of the first page. */ function onGridClick(event) { const target = event.target; if (!(target instanceof Element)) return; const link = target.closest("a[onclick]"); if (!(link instanceof HTMLAnchorElement)) return; const postId = extractPostIdFromFavoritesDeleteOnclick(link.getAttribute("onclick") ?? ""); if (postId === null) return; event.preventDefault(); event.stopPropagation(); const cell = link.parentElement; removeFavorite(postId).then((result) => { if (result.status === "removed") { cell?.remove(); return; } onRemoveFailed?.(); }).catch((error) => { log.warn("favorites-browser: remove failed", error); onRemoveFailed?.(); }); } var boundGrids = /* @__PURE__ */ new WeakSet(); /** Makes the bins of the cells under `gridRoot` remove without leaving the page. */ function bindInPlaceRemoval(gridRoot) { if (boundGrids.has(gridRoot)) return; boundGrids.add(gridRoot); gridRoot.addEventListener("click", onGridClick, true); } function ensureGrid() { if (grid !== null && grid.container.isConnected) return grid; const siteList = document.querySelector(`${SITE_SELECTORS.imageList}:not(.${FAVORITES_RESULTS_CLASS})`); if (siteList === null) return null; const container = document.createElement("div"); container.className = `image-list ${FAVORITES_RESULTS_CLASS}`; bindInPlaceRemoval(container); const more = document.createElement("button"); more.type = "button"; more.className = MORE_CLASS; more.textContent = MORE_LABEL$1; more.hidden = true; siteList.after(container, more); const created = { container, more, results: [], shown: 0 }; more.addEventListener("click", () => { appendChunk(created); }); if (typeof IntersectionObserver === "function") new IntersectionObserver((records) => { if (records.some((record) => record.isIntersecting)) appendChunk(created); }, { rootMargin: MORE_ROOT_MARGIN }).observe(more); grid = created; return created; } /** Shows `results` instead of the site's grid. */ function showFavoriteResults(results) { const target = ensureGrid(); if (target === null) return; target.container.replaceChildren(); target.results = results; target.shown = 0; document.body.classList.add(FAVORITES_BROWSING_BODY_CLASS); appendChunk(target); } /** * The ids of the favorites the filters leave, in the order shown and over all * the pages of the result; null while the site's own grid is on the page, * which is every favorite. */ function shownFavoriteIds() { if (grid === null || !document.body.classList.contains("rdw-fav-browsing")) return null; return grid.results.map((entry) => entry.id); } /** Shows `node` where the results would be: nothing matched. */ function showFavoriteEmpty(node) { const target = ensureGrid(); if (target === null) return; target.container.replaceChildren(node); target.results = []; target.shown = 0; target.more.hidden = true; document.body.classList.add(FAVORITES_BROWSING_BODY_CLASS); } /** Every tag of the favorites with its count, for the suggestions. */ function favoriteTagCounts(index, favorites) { return topFavoriteTags(index, favorites, Number.MAX_SAFE_INTEGER); } /** The suggestions in the shape the field draws. */ function toSuggestList(found) { if (found === null) return null; return { heading: found.heading, items: found.items.map((item, at) => ({ key: `${item.group}:${item.insert}`, label: item.label, matchStart: item.matchStart, matchLength: item.matchLength, trailing: item.count === null ? item.caption : item.count.toLocaleString(LOCALE$2), announce: item.count === null ? `${item.label}, ${item.caption ?? ""}` : `${item.label}, ${postsLabel(item.count)}`, divider: at > 0 && item.group === "inside" && found.items[at - 1]?.group !== "inside" })) }; } /** What to say when a search found nothing. */ function describeEmptyResult(text, tags) { const word = unknownWords(text, tags)[0]; if (word === void 0) return { title: EMPTY_NO_MATCH, note: "", offer: null }; const closest = closestTag(tags, word); return { title: `${EMPTY_NO_TAG_PREFIX}${word}${EMPTY_NO_TAG_SUFFIX}`, note: closest === null ? EMPTY_NOTE_NONE : EMPTY_NOTE_CLOSEST, offer: closest === null ? null : { word, tag: closest.tag, count: closest.count } }; } /** The query with one word put in place of another, the rest as typed. */ function replaceWord(text, word, tag) { return text.trim().split(/\s+/).map((part) => part.toLowerCase() === word ? tag : part).join(" "); } function buildEmptyNode(result, onOffer) { const node = document.createElement("div"); node.className = EMPTY_CLASS; node.setAttribute("role", "status"); const title = document.createElement("strong"); title.textContent = result.title; node.append(title); if (result.note.length > 0) { const note = document.createElement("span"); note.textContent = result.note; node.append(note); } const { offer } = result; if (offer !== null) { const button = document.createElement("button"); button.type = "button"; button.className = "rdw-btn rdw-kit-focusable rdw-btn--secondary rdw-btn--m"; button.textContent = `${EMPTY_SHOW_PREFIX}${offer.tag} (${offer.count.toLocaleString(LOCALE$2)})`; button.addEventListener("click", () => { onOffer(offer.word, offer.tag); }); node.append(button); } return node; } /** Gives the page back to the site's grid and pager. */ function hideFavoriteResults() { document.body.classList.remove(FAVORITES_BROWSING_BODY_CLASS); if (grid !== null) { grid.container.replaceChildren(); grid.results = []; grid.shown = 0; grid.more.hidden = true; } } /** "11,962 posts"; a count of none is said too, unlike in the page's own total. */ function postsLabel(count) { return `${count.toLocaleString(LOCALE$2)} ${count === 1 ? "post" : "posts"}`; } /** Says so when the index does not hold every favorite; nothing otherwise. */ function indexNotice(indexed, favorites) { if (indexed >= favorites) return ""; return `The index holds ${indexed.toLocaleString(LOCALE$2)} of ${favorites.toLocaleString(LOCALE$2)} favorites; Full resync in RuleDesk → Favorites adds the rest.`; } /** * What the warning says of the typed terms the index cannot answer; nothing * when there are none. A metatag is named by its name (`rating:`), not by the * whole term: it is the kind of condition that does not work here, whatever * its value. No way out is offered: the search on Posts covers the whole * site, not the favorites, and the site has no metatag for "my favorites" * (`fav:` is read as an ordinary tag there). */ function unsupportedNotice(terms) { const names = []; for (const raw of terms) { const term = raw.startsWith(EXCLUDE_SIGN) ? raw.slice(1) : raw; const at = term.indexOf(META_SEPARATOR); const name = at > 0 ? term.slice(0, at + 1) : term; if (!names.includes(name)) names.push(name); } if (names.length === 0) return ""; return `${names.join(", ")}${names.length === 1 ? UNSUPPORTED_ONE : UNSUPPORTED_MANY}${UNSUPPORTED_TAIL}`; } /** True once a sync of the favorites has finished: the local list is then whole, or was. */ function favoritesSynced() { return getSyncState()?.finishedAt !== void 0; } /** Opens a random post of the local list of favorites. */ function openRandomFavorite() { const ids = [...loadFavSet()]; const id = ids[Math.floor(Math.random() * ids.length)]; if (id !== void 0) window.location.assign(`${POST_HREF_PREFIX}${String(id)}`); } /** * "cat* -video · Images · wallpapers": what the list is narrowed to, for the * selection bar and for the download of the results. Empty when nothing narrows it. */ function favoritesFilterSummary(text, media, collection = "") { const parts = []; const query = text.trim(); if (query.length > 0) parts.push(query); const option = MEDIA_OPTIONS$1.find((item) => item.value === media); if (media !== "all" && option !== void 0) parts.push(option.label); if (collection.length > 0) parts.push(collection); return parts.join(" · "); } function FavoritesBrowser(props = {}) { const [text, setText] = d(""); const [applied, setApplied] = d(""); const [media, setMedia] = d("all"); const [view, setView] = d(() => readView()); const [index, setIndex] = d(null); const [status, setStatus] = d(""); const [found, setFound] = d(null); const loadingRef = T(false); const rowRef = T(null); const actionsSlotRef = T(null); const [shuffleSeed, setShuffleSeed] = d(null); const [order, setOrder] = d(ORDER_NEWEST); const [collection, setCollection] = d("any"); const [aiHidden, setAiHidden] = d(() => aiHiddenIn(AI_SCOPE_FAVORITES)); const [indexPartial, setIndexPartial] = d(false); const [synced, setSynced] = d(() => favoritesSynced()); A(() => { const check = () => { setSynced(favoritesSynced()); }; window.addEventListener("hashchange", check); return () => { window.removeEventListener("hashchange", check); }; }, []); const aiEverywhere = aiHiddenEverywhere(); const [followedAll, setFollowedAll] = d(false); const { sideHost } = props; const stacked = sideHost !== null && sideHost !== void 0; const column = stacked ? sideHost.closest(`.rdw-fav-side`) ?? sideHost : null; const unsynced = stacked && !synced; const query = parseFavoritesQuery(applied); const active = view === VIEW_SCROLL || media !== "all" || shuffleSeed !== null || order !== "newest" || collection !== "any" || aiHidden || !isEmptyFavoritesQuery(query); const { onSummary } = props; A(() => { const parts = [(collection === "any" ? void 0 : collectionChoices(load$1().collections).find((option) => option.value === collection))?.label ?? "", aiHidden ? NO_AI_SUMMARY : ""].filter((part) => part.length > 0); onSummary?.(favoritesFilterSummary(applied, media, parts.join(" · "))); }, [ onSummary, applied, media, collection, aiHidden ]); const loadIndex = () => { if (loadingRef.current) return; loadingRef.current = true; readFavoriteIndex().then((entries) => { setIndex(entries); }).catch((error) => { log.warn("favorites-browser: index read failed", error); setIndex([]); }); }; A(() => { if (text.length > 0 && index === null) loadIndex(); }, [text, index]); A(() => { if (!stacked || load$1().artists.length === 0) return; const timer = window.setTimeout(loadIndex, 0); return () => { window.clearTimeout(timer); }; }, [stacked]); const tagCounts = w$1(() => index === null ? [] : favoriteTagCounts(index, loadFavSet()), [index]); const followed = w$1(() => tagCounts.length === 0 ? [] : followedInFavorites(load$1().artists, tagCounts), [tagCounts]); const suggest = w$1(() => ({ label: SUGGEST_LABEL, list: (value, caret) => toSuggestList(suggestFor(tagCounts, wordAtCaret(value, caret))), pick: (value, caret, at) => { const word = wordAtCaret(value, caret); const item = suggestFor(tagCounts, word)?.items[at]; return word === null || item === void 0 ? null : completeWord(value, word, item.insert); } }), [tagCounts]); A(() => { if (column === null) return; const sync = () => { const hidden = column.scrollHeight - column.scrollTop - column.clientHeight; column.classList.toggle(SIDE_MORE_CLASS, hidden > SCROLL_END_SLACK_PX); }; sync(); column.addEventListener("scroll", sync, { passive: true }); window.addEventListener("resize", sync, { passive: true }); const observer = typeof ResizeObserver === "function" ? new ResizeObserver(sync) : null; observer?.observe(column); return () => { column.removeEventListener("scroll", sync); window.removeEventListener("resize", sync); observer?.disconnect(); }; }, [column]); const locked = props.locked === true; A(() => { column?.classList.toggle(SIDE_LOCKED_CLASS, locked); }, [column, locked]); A(() => { onRemoveFailed = () => { setStatus(REMOVE_FAILED_STATUS); }; return () => { onRemoveFailed = null; }; }, []); A(() => { if (!active || unsynced) { hideFavoriteResults(); setStatus(""); setIndexPartial(false); setFound(null); return; } if (index === null) { loadIndex(); return; } const timer = window.setTimeout(() => { const favorites = loadFavSet(); if (index.length === 0) { hideFavoriteResults(); setStatus(NO_INDEX_STATUS); setFound(null); return; } const typed = parseFavoritesQuery(applied); const scope = collectionScope(load$1().collections, collection); const asked = aiHidden ? { ...typed, exclude: [...typed.exclude, ...parseFavoritesQuery(NO_AI_TERM).exclude] } : typed; const byQuery = filterFavoriteIndex(index, favorites, asked, media); const inSiteOrder = scope === null ? byQuery : byQuery.filter((entry) => scope(entry.id)); const matched = typed.sort === null && order === "oldest" ? [...inSiteOrder].reverse() : inSiteOrder; const results = shuffleSeed === null ? matched : shuffleBySeed(matched, shuffleSeed); if (results.length === 0 && !isEmptyFavoritesQuery(typed)) showFavoriteEmpty(buildEmptyNode(describeEmptyResult(applied, tagCounts), (word, tag) => { const next = replaceWord(applied, word, tag); setText(next); setApplied(next); })); else if (results.length === 0 && scope !== null) showFavoriteEmpty(buildEmptyNode({ title: EMPTY_COLLECTION, note: EMPTY_COLLECTION_NOTE, offer: null }, () => void 0)); else showFavoriteResults(results); const indexed = index.filter((entry) => favorites.has(entry.id)).length; setStatus(indexNotice(indexed, favorites.size)); setIndexPartial(indexed < favorites.size); setFound(results.length); }, TYPING_PAUSE_MS); return () => { window.clearTimeout(timer); }; }, [ active, unsynced, index, applied, media, shuffleSeed, order, tagCounts, collection, aiHidden ]); const warning = unsupportedNotice(query.unsupported); const notices = [shuffleSeed !== null && query.sort !== null ? SHUFFLE_OVER_SORT_NOTICE : "", status].filter((line) => line.length > 0); const total = loadFavSet().size; const count = found !== null ? postsLabel(found) : total > 0 ? postsLabel(total) : ""; const { actionsRef } = props; A(() => { actionsRef?.(actionsSlotRef.current); return () => { actionsRef?.(null); }; }, [actionsRef]); const chips = queryChips(text); const setQuery = (next) => { setText(next); setApplied(next); }; const sortValue = shuffleSeed !== null ? ORDER_SHUFFLE : order; const collectionOptions = collectionChoices(load$1().collections); const collectionValue = collectionOptions.some((option) => option.value === collection) ? collection : "any"; const followedShown = followedAll ? followed : followed.slice(0, 12); const viewSwitch = /* @__PURE__ */ a(Segmented, { label: VIEW_LABEL, options: VIEW_OPTIONS, value: view, onChange: (value) => { if (isFavoritesView(value)) { setFeatureState(VIEW_STATE_ID, value); setView(value); } } }); const filters = /* @__PURE__ */ a($$1, { children: [ locked && props.onUnlock !== void 0 ? /* @__PURE__ */ a("div", { className: SIDE_LOCK_CLASS, role: "status", children: [/* @__PURE__ */ a("span", { children: LOCKED_NOTICE }), /* @__PURE__ */ a(Button, { variant: "ghost", size: "s", onClick: () => props.onUnlock?.(), children: UI_TEXT.cancel })] }) : null, /* @__PURE__ */ a("div", { className: SIDE_BODY_CLASS, ...locked ? { inert: true } : {}, children: [ /* @__PURE__ */ a("div", { className: SIDE_HEAD_CLASS, children: [/* @__PURE__ */ a(SectionLabel, { children: SIDE_TITLE }), stacked && !unsynced && count.length > 0 ? /* @__PURE__ */ a("span", { className: COUNT_CLASS$2, role: "status", children: count }) : null] }), unsynced ? /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("p", { className: WARNING_CLASS, role: "status", children: UNSYNCED_NOTE }), /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: () => { openSettingsAt(SETTINGS_SECTION_FAVORITES); }, children: UNSYNCED_BUTTON })] }) : /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a(SearchField, { id: SEARCH_FIELD_ID, className: SEARCH_BOX_CLASS, value: text, placeholder: SEARCH_PLACEHOLDER, "aria-label": SEARCH_ARIA_LABEL, clearLabel: CLEAR_LABEL$1, help: SEARCH_HELP, suggest, onFocus: loadIndex, onChange: setText, onCommit: setApplied }), warning.length > 0 ? /* @__PURE__ */ a("p", { className: WARNING_CLASS, role: "status", children: warning }) : null, notices.length > 0 ? /* @__PURE__ */ a("span", { className: STATUS_CLASS$2, role: "status", children: [notices.join(" "), indexPartial ? /* @__PURE__ */ a($$1, { children: [" ", /* @__PURE__ */ a("button", { type: "button", className: `${SYNC_LINK_CLASS} rdw-kit-focusable`, onClick: () => { openSettingsAt(SETTINGS_SECTION_FAVORITES); }, children: SYNC_NOW })] }) : null] }) : null, chips.length > 0 ? /* @__PURE__ */ a("div", { className: CHIPS_CLASS$1, role: "group", "aria-label": CHIPS_LABEL, children: chips.map((chip) => /* @__PURE__ */ a("button", { type: "button", className: `${CHIP_BUTTON_CLASS} rdw-kit-focusable`, title: chip.group ? void 0 : CHIP_EXCLUDE_TITLE, "aria-pressed": chip.group ? void 0 : chip.excluded, onClick: (event) => { const target = event.target; if (target instanceof Element && target.closest("button") !== event.currentTarget) return; setQuery(toggleChip(text, chip)); }, children: /* @__PURE__ */ a(Chip, { label: chip.label, variant: chip.group ? "group" : chip.excluded ? "exclude" : "dot", kind: chip.group || chip.excluded ? "default" : chipKindOfTag(chip.label), onRemove: () => { setQuery(removeChip(text, chip)); } }) }, `${String(chip.start)}:${chip.label}`)) }) : null, /* @__PURE__ */ a("div", { className: SIDE_GROUP_CLASS, children: [/* @__PURE__ */ a(SectionLabel, { children: MEDIA_LABEL }), /* @__PURE__ */ a(Segmented, { label: MEDIA_LABEL, options: MEDIA_OPTIONS$1, value: media, onChange: (value) => { if (isFavoritesMedia(value)) setMedia(value); } })] }), /* @__PURE__ */ a("div", { className: SIDE_GROUP_CLASS, children: [ /* @__PURE__ */ a(SectionLabel, { children: AI_LABEL }), /* @__PURE__ */ a(Segmented, { label: AI_LABEL, options: AI_MODE_OPTIONS, value: aiHidden ? AI_MODE_HIDE : AI_MODE_SHOW, disabled: aiEverywhere, onChange: (value) => { if (aiEverywhere) return; const hide = value === AI_MODE_HIDE; setAiHiddenIn(AI_SCOPE_FAVORITES, hide); setAiHidden(hide); } }), aiEverywhere ? /* @__PURE__ */ a(AiEverywhereNote, {}) : null ] }), /* @__PURE__ */ a("div", { className: SIDE_GROUP_CLASS, children: [/* @__PURE__ */ a(SectionLabel, { children: COLLECTION_LABEL }), /* @__PURE__ */ a(Select, { options: collectionOptions, value: collectionValue, onChange: setCollection })] }), /* @__PURE__ */ a("div", { className: SIDE_GROUP_CLASS, children: [ /* @__PURE__ */ a(SectionLabel, { children: SORT_LABEL }), /* @__PURE__ */ a(Segmented, { label: SORT_LABEL, options: SORT_OPTIONS$1, value: sortValue, onChange: (value) => { if (value === "shuffle") { setShuffleSeed(Date.now()); setOrder(ORDER_NEWEST); } else if (isFavoritesOrder(value)) { setShuffleSeed(null); setOrder(value); } } }), shuffleSeed !== null ? /* @__PURE__ */ a("p", { className: SIDE_HINT_CLASS, children: RESHUFFLE_HINT }) : null ] }), stacked ? /* @__PURE__ */ a("div", { className: SIDE_GROUP_CLASS, children: [/* @__PURE__ */ a(SectionLabel, { children: VIEW_LABEL }), viewSwitch] }) : null, text.trim().length > 0 || media !== "all" || collection !== "any" ? /* @__PURE__ */ a("div", { children: /* @__PURE__ */ a(Button, { variant: "ghost", size: "s", onClick: () => { setQuery(""); setMedia("all"); setCollection("any"); }, children: RESET_LABEL$1 }) }) : null ] }), stacked ? /* @__PURE__ */ a("div", { className: `${ACTIONS_CLASS$1} ${SIDE_ACTIONS_CLASS}`, ref: actionsSlotRef }) : null ] }), stacked && !unsynced && followed.length > 0 ? /* @__PURE__ */ a("div", { className: `${SIDE_BODY_CLASS} ${FOLLOWED_CARD_CLASS}`, ...locked ? { inert: true } : {}, children: [ /* @__PURE__ */ a(SectionLabel, { children: FOLLOWED_TITLE }), /* @__PURE__ */ a("ul", { className: FOLLOWED_LIST_CLASS, children: followedShown.map((item) => /* @__PURE__ */ a("li", { children: /* @__PURE__ */ a("button", { type: "button", className: `${FOLLOWED_ROW_CLASS} rdw-kit-focusable`, "aria-pressed": queryHasTag(text, item.tag), [FOLLOWED_KIND_ATTR]: item.kind, onClick: () => { setQuery(toggleQueryTag(text, item.tag)); }, children: [ /* @__PURE__ */ a("span", { className: FOLLOWED_DOT_CLASS, "aria-hidden": "true" }), /* @__PURE__ */ a("span", { className: FOLLOWED_NAME_CLASS, children: item.tag }), /* @__PURE__ */ a("span", { className: FOLLOWED_COUNT_CLASS, children: item.count.toLocaleString(LOCALE$2) }) ] }) }, item.tag)) }), followed.length > 12 ? /* @__PURE__ */ a("div", { children: /* @__PURE__ */ a(Button, { variant: "ghost", size: "s", onClick: () => { setFollowedAll(!followedAll); }, children: followedAll ? FOLLOWED_SHOW_LESS : `${FOLLOWED_SHOW_ALL} (${followed.length.toLocaleString(LOCALE$2)})` }) }) : null ] }) : null ] }); if (stacked) return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: FAVORITES_BROWSER_CSS }), U(filters, sideHost)] }); return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("style", { children: FAVORITES_BROWSER_CSS }), filters, /* @__PURE__ */ a("div", { className: CONTROLS_CLASS, ref: rowRef, children: [ count.length > 0 ? /* @__PURE__ */ a("span", { className: COUNT_CLASS$2, role: "status", children: count }) : null, /* @__PURE__ */ a("span", { className: GROUP_LABEL_CLASS, "aria-hidden": "true", children: VIEW_LABEL }), viewSwitch, /* @__PURE__ */ a("div", { className: ACTIONS_CLASS$1, ref: actionsSlotRef }) ] }) ] }); } var BASE_GRID_CSS = ` .${THUMB_CLASS} { position: relative; anchor-scope: ${THUMB_ANCHOR_NAME}; } .${THUMB_CLASS} img.preview, .${THUMB_CLASS} > a > img { anchor-name: ${THUMB_ANCHOR_NAME}; } `; /** Grid thumbnail CDN host (rule34.xxx). */ var THUMB_IMAGE_HOST = "wimg.rule34.xxx"; /** * Video CDN origin. Path after origin starts with `//images/` (verified double * slash on ws-cdn-video.rule34.xxx). */ var VIDEO_CDN_ORIGIN = "https://ws-cdn-video.rule34.xxx"; /** Repeated slashes are accepted: the favorites page writes `/thumbnails///`. */ var THUMB_PATH_PATTERN = /^\/+thumbnails\/+([^/]+)\/+thumbnail_([^/]+)\.jpg$/i; var HTTPS_PROTOCOL = "https:"; var THUMB_DIRECTORY = "thumbnails"; var THUMB_FILE_PREFIX = "thumbnail_"; var THUMB_FILE_EXT = "jpg"; var MIN_POST_ID = 0; var VIDEO_CDN_HOST = new URL(VIDEO_CDN_ORIGIN).hostname; /** `/samples//sample_.` with repeated slashes allowed. */ var SAMPLE_MEDIA_PATTERN = /^\/+samples\/+([^/]+)\/+sample_([^/]+)\.[^/.]+$/i; /** `/images//.` with repeated slashes allowed. */ var IMAGE_MEDIA_PATTERN = /^\/+images\/+([^/]+)\/+([^/]+)\.[^/.]+$/i; function normalizeMediaPostId(postId) { if (!Number.isInteger(postId) || postId < MIN_POST_ID) return null; return postId; } function readMediaDirAndHash(pathname) { const sample = SAMPLE_MEDIA_PATTERN.exec(pathname); const image = sample === null ? IMAGE_MEDIA_PATTERN.exec(pathname) : null; const match = sample ?? image; if (match === null) return null; const dir = match[1]; const hash = match[2]; if (dir === void 0 || hash === void 0 || dir.length === 0 || hash.length === 0) return null; return { dir, hash }; } function ensureThumbAnchor(thumb) { thumb.classList.add(THUMB_CLASS); } /** * Build the CDN mp4 URL from a grid webm thumb `img.preview` src. * Thumb: `https://wimg.rule34.xxx/thumbnails//thumbnail_.jpg?`, * or the same path on `rule34.xxx` for a post uploaded minutes ago * Video: `https://ws-cdn-video.rule34.xxx//images//.mp4?` * Unparseable input → null (no guessing). */ function buildVideoUrlFromThumbUrl(thumbUrl) { let parsed; try { parsed = new URL(thumbUrl); } catch { return null; } if (!isSiteUrl(thumbUrl)) return null; const match = THUMB_PATH_PATTERN.exec(parsed.pathname); if (match === null) return null; const dir = match[1]; const hash = match[2]; if (dir === void 0 || hash === void 0 || dir.length === 0 || hash.length === 0) return null; return `${VIDEO_CDN_ORIGIN}//images/${dir}/${hash}.mp4${parsed.search}`; } /** * Thumb URL for a sample or full-media CDN URL. * Sample: `https://wimg.rule34.xxx//samples//sample_.?` * Image/video: `https://ws-cdn-video.rule34.xxx//images//.?` * Result: `https://wimg.rule34.xxx/thumbnails//thumbnail_.jpg?` * Repeated slashes in the path are accepted. Unparseable input → null. * The query is `postId` (the caller’s post), not whatever query the media URL had. */ function deriveThumbUrlFromMedia(mediaUrl, postId) { const normalizedId = normalizeMediaPostId(postId); if (normalizedId === null) return null; let parsed; try { parsed = new URL(mediaUrl); } catch { return null; } if (parsed.protocol !== HTTPS_PROTOCOL) return null; if (parsed.hostname !== "wimg.rule34.xxx" && parsed.hostname !== VIDEO_CDN_HOST) return null; const media = readMediaDirAndHash(parsed.pathname); if (media === null) return null; return `https://${THUMB_IMAGE_HOST}/${THUMB_DIRECTORY}/${media.dir}/${THUMB_FILE_PREFIX}${media.hash}.${THUMB_FILE_EXT}?${String(normalizedId)}`; } var COLLECTION_PICKER_CLASS = "rdw-collection-picker"; var COLLECTION_PICKER_ITEM_CLASS = "rdw-collection-picker-item"; var COLLECTION_PICKER_COUNT_CLASS = "rdw-collection-picker-count"; var COLLECTION_PICKER_NEW_CLASS = "rdw-collection-picker-new"; var CLASS_LIST = "rdw-collection-picker-list"; var CLASS_CHECK = "rdw-collection-picker-check"; var CLASS_NAME$1 = "rdw-collection-picker-name"; var CLASS_EMPTY = "rdw-collection-picker-empty"; var CLASS_NEW_FIELD = "rdw-collection-picker-new-field"; var CLASS_ERROR$1 = "rdw-collection-picker-error"; var COLLECTION_PICKER_TEXT = { create: "Create", newName: "New collection name", filter: "Filter collections…", empty: "No collections yet", noMatch: "No matching collections", togglePrefix: "Toggle collection", nameTaken: "A collection with this name already exists.", list: "Custom collections" }; var MEMBER_ROLE = "menuitemcheckbox"; var CHECK_ICON_PX = 12; var CHECK_BOX_PX = 15; var ROW_GAP_PX = 8; var STACK_GAP_PX = 6; var COLLECTION_PICKER_CSS = ` .${COLLECTION_PICKER_CLASS} { display: grid; grid-template-columns: minmax(0, 1fr); gap: ${String(STACK_GAP_PX)}px; min-width: 0; color: var(--rdw-text); font: 12px/1.35 var(--rdw-font); } .${CLASS_LIST} { display: grid; grid-template-columns: minmax(0, 1fr); gap: 2px; max-height: ${String(232)}px; overflow-x: hidden; overflow-y: auto; } button.${COLLECTION_PICKER_ITEM_CLASS} { display: flex; align-items: center; gap: ${String(ROW_GAP_PX)}px; box-sizing: border-box; width: 100%; min-height: ${String(28)}px; margin: 0; padding: 0 6px; border: 0; border-radius: var(--rdw-radius-s); background: transparent; color: var(--rdw-text); font: inherit; font-weight: 400; text-align: left; cursor: pointer; } button.${COLLECTION_PICKER_ITEM_CLASS}:hover, button.${COLLECTION_PICKER_ITEM_CLASS}:focus-visible { background: var(--rdw-surface-2); } button.${COLLECTION_PICKER_ITEM_CLASS}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: -2px; } .${CLASS_CHECK} { flex: 0 0 ${String(CHECK_BOX_PX)}px; display: inline-grid; place-items: center; box-sizing: border-box; width: ${String(CHECK_BOX_PX)}px; height: ${String(CHECK_BOX_PX)}px; border: 1px solid var(--rdw-border); border-radius: 4px; background: transparent; color: var(--rdw-surface); } .${COLLECTION_PICKER_ITEM_CLASS}[aria-checked="true"] .${CLASS_CHECK} { background: var(--rdw-accent); border-color: var(--rdw-accent); } .${CLASS_NAME$1} { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .${COLLECTION_PICKER_COUNT_CLASS} { flex: 0 0 auto; color: var(--rdw-muted); font-variant-numeric: tabular-nums; } .${CLASS_EMPTY} { margin: 0; padding: 4px 6px; color: var(--rdw-muted); } form.${COLLECTION_PICKER_NEW_CLASS} { display: flex; align-items: center; gap: ${String(STACK_GAP_PX)}px; margin: 0; padding-top: ${String(STACK_GAP_PX)}px; border-top: 1px solid var(--rdw-border); } .${CLASS_ERROR$1} { margin: 0; color: var(--rdw-danger); } .${COLLECTION_PICKER_NEW_CLASS} .${CLASS_NEW_FIELD} { flex: 1 1 auto; min-width: 0; margin: 0; } `.trim(); function foldName$1(name) { return name.trim().toLowerCase(); } function matchesFilter(collection, filter) { const needle = foldName$1(filter); return needle.length === 0 || collection.name.toLowerCase().includes(needle); } function addPost(collectionId, postId, readThumbUrl) { const thumbUrl = readThumbUrl(); if (thumbUrl === null) { addPostToCollection(collectionId, postId); return; } addPostToCollection(collectionId, postId, thumbUrl); } /** * Custom collections of one post: a checkbox row per collection with its post * count, and a "name + Create" row. Used by the post panel and the grid "+" menu. * A new name that any collection already has (custom or dynamic, ignoring * case) is refused, as on the Collections page. */ function CollectionPicker(props) { const [filter, setFilter] = d(""); const [newName, setNewName] = d(""); const [error, setError] = d(""); const [, setRevision] = d(0); const collections = listPlaylists(); const memberIds = new Set(playlistsContaining(props.postId).map((item) => item.id)); const filterShown = collections.length > 8; const visible = filterShown ? collections.filter((item) => matchesFilter(item, filter)) : collections; const changed = () => { setRevision((value) => value + 1); props.onChange?.(); }; const toggle = (collectionId) => { if (memberIds.has(collectionId)) removePostFromPlaylist(collectionId, props.postId); else addPost(collectionId, props.postId, props.readThumbUrl); changed(); }; const createFromName = () => { const name = newName.trim(); if (name.length === 0) return; if (load$1().collections.some((item) => foldName$1(item.name) === foldName$1(name))) { setError(COLLECTION_PICKER_TEXT.nameTaken); return; } addPost(createPlaylist(name).id, props.postId, props.readThumbUrl); setNewName(""); changed(); }; const emptyText = collections.length === 0 ? COLLECTION_PICKER_TEXT.empty : COLLECTION_PICKER_TEXT.noMatch; return /* @__PURE__ */ a("div", { className: COLLECTION_PICKER_CLASS, children: [ /* @__PURE__ */ a("style", { children: COLLECTION_PICKER_CSS }), filterShown ? /* @__PURE__ */ a(TextField, { value: filter, onChange: setFilter, placeholder: COLLECTION_PICKER_TEXT.filter, "aria-label": COLLECTION_PICKER_TEXT.filter }) : null, visible.length === 0 ? /* @__PURE__ */ a("p", { className: CLASS_EMPTY, children: emptyText }) : /* @__PURE__ */ a("div", { className: CLASS_LIST, role: "group", "aria-label": COLLECTION_PICKER_TEXT.list, children: visible.map((collection) => /* @__PURE__ */ a("button", { type: "button", className: COLLECTION_PICKER_ITEM_CLASS, role: MEMBER_ROLE, "aria-checked": memberIds.has(collection.id), "aria-label": `${COLLECTION_PICKER_TEXT.togglePrefix} ${collection.name}`, onClick: (event) => { event.preventDefault(); event.stopPropagation(); toggle(collection.id); }, children: [ /* @__PURE__ */ a("span", { className: CLASS_CHECK, "aria-hidden": "true", children: memberIds.has(collection.id) ? /* @__PURE__ */ a(IconCheck, { size: CHECK_ICON_PX }) : null }), /* @__PURE__ */ a("span", { className: CLASS_NAME$1, children: collection.name }), /* @__PURE__ */ a("span", { className: COLLECTION_PICKER_COUNT_CLASS, children: String(collection.postIds?.length ?? 0) }) ] }, collection.id)) }), /* @__PURE__ */ a("form", { className: COLLECTION_PICKER_NEW_CLASS, onSubmit: (event) => { event.preventDefault(); event.stopPropagation(); createFromName(); }, children: [/* @__PURE__ */ a(TextField, { className: CLASS_NEW_FIELD, value: newName, onChange: (value) => { setNewName(value); setError(""); }, placeholder: COLLECTION_PICKER_TEXT.newName, "aria-label": COLLECTION_PICKER_TEXT.newName }), /* @__PURE__ */ a(Button, { type: "submit", variant: "primary", size: "s", disabled: newName.trim().length === 0, children: COLLECTION_PICKER_TEXT.create })] }), error.length > 0 ? /* @__PURE__ */ a("p", { className: CLASS_ERROR$1, role: "alert", children: error }) : null ] }); } /** * Puts a post into the favorites search index at the moment it is made a * favorite, from what the page already shows. Without this a new favorite * would be missing from the search on the Favorites page until the next * "Sync favorites". No requests. */ var POST_IMAGE_SELECTOR = "img#image"; var POST_VIDEO_SELECTOR = "video#gelcomVideoPlayer"; var VIDEO_SOURCE_SELECTOR$1 = "source"; var TAG_LINK_SELECTOR$1 = "a[href*='tags=']"; var TAG_JOIN = " "; /** The entry of a favorite made now: it sorts before everything indexed earlier. */ function buildLiveEntry(postId, tags, thumb, now) { const id = Number(postId); if (!Number.isInteger(id) || id <= 0 || tags.length === 0) return null; return { id, tags: tags.join(TAG_JOIN), thumb: thumb !== null && isSiteUrl(thumb) ? thumb : "", run: now, pos: 0, cut: false }; } function store(entry) { if (entry !== null) putFavoriteIndexEntriesQuietly([entry]); } /** A favorite made by the star of a grid thumb: tags and preview are on the thumb. */ function indexFavoriteFromThumb(postId, starButton) { const thumb = starButton.closest(SITE_SELECTORS.thumb); if (thumb === null) return; const image = thumb.querySelector(SITE_SELECTORS.previewImage); const src = image instanceof HTMLImageElement ? image.currentSrc || image.src : null; store(buildLiveEntry(postId, readThumbTags(thumb), src, Date.now())); } /** The tags of a post page, from the links of its tag sidebar. */ function readPostPageTags(root = document) { const tags = []; for (const row of root.querySelectorAll(SITE_SELECTORS.tagSidebarRow)) { const links = row.querySelectorAll(TAG_LINK_SELECTOR$1); const href = links[links.length - 1]?.getAttribute("href"); if (href === null || href === void 0) continue; let tag = null; try { tag = new URL(href, window.location.href).searchParams.get(SEARCH_PARAM_TAGS); } catch { tag = null; } if (tag !== null && tag.trim().length > 0) tags.push(tag.trim().toLowerCase()); } return tags; } function readPostMediaUrl() { const image = document.querySelector(POST_IMAGE_SELECTOR); if (image instanceof HTMLImageElement && image.src.length > 0) return image.src; const video = document.querySelector(POST_VIDEO_SELECTOR); if (!(video instanceof HTMLVideoElement)) return null; const source = video.querySelector(VIDEO_SOURCE_SELECTOR$1); const url = video.currentSrc || video.src || (source instanceof HTMLSourceElement ? source.src : ""); return url.length > 0 ? url : null; } /** A favorite made on the post page: tags from the sidebar, preview from the media address. */ function indexFavoriteFromPostPage(postId) { const media = readPostMediaUrl(); const thumb = media === null ? null : deriveThumbUrlFromMedia(media, Number(postId)); store(buildLiveEntry(postId, readPostPageTags(), thumb, Date.now())); } /** Kit IconButton root class — prefer for preview badges. */ var KIT_ICON_BUTTON_CLASS = "rdw-icon-btn"; function favAriaLabel(postId, marked) { return `${marked ? UI_TEXT.cardFavRemoveLabel : UI_TEXT.cardFavAddLabel} ${postId}`; } function applyFavButtonState(button, state, postId, errorTitle) { if (state === "pending") { button.disabled = true; button.classList.add(CSS_CLASS.cardFavPending); return; } button.classList.remove(CSS_CLASS.cardFavMarked, CSS_CLASS.cardFavError, CSS_CLASS.cardFavPending); button.disabled = false; button.removeAttribute("title"); if (state === "marked") { button.setAttribute("aria-pressed", "true"); button.setAttribute("aria-label", favAriaLabel(postId, true)); button.classList.add(CSS_CLASS.cardFavMarked); return; } if (state === "marked_error") { button.setAttribute("aria-pressed", "true"); button.setAttribute("aria-label", favAriaLabel(postId, true)); button.classList.add(CSS_CLASS.cardFavMarked, CSS_CLASS.cardFavError); button.title = errorTitle ?? UI_TEXT.cardFavErrorRequest; return; } if (state === "error") { button.setAttribute("aria-pressed", "false"); button.setAttribute("aria-label", favAriaLabel(postId, false)); button.classList.add(CSS_CLASS.cardFavError); button.title = errorTitle ?? UI_TEXT.cardFavErrorRequest; return; } button.setAttribute("aria-pressed", "false"); button.setAttribute("aria-label", favAriaLabel(postId, false)); } function createFavButton(postId, marked, className = CSS_CLASS.cardFav) { const button = document.createElement("button"); button.type = "button"; button.className = className; button.textContent = UI_TEXT.cardFavGlyph; applyFavButtonState(button, marked ? "marked" : "idle", postId); button.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); handleFavToggleClick(button, postId); }); return button; } async function handleFavToggleClick(button, postId) { if (button.disabled) return; const currentlyMarked = button.getAttribute("aria-pressed") === "true"; applyFavButtonState(button, "pending", postId); if (currentlyMarked) { const result = await removeFavorite(postId); if (result.status === "removed") { removeFav(postId); applyFavButtonState(button, "idle", postId); return; } applyFavButtonState(button, "marked_error", postId, UI_TEXT.cardFavErrorRequest); log.warn("Remove favorite failed", postId, result); return; } const result = await addFavorite(postId); if (result.status === "added" || result.status === "already") { addFav(postId); indexFavoriteFromThumb(postId, button); applyFavButtonState(button, "marked", postId); return; } if (result.status === "not_logged_in") { applyFavButtonState(button, "error", postId, UI_TEXT.cardFavErrorNotLoggedIn); log.warn("Favorite requires login", postId); return; } applyFavButtonState(button, "error", postId, UI_TEXT.cardFavErrorRequest); log.warn("Favorite failed", postId, result); } var FEATURE_ID$17 = "playlist-menu"; var FEATURE_LABEL$17 = "Add to collection button"; var FEATURE_PAGES$11 = [ "list", "post", "favorites" ]; var CLASS_ADD = "rdw-playlist-add"; var CLASS_ADD_IN = "rdw-playlist-add--in"; var CLASS_MENU = "rdw-playlist-menu"; var CLASS_MENU_POPUP = "rdw-playlist-menu--popup"; var ATTR_POST_ID = "data-rdw-post-id"; var TEXT_ADD_GLYPH = "+"; var LABEL_ADD = "Add to collection"; var MENU_Z_INDEX$1 = 2147483645; var MENU_WIDTH_PX$1 = 260; var MENU_PADDING_PX = 8; var MENU_GAP_PX = 4; var BUTTON_SIZE_PX = 28; var BUTTON_OFFSET_PX = 6; var BUTTON_BELOW_FAV_TOP_PX = 38; /** A favorites thumb: `div.image-list > span > span.thumb` (a search thumb has no wrapper). */ var FAVORITE_THUMB_SELECTOR = "div.image-list > span > span.thumb"; /** Set by the favorites bulk feature while posts are being selected. */ var FAVORITES_SELECTING_BODY_CLASS = "rdw-f-favorites-bulk-selecting"; var FOCUS_OUTLINE = "2px solid var(--rdw-accent)"; var FOCUS_OUTLINE_OFFSET = "2px"; var EVENT_KEYDOWN$1 = "keydown"; var EVENT_POINTERDOWN = "pointerdown"; var KEY_ESCAPE = "Escape"; var BODY_SELECTOR$4 = `body.${featureBodyClass(FEATURE_ID$17)}`; var FEATURE_CSS$15 = ` ${BODY_SELECTOR$4} .${CLASS_ADD} { position: absolute; top: ${String(BUTTON_BELOW_FAV_TOP_PX)}px; right: ${String(BUTTON_OFFSET_PX)}px; position-anchor: --rdw-img; top: calc(anchor(top) + ${String(BUTTON_BELOW_FAV_TOP_PX)}px); right: calc(anchor(right) + ${String(BUTTON_OFFSET_PX)}px); z-index: 5; box-sizing: border-box; display: inline-grid; place-items: center; min-width: ${String(BUTTON_SIZE_PX)}px; min-height: ${String(BUTTON_SIZE_PX)}px; width: ${String(BUTTON_SIZE_PX)}px; height: ${String(BUTTON_SIZE_PX)}px; padding: 0; border: 1px solid rgba(0, 0, 0, 0.13); border-radius: 8px; background: rgba(255, 255, 255, 0.93); color: #1c2228; cursor: pointer; font-size: 13px; font-weight: 700; line-height: 1; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2); opacity: 0; } ${BODY_SELECTOR$4} ${FAVORITE_THUMB_SELECTOR} > .${CLASS_ADD} { position-anchor: ${FAVORITE_IMAGE_ANCHOR_NAME}; } ${BODY_SELECTOR$4}.${FAVORITES_SELECTING_BODY_CLASS} ${FAVORITE_THUMB_SELECTOR} > .${CLASS_ADD} { display: none; } ${BODY_SELECTOR$4} .${THUMB_CLASS}:hover .${CLASS_ADD}, ${BODY_SELECTOR$4} .${CLASS_ADD}:focus-visible { opacity: 0.65; } ${BODY_SELECTOR$4} .${THUMB_CLASS} .${CLASS_ADD}:hover, ${BODY_SELECTOR$4} .${CLASS_ADD}:focus-visible { opacity: 1; } ${BODY_SELECTOR$4} .${CLASS_ADD}:focus-visible { outline: ${FOCUS_OUTLINE}; outline-offset: ${FOCUS_OUTLINE_OFFSET}; } ${BODY_SELECTOR$4} .${CLASS_ADD}.${CLASS_ADD_IN} { background: #ffd75e; border-color: #c79a00; color: #5c4500; } ${BODY_SELECTOR$4} .${CLASS_MENU} { box-sizing: border-box; width: ${String(MENU_WIDTH_PX$1)}px; max-width: calc(100vw - ${String(8)}px); padding: ${String(MENU_PADDING_PX)}px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); background: var(--rdw-surface); color: var(--rdw-text); font: 12px/1.35 var(--rdw-font); } ${BODY_SELECTOR$4} .${CLASS_MENU}.${CLASS_MENU_POPUP} { position: fixed; z-index: ${String(MENU_Z_INDEX$1)}; box-shadow: var(--rdw-shadow-2); } `; var NO_THUMB_URL = () => null; var unsubscribeThumbsAdded$4; var openPopup = null; var escapeBound = false; var pointerBound = false; function parsePostId(value) { if (value === null || value.length === 0) return null; const parsed = Number(value); if (!Number.isFinite(parsed)) return null; const truncated = Math.trunc(parsed); return truncated < 0 ? null : truncated; } function postInAnyPlaylist(postId) { return playlistsContaining(postId).length > 0; } function applyAddButtonState(button, postId) { const inPlaylist = postInAnyPlaylist(postId); button.classList.toggle(CLASS_ADD_IN, inPlaylist); button.setAttribute("aria-pressed", inPlaylist ? "true" : "false"); button.setAttribute("aria-label", `${LABEL_ADD} ${String(postId)}`); } function postAnchorSelector(postId) { return `#p${postId}`; } function readImageAddress(img) { const current = img.currentSrc.trim(); if (current.length > 0) return current; const attribute = img.getAttribute("src"); if (attribute === null) return null; const trimmed = attribute.trim(); if (trimmed.length === 0) return null; return trimmed; } /** * Thumb URL from this post's `img.preview`. * A preview outside `a#p{id}` wins. The copy nested in the link is used only * when that is the only preview (rule34 puts `img.preview` inside the anchor). */ function readPreviewThumbUrl(thumb, postId) { const anchor = thumb.querySelector(postAnchorSelector(postId)); const images = thumb.querySelectorAll(SITE_SELECTORS.previewImage); let nestedImage = null; for (const node of images) { if (!(node instanceof HTMLImageElement)) continue; if (anchor instanceof Element && anchor.contains(node)) { if (nestedImage === null) nestedImage = node; continue; } const url = readImageAddress(node); if (url !== null) return url; } if (nestedImage !== null) return readImageAddress(nestedImage); const plain = thumb.querySelector(THUMB_IMAGE_SELECTOR); return plain instanceof HTMLImageElement ? readImageAddress(plain) : null; } function readThumbUrlFromTrigger(button) { const postId = button.getAttribute(ATTR_POST_ID); if (postId === null || postId.length === 0) return null; const thumb = button.closest(SITE_SELECTORS.thumb); if (!(thumb instanceof HTMLElement)) return null; return readPreviewThumbUrl(thumb, postId); } function findThumbLink$2(thumb, postId) { const byId = thumb.querySelector(postAnchorSelector(postId)); if (byId instanceof HTMLAnchorElement) return byId; const byHref = thumb.querySelector(SITE_SELECTORS.thumbLink); return byHref instanceof HTMLAnchorElement ? byHref : null; } function closeOpenMenu() { if (openPopup === null) return; Q$1(null, openPopup.menu); openPopup.menu.remove(); openPopup.trigger.setAttribute("aria-expanded", "false"); openPopup = null; unbindGlobalCloseListeners(); } function onDocumentKeydown(event) { if (event.key !== KEY_ESCAPE) return; if (openPopup === null) return; event.preventDefault(); closeOpenMenu(); } function onDocumentPointerDown(event) { if (openPopup === null) return; const target = event.target; if (!(target instanceof Node)) return; if (openPopup.menu.contains(target) || openPopup.trigger.contains(target)) return; closeOpenMenu(); } function bindGlobalCloseListeners() { if (!escapeBound) { escapeBound = true; document.addEventListener(EVENT_KEYDOWN$1, onDocumentKeydown); } if (!pointerBound) { pointerBound = true; document.addEventListener(EVENT_POINTERDOWN, onDocumentPointerDown, true); } } function unbindGlobalCloseListeners() { if (escapeBound) { document.removeEventListener(EVENT_KEYDOWN$1, onDocumentKeydown); escapeBound = false; } if (pointerBound) { document.removeEventListener(EVENT_POINTERDOWN, onDocumentPointerDown, true); pointerBound = false; } } function positionMenuNear(menu, anchor) { const rect = anchor.getBoundingClientRect(); const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; menu.style.visibility = "hidden"; menu.style.left = "0"; menu.style.top = "0"; document.body.append(menu); const menuWidth = menu.offsetWidth; const menuHeight = menu.offsetHeight; let left = rect.right - menuWidth; if (left < MENU_GAP_PX) left = Math.min(rect.left, viewportWidth - menuWidth - MENU_GAP_PX); left = Math.max(MENU_GAP_PX, Math.min(left, viewportWidth - menuWidth - MENU_GAP_PX)); let top = rect.bottom + MENU_GAP_PX; if (top + menuHeight > viewportHeight - MENU_GAP_PX) top = rect.top - menuHeight - MENU_GAP_PX; if (top < MENU_GAP_PX) top = MENU_GAP_PX; menu.style.left = `${String(left)}px`; menu.style.top = `${String(top)}px`; menu.style.visibility = ""; } function syncAddButtonsForPost(postId) { const buttons = document.querySelectorAll(`button.${CLASS_ADD}[${ATTR_POST_ID}="${String(postId)}"]`); for (const node of buttons) { if (!(node instanceof HTMLButtonElement)) continue; applyAddButtonState(node, postId); } } /** * Brings every "+" on the page in step with the collections, after posts were * added by something other than the "+" itself (the selection bar). */ function refreshAddButtons() { for (const node of document.querySelectorAll(`button.${CLASS_ADD}[${ATTR_POST_ID}]`)) { const postId = Number(node.getAttribute(ATTR_POST_ID)); if (node instanceof HTMLButtonElement && Number.isFinite(postId)) applyAddButtonState(node, postId); } } /** * Builds the collection menu for a post: a themed panel holding the shared * collection picker. Callers own placement; the list page keeps one open at a time. */ function createPlaylistMenu(postId, options) { const root = document.createElement("div"); root.className = CLASS_MENU; root.setAttribute("role", "menu"); root.setAttribute(ATTR_POST_ID, String(postId)); const onChange = options?.onChange; Q$1(k$1(CollectionPicker, { postId, readThumbUrl: options?.readThumbUrl ?? NO_THUMB_URL, ...onChange === void 0 ? {} : { onChange } }), root); return root; } function openMenuForButton(button, postId) { if (openPopup !== null && openPopup.trigger === button) { closeOpenMenu(); return; } closeOpenMenu(); const menu = createPlaylistMenu(postId, { onChange: () => { syncAddButtonsForPost(postId); }, readThumbUrl: () => readThumbUrlFromTrigger(button) }); menu.classList.add(CLASS_MENU_POPUP); positionMenuNear(menu, button); button.setAttribute("aria-expanded", "true"); openPopup = { menu, trigger: button, postId }; bindGlobalCloseListeners(); } function attachAddButton(thumb, postId) { if (thumb.querySelector(`button.${CLASS_ADD}`) !== null) return; const numericId = parsePostId(postId); if (numericId === null) return; const link = findThumbLink$2(thumb, postId); if (link === null) return; ensureThumbAnchor(thumb); const button = document.createElement("button"); button.type = "button"; button.className = `${KIT_ICON_BUTTON_CLASS} ${CLASS_ADD}`; button.textContent = TEXT_ADD_GLYPH; button.setAttribute(ATTR_POST_ID, String(numericId)); button.setAttribute("aria-haspopup", "menu"); button.setAttribute("aria-expanded", "false"); applyAddButtonState(button, numericId); button.addEventListener("click", (event) => { event.preventDefault(); event.stopPropagation(); openMenuForButton(button, numericId); }); link.after(button); } function stampPlaylistButtons(root = document) { const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) { if (!(thumb instanceof HTMLElement)) continue; const postId = extractPostIdFromThumb(thumb) ?? extractPostIdFromThumbLink(thumb); if (postId === null) continue; attachAddButton(thumb, postId); } } function ensureListSubscriptions$1() { if (unsubscribeThumbsAdded$4 !== void 0) return; unsubscribeThumbsAdded$4 = onThumbsAdded((root) => { stampPlaylistButtons(root); }); } function mountPlaylistMenu(ctx) { if (ctx.pageKind !== "list" && ctx.pageKind !== "favorites") return; stampPlaylistButtons(document); ensureListSubscriptions$1(); } var playlistMenuFeature = { id: FEATURE_ID$17, label: FEATURE_LABEL$17, settingsCaption: "A “+” on each thumbnail and on the post page: it opens the list of custom collections.", pages: [...FEATURE_PAGES$11], defaultEnabled: true, css: FEATURE_CSS$15, mount: mountPlaylistMenu }; /** * Adds several posts to one custom collection at once: pick a collection, or * name a new one. Used by the selection bars of Posts and Favorites. Nothing * is requested: the posts and their previews are what the page already shows. */ var BULK_COLLECTION_CLASS = "rdw-bulk-collection"; var LIST_CLASS = "rdw-bulk-collection-list"; var ITEM_CLASS = "rdw-bulk-collection-item"; var NAME_CLASS$1 = "rdw-bulk-collection-name"; var COUNT_CLASS$1 = "rdw-bulk-collection-count"; var NEW_CLASS = "rdw-bulk-collection-new"; var NEW_FIELD_CLASS = "rdw-bulk-collection-new-field"; var TITLE_CLASS$3 = "rdw-bulk-collection-title"; var NOTE_CLASS = "rdw-bulk-collection-note"; var ERROR_CLASS = "rdw-bulk-collection-error"; var FOOT_CLASS$2 = "rdw-bulk-collection-foot"; var LIST_MAX_HEIGHT_PX = 260; /** The name filter appears once the list is longer than this. */ var FILTER_MIN = 8; var LOCALE$1 = "en-US"; var TEXT = { aria: "Add posts to a collection", filter: "Filter collections…", empty: "No custom collections yet. Name one below.", noMatch: "No matching collections", newName: "New collection name", create: "Create and add", nameTaken: "A collection with this name already exists." }; var BULK_COLLECTION_CSS = ` .${BULK_COLLECTION_CLASS} { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; color: var(--rdw-text); font: 13px/1.4 var(--rdw-font); } .${TITLE_CLASS$3} { margin: 0; font: 700 15px var(--rdw-font); color: var(--rdw-text); } .${NOTE_CLASS} { margin: 0; color: var(--rdw-muted); } .${LIST_CLASS} { display: grid; grid-template-columns: minmax(0, 1fr); gap: 2px; max-height: ${String(LIST_MAX_HEIGHT_PX)}px; overflow-x: hidden; overflow-y: auto; } button.${ITEM_CLASS} { display: flex; align-items: center; gap: 8px; box-sizing: border-box; width: 100%; min-height: 32px; margin: 0; padding: 0 8px; border: 0; border-radius: var(--rdw-radius-s); background: transparent; color: var(--rdw-text); font: inherit; font-weight: 400; text-align: left; cursor: pointer; } button.${ITEM_CLASS}:hover, button.${ITEM_CLASS}:focus-visible { background: var(--rdw-surface-2); } button.${ITEM_CLASS}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: -2px; } .${NAME_CLASS$1} { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .${COUNT_CLASS$1} { flex: none; color: var(--rdw-muted); font-variant-numeric: tabular-nums; } form.${NEW_CLASS} { display: flex; align-items: center; gap: 6px; margin: 0; padding-top: 10px; border-top: 1px solid var(--rdw-border); } .${NEW_CLASS} .${NEW_FIELD_CLASS} { flex: 1 1 auto; min-width: 0; margin: 0; } .${ERROR_CLASS} { margin: 0; color: var(--rdw-danger); } .${FOOT_CLASS$2} { display: flex; justify-content: flex-end; } `.trim(); function foldName(name) { return name.trim().toLowerCase(); } function postsWord(count) { return `${count.toLocaleString(LOCALE$1)} ${count === 1 ? "post" : "posts"}`; } /** "Add 12 posts to a collection". */ function bulkCollectionTitle(count) { return `Add ${postsWord(count)} to a collection`; } /** "Added 12 posts to “name”." or "Added 3 of 12 posts to “name”; the rest were already there." */ function bulkCollectionSummary(result) { if (result.added === result.total) return `Added ${postsWord(result.total)} to “${result.name}”.`; if (result.added === 0) return `All ${postsWord(result.total)} were already in “${result.name}”.`; return `Added ${result.added.toLocaleString(LOCALE$1)} of ${postsWord(result.total)} to “${result.name}”; the rest were already there.`; } function BulkCollectionDialog(props) { const [filter, setFilter] = d(""); const [newName, setNewName] = d(""); const [error, setError] = d(""); const collections = props.open ? listPlaylists() : []; const filterShown = collections.length > FILTER_MIN; const needle = foldName(filter); const visible = filterShown && needle.length > 0 ? collections.filter((item) => item.name.toLowerCase().includes(needle)) : collections; const close = () => { setFilter(""); setNewName(""); setError(""); props.onClose(); }; const addTo = (collectionId) => { const result = addPostsToCollection(collectionId, props.posts); if (result === null) return; const done = { name: result.collection.name, added: result.added, total: props.posts.length }; close(); props.onDone(done); }; const createAndAdd = () => { const name = newName.trim(); if (name.length === 0) return; if (load$1().collections.some((item) => foldName(item.name) === foldName(name))) { setError(TEXT.nameTaken); return; } addTo(createPlaylist(name).id); }; return /* @__PURE__ */ a(Dialog, { open: props.open, onClose: close, "aria-label": TEXT.aria, className: BULK_COLLECTION_CLASS, children: [ /* @__PURE__ */ a("style", { children: BULK_COLLECTION_CSS }), /* @__PURE__ */ a("h3", { className: TITLE_CLASS$3, children: bulkCollectionTitle(props.posts.length) }), filterShown ? /* @__PURE__ */ a(TextField, { value: filter, onChange: setFilter, placeholder: TEXT.filter, "aria-label": TEXT.filter }) : null, visible.length === 0 ? /* @__PURE__ */ a("p", { className: NOTE_CLASS, children: collections.length === 0 ? TEXT.empty : TEXT.noMatch }) : /* @__PURE__ */ a("div", { className: LIST_CLASS, children: visible.map((collection) => /* @__PURE__ */ a("button", { type: "button", className: ITEM_CLASS, onClick: () => { addTo(collection.id); }, children: [/* @__PURE__ */ a("span", { className: NAME_CLASS$1, children: collection.name }), /* @__PURE__ */ a("span", { className: COUNT_CLASS$1, children: String(collection.postIds?.length ?? 0) })] }, collection.id)) }), /* @__PURE__ */ a("form", { className: NEW_CLASS, onSubmit: (event) => { event.preventDefault(); event.stopPropagation(); createAndAdd(); }, children: [/* @__PURE__ */ a(TextField, { className: NEW_FIELD_CLASS, value: newName, onChange: (value) => { setNewName(value); setError(""); }, placeholder: TEXT.newName, "aria-label": TEXT.newName }), /* @__PURE__ */ a(Button, { type: "submit", variant: "primary", size: "s", disabled: newName.trim().length === 0, children: TEXT.create })] }), error.length > 0 ? /* @__PURE__ */ a("p", { className: ERROR_CLASS, role: "alert", children: error }) : null, /* @__PURE__ */ a("div", { className: FOOT_CLASS$2, children: /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: close, children: UI_TEXT.cancel }) }) ] }); } var removeClickBound = false; var POST_LINK_ID_PREFIX = "p"; /** * Resolve a favorites-page thumb's post id from Remove onclick, thumb id, or a#p{ID}. */ function resolveFavoriteThumbPostId(thumb) { const removeLinks = thumb.querySelectorAll(SITE_SELECTORS.favoritesDeleteLink); for (const link of removeLinks) { if (!(link instanceof HTMLAnchorElement)) continue; const onclick = link.getAttribute("onclick"); if (onclick === null) continue; const fromOnclick = extractPostIdFromFavoritesDeleteOnclick(onclick); if (fromOnclick !== null) return fromOnclick; } const fromThumbId = extractPostIdFromThumb(thumb); if (fromThumbId !== null) return fromThumbId; const postLinks = thumb.querySelectorAll(`a[id^="${POST_LINK_ID_PREFIX}"]`); for (const link of postLinks) { if (!(link instanceof HTMLAnchorElement)) continue; const id = link.id; if (!id.startsWith(POST_LINK_ID_PREFIX)) continue; const postId = id.slice(1); if (/^\d+$/.test(postId)) return postId; } return null; } /** Current-page favorite thumbs that have a resolvable post id. */ function listFavoriteThumbEntries(root = document) { const entries = []; const seen = /* @__PURE__ */ new Set(); const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const node of thumbs) { if (!(node instanceof HTMLElement)) continue; const postId = resolveFavoriteThumbPostId(node); if (postId === null || seen.has(postId)) continue; seen.add(postId); entries.push({ thumb: node, postId }); } return entries; } var CELL_SEPARATOR_TAGS = /* @__PURE__ */ new Set([ "BR", "HR", "WBR" ]); var CELL_SEPARATOR_TEXT_PATTERN = /^[|\u00b7•·,\s]*$/; /** * True for Remove links / light separators that belong to a favorites cell. * Stops adjacency walks before paginator, scripts, and other page chrome. */ function isFavoriteCellResidue(node, postId) { if (node.nodeType === Node.TEXT_NODE) { const text = node.textContent ?? ""; return CELL_SEPARATOR_TEXT_PATTERN.test(text); } if (!(node instanceof HTMLElement)) return false; if (CELL_SEPARATOR_TAGS.has(node.tagName)) return true; if (!(node instanceof HTMLAnchorElement)) return false; const onclick = node.getAttribute("onclick"); if (onclick === null) return false; const removeId = extractPostIdFromFavoritesDeleteOnclick(onclick); if (removeId === null) return false; return postId === null || removeId === postId; } /** * Remove a favorites cell from the DOM: the thumb and, when Remove / separators * sit between this thumb and the next `span.thumb`, those siblings too. * Never injects into `a#p{ID}`; never deletes paginator/other non-cell nodes. */ function removeFavoriteCell(thumb) { const postId = resolveFavoriteThumbPostId(thumb); const nodesToRemove = [thumb]; let sibling = thumb.nextSibling; while (sibling !== null) { if (sibling instanceof HTMLElement && sibling.matches(SITE_SELECTORS.thumb)) break; if (!isFavoriteCellResidue(sibling, postId)) break; nodesToRemove.push(sibling); sibling = sibling.nextSibling; } for (const node of nodesToRemove) node.remove(); } function collectFavoritePostIds(root) { const ids = []; const seen = /* @__PURE__ */ new Set(); const links = root.querySelectorAll(SITE_SELECTORS.favoritesDeleteLink); for (const link of links) { if (!(link instanceof HTMLAnchorElement)) continue; const onclick = link.getAttribute("onclick"); if (onclick === null) continue; const postId = extractPostIdFromFavoritesDeleteOnclick(onclick); if (postId === null || seen.has(postId)) continue; seen.add(postId); ids.push(postId); } return ids; } function bindRemoveClickCapture() { if (removeClickBound) return; removeClickBound = true; document.addEventListener("click", (event) => { const target = event.target; if (!(target instanceof Element)) return; const link = target.closest("a"); if (!(link instanceof HTMLAnchorElement)) return; const onclick = link.getAttribute("onclick"); if (onclick === null) return; const postId = extractPostIdFromFavoritesDeleteOnclick(onclick); if (postId === null) return; removeFav(postId); }, true); } function syncFavoritesPage(root = document, search = window.location.search) { if (detectPageKind(search) !== "favorites") return; const ids = collectFavoritePostIds(root); const numericIds = []; for (const postId of ids) { const parsed = Number(postId); if (Number.isFinite(parsed)) numericIds.push(Math.trunc(parsed)); } addFavs(numericIds); bindRemoveClickCapture(); } /** * Reads the index entries of one favorites page of the site. * * Favorites grid: `div.image-list > span > span.thumb > a#p{ID} > img`; the * image `title` is the tag list (the site cuts its first and last character), * `src` is the preview address. */ var THUMB_LINK_SELECTOR$1 = "span.thumb > a[id^=\"p\"]"; var LINK_ID_PATTERN = /^p(\d+)$/; var IMAGE_SELECTOR = ":scope > img"; /** * @param run when the sync run started, ms since epoch * @param firstPos place of the first post of this page in the site's list */ function readFavoriteIndexEntries(page, run, firstPos, base = window.location.href) { const entries = []; const seen = /* @__PURE__ */ new Set(); let pos = firstPos; for (const link of page.querySelectorAll(THUMB_LINK_SELECTOR$1)) { const match = LINK_ID_PATTERN.exec(link.id); const img = link.querySelector(IMAGE_SELECTOR); if (match?.[1] === void 0 || !(img instanceof HTMLImageElement)) continue; const id = Number(match[1]); if (seen.has(id)) continue; seen.add(id); let thumb = ""; try { thumb = new URL(img.getAttribute("src") ?? "", base).href; } catch { thumb = ""; } entries.push({ id, tags: img.title.trim(), thumb: isSiteUrl(thumb) ? thumb : "", run, pos, cut: true }); pos += 1; } return entries; } /** Minimum pause between sequential favorites page fetches. */ var FAVORITES_SYNC_PAGE_PAUSE_MS = exports("ck",1500); /** Pauses before each of the three retries (HTTP error / missing paginator). */ var FAVORITES_SYNC_RETRY_DELAYS_MS = [ 1e4, 3e4, 6e4 ]; var FAVORITES_SYNC_MODE_INCREMENTAL = exports("ch",FAVS_SYNC_MODE_INCREMENTAL); var FAVORITES_SYNC_MODE_FULL = exports("U",FAVS_SYNC_MODE_FULL); var MY_FAVORITES_LINK_SELECTOR$1 = "li#my-favorites-container a[href*=\"page=favorites\"]"; var THUMB_SELECTOR$1 = "span.thumb"; var THUMB_POST_LINK_SELECTOR = "span.thumb a[id^=\"p\"]"; var PAGINATOR_SELECTOR = "#paginator"; var LASTPAGE_SELECTOR = "a[name=\"lastpage\"]"; var NEXT_SELECTOR = "a[name=\"next\"]"; var REMOVE_LINK_SELECTOR = "a[onclick]"; var POST_LINK_ID_PATTERN = /^p(\d+)$/; var ONCLICK_PID_PATTERN = /[?&]pid=(\d+)/; var URL_PARSE_BASE = "https://rule34.xxx"; var TAB_ID_RANDOM_RADIX = 36; var TAB_ID_RANDOM_SLICE_START = 2; var FAVORITES_SYNC_ERROR_NOT_LOGGED_IN = "not logged in or menu not found"; var FAVORITES_SYNC_ERROR_UNEXPECTED_PAGE = "unexpected page"; function createAbortResult(total, page, pages) { return { status: "aborted", total, page, pages }; } function isAbortError$1(error) { return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError"; } function throwIfAborted(signal) { if (signal.aborted) throw new DOMException("Aborted", "AbortError"); } function delay$1(ms, signal) { return new Promise((resolve, reject) => { if (signal.aborted) { reject(new DOMException("Aborted", "AbortError")); return; } const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); if (signal.aborted) { reject(new DOMException("Aborted", "AbortError")); return; } resolve(); }, ms); const onAbort = () => { clearTimeout(timer); reject(new DOMException("Aborted", "AbortError")); }; signal.addEventListener("abort", onAbort, { once: true }); }); } function parsePositiveInt(raw) { if (raw === null) return null; const trimmed = raw.trim(); if (trimmed.length === 0) return null; const value = Number(trimmed); if (!Number.isFinite(value) || value < 0) return null; return Math.trunc(value); } function parsePidFromOnclick(onclick) { const raw = ONCLICK_PID_PATTERN.exec(onclick)?.[1]; if (raw === void 0) return null; return parsePositiveInt(raw); } function titleSnippetFromHtml(html) { try { return titleSnippetFromDocument(new DOMParser().parseFromString(html, "text/html")); } catch { return ""; } } function titleSnippetFromDocument(doc) { const raw = doc.title.trim(); if (raw.length <= 80) return raw; return raw.slice(0, 80); } function formatPauseMessage(status, titleSnippet) { if (titleSnippet.length === 0) return `HTTP ${String(status)}`; return `HTTP ${String(status)}: ${titleSnippet}`; } /** Stable tab id for sync lock (Package H / multi-tab). */ function createFavoritesSyncTabId() { const random = Math.random().toString(TAB_ID_RANDOM_RADIX).slice(TAB_ID_RANDOM_SLICE_START, 12); return `tab-${String(Date.now())}-${random}`; } function extractUserIdFromDocument(root) { const link = root.querySelector(MY_FAVORITES_LINK_SELECTOR$1); if (!(link instanceof HTMLAnchorElement)) return null; const href = link.getAttribute("href"); if (href === null || href.length === 0) return null; try { return parsePositiveInt(new URL(href, URL_PARSE_BASE).searchParams.get("id")); } catch { return null; } } /** * Reads `id` from a favorites view URL search string. * Returns null when the location is not a favorites page or id is missing. */ function extractUserIdFromFavoritesSearch(search) { if (detectPageKind(search) !== "favorites") return null; return parsePositiveInt(new URLSearchParams(search).get("id")); } /** * Resolve favorites owner id: menu link → favorites URL id → saved sync value. */ function resolveFavoritesUserId(root, search, savedUserId) { const fromMenu = extractUserIdFromDocument(root); if (fromMenu !== null) return fromMenu; const fromUrl = extractUserIdFromFavoritesSearch(search); if (fromUrl !== null) return fromUrl; if (savedUserId !== void 0 && Number.isFinite(savedUserId)) return Math.trunc(savedUserId); return null; } function buildFavoritesPageUrl(userId, pid) { const params = new URLSearchParams(); params.set(SEARCH_PARAM_PAGE, FAVORITES_PAGE); params.set("s", FAVORITES_SECTION_VIEW); params.set("id", String(userId)); params.set("pid", String(pid)); return `${SEARCH_PATH}?${params.toString()}`; } function pageIndexFromPid(pid) { return Math.floor(pid / 50) + 1; } function pagesFromLastPid(lastPid) { return Math.floor(lastPid / 50) + 1; } function collectFavoriteIdsFromDocument(doc) { const ids = /* @__PURE__ */ new Set(); const postLinks = doc.querySelectorAll(THUMB_POST_LINK_SELECTOR); for (const link of postLinks) { const raw = POST_LINK_ID_PATTERN.exec(link.id)?.[1]; if (raw === void 0) continue; const parsed = Number(raw); if (Number.isFinite(parsed)) ids.add(Math.trunc(parsed)); } const removeLinks = doc.querySelectorAll(REMOVE_LINK_SELECTOR); for (const link of removeLinks) { const onclick = link.getAttribute("onclick"); if (onclick === null) continue; const postId = extractPostIdFromFavoritesDeleteOnclick(onclick); if (postId === null) continue; const parsed = Number(postId); if (Number.isFinite(parsed)) ids.add(Math.trunc(parsed)); } return Array.from(ids); } /** * Reads last-page pid from a[name="lastpage"] onclick only. * No lastpage and no next → current page is last (returns currentPid). * No lastpage but next exists, or lastpage onclick unparseable → null (unexpected). */ function resolveLastPid(doc, currentPid) { const lastpage = doc.querySelector(LASTPAGE_SELECTOR); if (lastpage instanceof HTMLAnchorElement) { const onclick = lastpage.getAttribute("onclick"); if (onclick === null || onclick.length === 0) return null; return parsePidFromOnclick(onclick); } if (doc.querySelector(NEXT_SELECTOR) !== null) return null; return currentPid; } function hasPaginator(doc) { return doc.querySelector(PAGINATOR_SELECTOR) !== null; } /** * Reads sync mode from persisted FavsSyncState.mode. * Missing / unexpected → undefined. */ function readFavoritesSyncMode(sync) { const mode = sync?.mode; if (mode === FAVORITES_SYNC_MODE_INCREMENTAL || mode === FAVORITES_SYNC_MODE_FULL) return mode; } /** * True when the page has at least one id and every id is already local. * Empty pages are not early-stop (handled by trailing-empty completion). */ function pageIdsAllInLocalSet(pageIds, local) { if (pageIds.length === 0) return false; for (const id of pageIds) if (!local.has(id)) return false; return true; } function resolveRunMode(unfinished, existing, requested) { if (unfinished) return readFavoritesSyncMode(existing) ?? FAVORITES_SYNC_MODE_FULL; return requested ?? FAVORITES_SYNC_MODE_INCREMENTAL; } function persistSyncProgress(fields) { const state = { nextPid: fields.nextPid, lastPid: fields.lastPid, startedAt: fields.startedAt, running: fields.running, userId: fields.userId, mode: fields.mode, lock: { tabId: fields.tabId, beatAt: Date.now() } }; if (fields.finishedAt !== void 0) state.finishedAt = fields.finishedAt; setSyncState(state); return state; } async function fetchFavoritesPageOnce(url, signal) { let response; try { response = await fetch(url, { method: "GET", credentials: FETCH_CREDENTIALS, signal }); } catch (error) { if (isAbortError$1(error)) throw error; const message = error instanceof Error ? error.message : "request failed"; log.warn("favorites sync: fetch failed", url, error); return { ok: false, status: 0, titleSnippet: message.slice(0, 80), message }; } const html = await response.text(); const titleSnippet = titleSnippetFromHtml(html); if (!response.ok) { log.warn("favorites sync: HTTP error", response.status, url); return { ok: false, status: response.status, titleSnippet, message: formatPauseMessage(response.status, titleSnippet) }; } const doc = new DOMParser().parseFromString(html, "text/html"); if (!hasPaginator(doc)) { log.warn("favorites sync: missing paginator", url); return { ok: false, status: response.status, titleSnippet: titleSnippetFromDocument(doc), message: formatPauseMessage(response.status, titleSnippetFromDocument(doc)) }; } return { ok: true, doc, status: response.status, titleSnippet: titleSnippetFromDocument(doc) }; } /** * Fetch one favorites page; retry up to 3 times after 10s / 30s / 60s on * HTTP errors or missing paginator. */ async function fetchFavoritesPageWithRetries(url, signal) { let lastFailure = null; for (let attempt = 0; attempt <= FAVORITES_SYNC_RETRY_DELAYS_MS.length; attempt += 1) { throwIfAborted(signal); if (attempt > 0) { const delayMs = FAVORITES_SYNC_RETRY_DELAYS_MS[attempt - 1]; if (delayMs === void 0) break; log.warn("favorites sync: retrying after delay", { attempt, delayMs, url }); await delay$1(delayMs, signal); throwIfAborted(signal); } const result = await fetchFavoritesPageOnce(url, signal); if (result.ok) return result; lastFailure = result; } if (lastFailure === null) return { ok: false, status: 0, titleSnippet: "", message: formatPauseMessage(0, "") }; return lastFailure; } /** * Walks the site favorites list page-by-page and merges ids into local favs. * Only adds; never removes. Network I/O lives here only (explicit user click). */ async function runFavoritesSync(options) { const { onProgress, signal } = options; const tabId = options.tabId ?? createFavoritesSyncTabId(); const existing = getSyncState(); const userId = resolveFavoritesUserId(document, window.location.search, existing?.userId); if (userId === null) { log.warn("favorites sync: user id not found"); return { status: "error", message: FAVORITES_SYNC_ERROR_NOT_LOGGED_IN }; } const unfinished = existing !== void 0 && existing.finishedAt === void 0; const mode = resolveRunMode(unfinished, existing, options.mode); const startedAt = unfinished ? existing.startedAt : (/* @__PURE__ */ new Date()).toISOString(); const parsedStart = Date.parse(startedAt); const runStamp = Number.isNaN(parsedStart) ? Date.now() : parsedStart; let pid = unfinished ? existing.nextPid : 0; let lastPid = unfinished ? existing.lastPid : 0; let persistedNextPid = pid; let total = loadFavSet().size; let page = pageIndexFromPid(pid); let pages = pagesFromLastPid(lastPid); let sawNonEmptyPage = unfinished && existing.nextPid > 0; const writeProgress = (fields) => { const nextPid = fields.nextPid ?? persistedNextPid; persistedNextPid = nextPid; if (fields.lastPid !== void 0) lastPid = fields.lastPid; const payload = { nextPid, lastPid, startedAt, userId, tabId, running: fields.running, mode }; if (fields.finishedAt !== void 0) payload.finishedAt = fields.finishedAt; persistSyncProgress(payload); }; try { throwIfAborted(signal); writeProgress({ running: true }); while (true) { throwIfAborted(signal); const fetched = await fetchFavoritesPageWithRetries(buildFavoritesPageUrl(userId, pid), signal); if (!fetched.ok) { writeProgress({ running: true }); return { status: "error", message: fetched.message }; } const { doc } = fetched; const cardCount = doc.querySelectorAll(THUMB_SELECTOR$1).length; page = pageIndexFromPid(pid); if (cardCount === 0 && sawNonEmptyPage) { pages = Math.max(pages, page); const finishedAt = (/* @__PURE__ */ new Date()).toISOString(); writeProgress({ nextPid: pid + 50, running: false, finishedAt }); onProgress({ page, pages, total }); log.info("favorites sync: completed on empty trailing page", { total, pages, pid, mode }); return { status: "completed", total, pages }; } const resolvedLastPid = resolveLastPid(doc, pid); if (resolvedLastPid === null) { log.warn("favorites sync: unexpected page", { pid, cardCount }); writeProgress({ running: true }); return { status: "error", message: FAVORITES_SYNC_ERROR_UNEXPECTED_PAGE }; } lastPid = resolvedLastPid; pages = pagesFromLastPid(lastPid); if (cardCount === 0) { log.warn("favorites sync: unexpected empty page", { pid, lastPid }); writeProgress({ running: true }); return { status: "error", message: FAVORITES_SYNC_ERROR_UNEXPECTED_PAGE }; } sawNonEmptyPage = true; const ids = collectFavoriteIdsFromDocument(doc); putFavoriteIndexEntriesQuietly(readFavoriteIndexEntries(doc, runStamp, pid)); const allKnown = pageIdsAllInLocalSet(ids, loadFavSet()); addFavs(ids); total = loadFavSet().size; const nextPid = pid + 50; writeProgress({ nextPid, lastPid, running: true }); onProgress({ page, pages, total }); if (mode === FAVORITES_SYNC_MODE_INCREMENTAL && allKnown) { const finishedAt = (/* @__PURE__ */ new Date()).toISOString(); writeProgress({ nextPid, lastPid, running: false, finishedAt }); log.info("favorites sync: incremental early stop", { total, pages, page, pid }); return { status: "completed", total, pages }; } if (pid >= lastPid) { const finishedAt = (/* @__PURE__ */ new Date()).toISOString(); writeProgress({ nextPid, lastPid, running: false, finishedAt }); log.info("favorites sync: completed", { total, pages, mode }); return { status: "completed", total, pages }; } throwIfAborted(signal); await delay$1(FAVORITES_SYNC_PAGE_PAUSE_MS, signal); throwIfAborted(signal); pid = nextPid; page = pageIndexFromPid(pid); } } catch (error) { if (isAbortError$1(error)) { writeProgress({ running: false }); log.info("favorites sync: aborted", { pid, total, mode }); return createAbortResult(total, page, pages); } log.error("favorites sync: unexpected failure", error); writeProgress({ running: true }); return { status: "error", message: error instanceof Error ? error.message : "unexpected error" }; } } var FEATURE_ID$16 = "favorites-bulk"; var FEATURE_LABEL$16 = "Bulk remove favorites"; var FEATURE_PAGES$10 = ["favorites"]; var ROOT_ID$2 = "rdw-favorites-bulk"; var ROOT_CLASS$2 = "rdw-favorites-bulk"; /** The row under the title that stays at the top of the window. */ var PIN_ID = "rdw-favorites-pin"; var PIN_CLASS = "rdw-favorites-pin"; var FILTERS_CLASS = "rdw-favorites-filters"; var SUMMARY_CLASS = "rdw-favorites-bulk-summary"; var MENU_CLASS = "rdw-favorites-menu"; var MENU_ITEM_CLASS = "rdw-favorites-menu-item"; var DOWNLOAD_CLASS = "rdw-favorites-download"; var DOWNLOAD_TITLE_CLASS = "rdw-favorites-download-title"; var DOWNLOAD_NOTE_CLASS = "rdw-favorites-download-note"; var DOWNLOAD_STALE_CLASS = "rdw-favorites-download-stale"; var LINK_BUTTON_CLASS = "rdw-favorites-link"; var MENU_WIDTH_PX = 200; /** Above and below the controls of the pinned row. */ var PIN_PADDING_PX = 12; var BAR_CLASS$1 = "rdw-favorites-bulk-bar"; var STATUS_CLASS$1 = "rdw-favorites-bulk-status"; var CONFIRM_CLASS = "rdw-favorites-bulk-confirm"; var CONFIRM_ROW_CLASS = "rdw-favorites-bulk-confirm-row"; var PROGRESS_WRAP_CLASS = "rdw-favorites-bulk-progress"; var TITLE_CLASS$2 = "rdw-favorites-title"; var TITLE_TEXT = "Favorites"; var LOCALE = "en-US"; /** Above the thumbs and their corner buttons. */ var HEADER_Z_INDEX = 6; /** Selection chrome on site thumbs — skin may restyle (HANDOFF G). */ var CLASS_THUMB_SELECTED = "rdw-fav-bulk-selected"; var CLASS_THUMB_CHECK = "rdw-fav-bulk-check"; var TEXT_SELECT = "Select"; var TEXT_SELECT_PAGE = "Select page"; /** The results grid has no pages: what is selected is what has been loaded so far. */ var TEXT_SELECT_LOADED = "Select loaded"; var TEXT_ADD_TO_COLLECTION = "Add to collection"; var TEXT_RANDOM = "Random post"; var TEXT_RANDOM_TITLE = "Open a random favorite"; var TEXT_MORE_ACTIONS = "More actions"; var TEXT_DOWNLOAD_ALL = "Download all…"; var TEXT_SYNC = "Sync favorites…"; var TEXT_SYNC_FIRST = "Sync first"; var TEXT_DOWNLOAD_TITLE = "Download all favorites?"; var TEXT_DOWNLOAD_RESULTS = "Download results…"; var TEXT_DOWNLOAD_RESULTS_TITLE = "Download the results?"; var TEXT_DOWNLOAD_RESULTS_ARIA = "Download the results"; var TEXT_DOWNLOAD_BUTTON = "Download"; var TEXT_DOWNLOAD_ARIA = "Download all favorites"; var TEXT_SELECTED_MARK = "Selected"; var MS_PER_DAY$1 = 864e5; /** Name of the download job and of its folder. */ var DOWNLOAD_JOB_NAME = "Favorites"; var TEXT_CANCEL = UI_TEXT.cancel; var TEXT_STOP = "Stop"; var TEXT_DISMISS = "Dismiss"; /** The dots say a confirmation follows. */ var TEXT_REMOVE_SELECTED = "Remove from favorites…"; var TEXT_DOWNLOAD_SELECTED = "Download selected"; var DOWNLOAD_SELECTED_JOB_NAME = "Favorites (selected)"; /** Around the bar of a selection and the line under it. */ var SELECT_WRAP_CLASS = "rdw-favorites-bulk-select"; var TEXT_CONFIRM_PREFIX = "Remove "; var TEXT_CONFIRM_MID = " favorite"; var TEXT_CONFIRM_MID_PLURAL = " favorites"; var TEXT_CONFIRM_SUFFIX = "? This cannot be undone on the site."; var TEXT_CONFIRM_ARIA = "Confirm bulk remove favorites"; var TEXT_PROGRESS_OF = " of "; var TEXT_ERROR_DELETED_PREFIX = "Deleted "; var TEXT_ERROR_DELETED_MID = " of "; var TEXT_ERROR_FAILED_PREFIX = ". Failed on post "; var TEXT_ERROR_FAILED_SUFFIX = "."; var TEXT_STOPPED_PREFIX = "Stopped after "; var TEXT_STOPPED_MID = " of "; var TEXT_STOPPED_SUFFIX = "."; var CHECK_GLYPH = "✓"; var ACCENT_FALLBACK = "#4c8bf5"; var SURFACE_FALLBACK = "#ffffff"; var SELECT_OUTLINE_WIDTH = "2px"; var SELECT_OUTLINE_OFFSET = "2px"; var CHECK_SIZE = "1.25rem"; var CHECK_INSET = "0.25rem"; var CHECK_Z_INDEX = 2; var CHECK_FONT_SIZE = "0.75rem"; var BODY_CLASS$9 = featureBodyClass(FEATURE_ID$16); var BODY_SELECTING_CLASS = `${BODY_CLASS$9}-selecting`; var FEATURE_CSS$14 = ` /* While posts are being selected a thumbnail does not lift under the pointer: lifted, it stands out of the frame of a selected post. */ body.${BODY_SELECTING_CLASS} span.thumb:hover img { transform: none !important; } body.${BODY_CLASS$9} .${ROOT_CLASS$2}, body.${BODY_CLASS$9} .${PIN_CLASS} { display: flex; flex-wrap: wrap; align-items: center; box-sizing: border-box; width: 100%; max-width: 100%; margin: 0; flex: 0 0 100%; grid-column: 1 / -1; } /* Beside the column of filters both stand in the second column of the block. */ body.${BODY_CLASS$9} .${FAVORITES_LAYOUT_CLASS} > .${ROOT_CLASS$2}, body.${BODY_CLASS$9} .${FAVORITES_LAYOUT_CLASS} > .${PIN_CLASS} { grid-column: 2; width: auto; } /* The selection bar in the column, over the card of filters. */ body.${BODY_CLASS$9} .${FAVORITES_SIDE_BAR_CLASS} .${BAR_CLASS$1} { margin-bottom: 8px; padding: 10px; border: 1px solid var(--rdw-accent); border-radius: var(--rdw-radius-l); background: var(--rdw-accent-soft); color: var(--rdw-text); } body.${BODY_CLASS$9} .${FAVORITES_SIDE_BAR_CLASS} .${BAR_CLASS$1} > .rdw-btn { flex: 1 1 auto; white-space: nowrap; } /* Holds only the page's heading, which is for screen readers: the menu already shows where you are. */ body.${BODY_CLASS$9} .${ROOT_CLASS$2} { position: relative; height: 0; } /* The space under the header is the row's own padding, so that the row has the same space above it as below it, held or not. */ body.${BODY_CLASS$9} div#header { margin-bottom: 0 !important; } /* The row of search, filters and buttons (or of the selection) stays at the top. */ body.${BODY_CLASS$9} .${PIN_CLASS} { gap: 0.35rem 0.5rem; padding: ${String(PIN_PADDING_PX)}px 0; position: sticky; top: ${STICKY_TOP}; z-index: ${String(HEADER_Z_INDEX)}; background: var(--rdw-bg); } body.${BODY_CLASS$9} .${FILTERS_CLASS} { display: flex; flex-wrap: wrap; gap: 0.25rem; flex: 1 1 auto; min-width: 0; } body.${BODY_CLASS$9} .${FILTERS_CLASS}[hidden] { display: none; } body.${BODY_CLASS$9} .${TITLE_CLASS$2} { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0; } body.${BODY_CLASS$9} .${ROOT_CLASS$2} .rdw-btn, body.${BODY_CLASS$9} .${PIN_CLASS} .rdw-btn { font-weight: 500; } /* The strip turned into the selection: filled, so that it is seen without reading it that a click on a thumbnail now selects (the designer, 17.11.2026). */ body.${BODY_CLASS$9} .${PIN_CLASS} .${BAR_CLASS$1} { flex: 1 1 auto; padding: 4px 8px; border-radius: var(--rdw-radius-m); background: var(--rdw-accent-soft); color: var(--rdw-text); } body.${BODY_CLASS$9} .${SUMMARY_CLASS} { flex: 1 1 8rem; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font: 12px var(--rdw-font); color: var(--rdw-muted); } .${MENU_CLASS} { padding: 6px; gap: 2px; } .${MENU_ITEM_CLASS} { display: flex; align-items: center; gap: 8px; width: 100%; min-height: 30px; padding: 0 8px; border: 0; border-radius: var(--rdw-radius-s); background: transparent; color: var(--rdw-text); font: 13px var(--rdw-font); text-align: left; cursor: pointer; } .${MENU_ITEM_CLASS}:hover, .${MENU_ITEM_CLASS}:focus-visible { background: var(--rdw-surface-2); } .${DOWNLOAD_CLASS} { display: grid; gap: 0.5rem; } .${DOWNLOAD_TITLE_CLASS} { margin: 0; font: 700 15px var(--rdw-font); color: var(--rdw-text); } .${DOWNLOAD_NOTE_CLASS}, .${DOWNLOAD_STALE_CLASS} { margin: 0; font: 13px/1.4 var(--rdw-font); color: var(--rdw-muted); } .${DOWNLOAD_STALE_CLASS} { color: var(--rdw-text); } .${LINK_BUTTON_CLASS} { padding: 0; border: 0; background: none; color: var(--rdw-accent); font: inherit; text-decoration: underline; cursor: pointer; } .${DOWNLOAD_CLASS} .${CONFIRM_ROW_CLASS} { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 0.35rem 0.5rem; margin-top: 0.25rem; } body.${BODY_CLASS$9} .${SELECT_WRAP_CLASS} { display: grid; gap: 6px; flex: 1 1 auto; min-width: 0; } body.${BODY_CLASS$9} .${FAVORITES_SIDE_BAR_CLASS} .${SELECT_WRAP_CLASS} { margin-bottom: 8px; } body.${BODY_CLASS$9} .${BAR_CLASS$1} { display: flex; flex: 0 1 auto; flex-wrap: wrap; align-items: center; gap: 0.35rem 0.5rem; box-sizing: border-box; } body.${BODY_CLASS$9} .${STATUS_CLASS$1} { flex: 0 1 auto; min-width: 0; font: inherit; font-size: 0.875rem; line-height: 1.3; } body.${BODY_CLASS$9} .${CONFIRM_CLASS} { display: grid; gap: 0.75rem; } body.${BODY_CLASS$9} .${CONFIRM_ROW_CLASS} { display: flex; flex-wrap: wrap; gap: 0.35rem 0.5rem; } body.${BODY_CLASS$9} .${PROGRESS_WRAP_CLASS} { flex: 1 1 12rem; min-width: 8rem; max-width: 24rem; } body.${BODY_CLASS$9} span.thumb { position: relative; } body.${BODY_CLASS$9} span.thumb.${CLASS_THUMB_SELECTED} { outline: ${SELECT_OUTLINE_WIDTH} solid var(--rdw-accent, ${ACCENT_FALLBACK}); outline-offset: ${SELECT_OUTLINE_OFFSET}; } body.${BODY_CLASS$9} span.thumb > .${CLASS_THUMB_CHECK} { position: absolute; top: ${CHECK_INSET}; left: ${CHECK_INSET}; z-index: ${String(CHECK_Z_INDEX)}; display: none; align-items: center; justify-content: center; width: ${CHECK_SIZE}; height: ${CHECK_SIZE}; border-radius: 999px; background: var(--rdw-accent, ${ACCENT_FALLBACK}); color: var(--rdw-surface, ${SURFACE_FALLBACK}); font-size: ${CHECK_FONT_SIZE}; font-weight: 700; line-height: 1; pointer-events: none; } body.${BODY_CLASS$9} span.thumb.${CLASS_THUMB_SELECTED} > .${CLASS_THUMB_CHECK} { display: inline-flex; } `.trim(); function confirmMessage(count) { return `${TEXT_CONFIRM_PREFIX}${String(count)}${count === 1 ? TEXT_CONFIRM_MID : TEXT_CONFIRM_MID_PLURAL}${TEXT_CONFIRM_SUFFIX}`; } function progressLabel(done, total) { return `${String(done)}${TEXT_PROGRESS_OF}${String(total)}`; } function errorMessage(deleted, total, failedPostId) { return `${TEXT_ERROR_DELETED_PREFIX}${String(deleted)}${TEXT_ERROR_DELETED_MID}${String(total)}${TEXT_ERROR_FAILED_PREFIX}${failedPostId}${TEXT_ERROR_FAILED_SUFFIX}`; } function stoppedMessage(deleted, total) { return `${TEXT_STOPPED_PREFIX}${String(deleted)}${TEXT_STOPPED_MID}${String(total)}${TEXT_STOPPED_SUFFIX}`; } function isAbortError(error) { return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError"; } function delay(ms, signal) { return new Promise((resolve, reject) => { if (signal.aborted) { reject(new DOMException("Aborted", "AbortError")); return; } const timer = setTimeout(() => { signal.removeEventListener("abort", onAbort); if (signal.aborted) { reject(new DOMException("Aborted", "AbortError")); return; } resolve(); }, ms); const onAbort = () => { clearTimeout(timer); reject(new DOMException("Aborted", "AbortError")); }; signal.addEventListener("abort", onAbort, { once: true }); }); } function ensureCheckOverlay(thumb) { if (thumb.querySelector(`:scope > .rdw-fav-bulk-check`) !== null) return; const check = document.createElement("span"); check.className = CLASS_THUMB_CHECK; check.setAttribute("role", "img"); check.setAttribute("aria-label", TEXT_SELECTED_MARK); check.textContent = CHECK_GLYPH; const postLink = thumb.querySelector(`a[id^="p"]`); if (postLink instanceof HTMLAnchorElement && postLink.parentElement === thumb) { postLink.after(check); return; } thumb.prepend(check); } function clearThumbSelectionChrome(root = document) { const selected = root.querySelectorAll(`${SITE_SELECTORS.thumb}.${CLASS_THUMB_SELECTED}`); for (const node of selected) node.classList.remove(CLASS_THUMB_SELECTED); const checks = root.querySelectorAll(`${SITE_SELECTORS.thumb} > .${CLASS_THUMB_CHECK}`); for (const node of checks) node.remove(); } function applySelectionChrome(entries, selected) { for (const entry of entries) { const isSelected = selected.has(entry.postId); entry.thumb.classList.toggle(CLASS_THUMB_SELECTED, isSelected); if (isSelected) ensureCheckOverlay(entry.thumb); else { const check = entry.thumb.querySelector(`:scope > .${CLASS_THUMB_CHECK}`); if (check !== null) check.remove(); } } } /** * Place the bar as its own full-width row above the thumbs grid/list — * not as a sibling grid/flex item beside the first thumb. */ function findBarHost() { const imageList = document.querySelector(SITE_SELECTORS.imageList); if (imageList !== null && imageList.parentNode !== null) return { parent: imageList.parentNode, before: imageList }; const firstThumb = document.querySelector(SITE_SELECTORS.thumb); if (firstThumb !== null) { const grid = firstThumb.parentElement; if (grid !== null && grid.parentNode !== null) { if (grid !== document.body && grid !== document.documentElement) return { parent: grid.parentNode, before: grid }; return { parent: grid, before: firstThumb }; } } const paginator = document.querySelector("#paginator"); if (paginator !== null && paginator.parentNode !== null) return { parent: paginator.parentNode, before: paginator }; return { parent: document.body, before: document.body.firstChild }; } /** * Starts a download of favorites: of `only`, in that order, when the list is * narrowed, otherwise of every favorite in the local list, newest first. The * manager finds the files through the API by post id and shows its own panel. */ function downloadAllFavorites(only = null) { const ids = only === null ? [...loadFavSet()].sort((a, b) => b - a) : [...only]; if (ids.length === 0 || isDownloadBusy()) return; startDownload(DOWNLOAD_JOB_NAME, { kind: "ids", ids }); } function removeDomCellForPost(postId) { const entry = listFavoriteThumbEntries(favoritesGridRoot()).find((item) => item.postId === postId); if (entry !== void 0) { removeFavoriteCell(entry.thumb); return; } const fallback = document.getElementById(`s${postId}`); if (fallback instanceof HTMLElement) removeFavoriteCell(fallback); } /** How long ago the favorites were synced, and whether that is long enough to say so. */ function syncAge(finishedAt, now) { const parsed = finishedAt === void 0 ? NaN : Date.parse(finishedAt); if (!Number.isFinite(parsed)) return { text: "Never synced.", stale: true }; const days = Math.max(0, Math.floor((now - parsed) / MS_PER_DAY$1)); const stale = days > 7; if (days === 0) return { text: "Synced today.", stale }; return { text: `Synced ${String(days)} ${days === 1 ? "day" : "days"} ago.`, stale }; } function downloadNote(count) { const files = count === 1 ? "original file" : "original files"; return `${count.toLocaleString(LOCALE)} ${files}: every favorite in the local list, not only this page.`; } /** The same for a narrowed list: what narrows it is named, so that nothing else is expected. */ function downloadResultsNote(count, summary) { const files = count === 1 ? "original file" : "original files"; return `${count.toLocaleString(LOCALE)} ${files}: favorites matching ${summary}, from all pages.`; } /** Opens the settings page at its Favorites block, where the sync buttons are. */ function openSyncSettings() { requestSettingsSection(SETTINGS_SECTION_FAVORITES); window.location.hash = RDW_HASH_SETTINGS; } /** The buttons at the right end of the row: a random post, selecting, and the menu of rare actions. */ function IdleActions(props) { const [menuOpen, setMenuOpen] = d(false); const [downloadOpen, setDownloadOpen] = d(false); const menuButtonRef = T(null); const [shownIds, setShownIds] = d(null); const narrowed = props.summary.length > 0; const total = loadFavSet().size; const count = narrowed && shownIds !== null ? shownIds.length : total; const downloadLabel = narrowed ? TEXT_DOWNLOAD_RESULTS : TEXT_DOWNLOAD_ALL; const openDownload = () => { setShownIds(narrowed ? shownFavoriteIds() : null); setDownloadOpen(true); }; const age = syncAge(getSyncState()?.finishedAt, Date.now()); const synced = favoritesSynced(); const closeMenu = () => { setMenuOpen(false); }; const closeDownload = () => { setDownloadOpen(false); }; return /* @__PURE__ */ a($$1, { children: [ synced || !props.stacked ? /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", title: TEXT_RANDOM_TITLE, onClick: openRandomFavorite, children: [/* @__PURE__ */ a(IconDice, { size: 14 }), TEXT_RANDOM] }) : null, /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: props.onSelect, children: TEXT_SELECT }), props.stacked && !synced ? null : props.stacked ? /* @__PURE__ */ a($$1, { children: [downloadsAvailable() ? /* @__PURE__ */ a(Button, { variant: "ghost", size: "s", disabled: total === 0, onClick: openDownload, children: [/* @__PURE__ */ a(IconDownload, { size: 14 }), downloadLabel] }) : null, /* @__PURE__ */ a(Button, { variant: "ghost", size: "s", onClick: openSyncSettings, children: [/* @__PURE__ */ a(IconRefresh, { size: 14 }), TEXT_SYNC] })] }) : /* @__PURE__ */ a(IconButton, { label: TEXT_MORE_ACTIONS, menuOpen, buttonRef: menuButtonRef, onClick: () => { setMenuOpen(!menuOpen); }, children: /* @__PURE__ */ a(IconDots, { size: 16 }) }), /* @__PURE__ */ a(Popover, { open: menuOpen && !props.stacked, onClose: closeMenu, anchorRef: menuButtonRef, widthPx: MENU_WIDTH_PX, alignEnd: true, role: "menu", "aria-label": TEXT_MORE_ACTIONS, className: MENU_CLASS, children: [downloadsAvailable() ? /* @__PURE__ */ a("button", { type: "button", role: "menuitem", className: `${MENU_ITEM_CLASS} rdw-kit-focusable`, disabled: total === 0, onClick: () => { closeMenu(); openDownload(); }, children: [/* @__PURE__ */ a(IconDownload, { size: 16 }), downloadLabel] }) : null, /* @__PURE__ */ a("button", { type: "button", role: "menuitem", className: `${MENU_ITEM_CLASS} rdw-kit-focusable`, onClick: () => { closeMenu(); openSyncSettings(); }, children: [/* @__PURE__ */ a(IconRefresh, { size: 16 }), TEXT_SYNC] })] }), /* @__PURE__ */ a(Dialog, { open: downloadOpen, onClose: closeDownload, "aria-label": narrowed ? TEXT_DOWNLOAD_RESULTS_ARIA : TEXT_DOWNLOAD_ARIA, className: DOWNLOAD_CLASS, children: [ /* @__PURE__ */ a("h3", { className: DOWNLOAD_TITLE_CLASS, children: narrowed ? TEXT_DOWNLOAD_RESULTS_TITLE : TEXT_DOWNLOAD_TITLE }), /* @__PURE__ */ a("p", { className: DOWNLOAD_NOTE_CLASS, children: [narrowed ? downloadResultsNote(count, props.summary) : downloadNote(count), age.stale ? null : ` ${age.text}`] }), age.stale ? /* @__PURE__ */ a("p", { className: DOWNLOAD_STALE_CLASS, children: [ age.text, " ", /* @__PURE__ */ a("button", { type: "button", className: `${LINK_BUTTON_CLASS} rdw-kit-focusable`, onClick: () => { closeDownload(); openSyncSettings(); }, children: TEXT_SYNC_FIRST }) ] }) : null, /* @__PURE__ */ a("div", { className: CONFIRM_ROW_CLASS, children: [/* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: closeDownload, children: TEXT_CANCEL }), /* @__PURE__ */ a(Button, { variant: "primary", size: "s", disabled: count === 0, onClick: () => { closeDownload(); downloadAllFavorites(narrowed ? shownIds : null); }, children: `${TEXT_DOWNLOAD_BUTTON} ${count.toLocaleString(LOCALE)}` })] }) ] }) ] }); } /** The selected posts that are on the page, with their previews, in page order. */ function selectedPostsOnPage(selected) { const posts = []; for (const entry of listFavoriteThumbEntries(favoritesGridRoot())) { if (!selected.has(entry.postId)) continue; const id = Number(entry.postId); if (Number.isInteger(id) && id > 0) posts.push({ id, thumbUrl: readPreviewThumbUrl(entry.thumb, entry.postId) }); } return posts; } function FavoritesBulkBar(props) { const [phase, setPhase] = d({ kind: "idle" }); const [selected, setSelected] = d(() => /* @__PURE__ */ new Set()); const abortRef = T(null); const selectedRef = T(selected); selectedRef.current = selected; const [collectionPosts, setCollectionPosts] = d(null); const [note, setNote] = d(""); const selectionActive = phase.kind === "selecting" || phase.kind === "confirm" || phase.kind === "removing"; const { onSelectionModeChange, onBusyChange } = props; A(() => { onSelectionModeChange(selectionActive); }, [onSelectionModeChange, selectionActive]); const busy = phase.kind !== "idle"; A(() => { onBusyChange(busy); }, [onBusyChange, busy]); A(() => { if (!selectionActive) { clearThumbSelectionChrome(); return; } applySelectionChrome(listFavoriteThumbEntries(favoritesGridRoot()), selected); }, [selectionActive, selected]); A(() => { return () => { abortRef.current?.abort(); clearThumbSelectionChrome(); }; }, []); A(() => { if (phase.kind !== "selecting" && phase.kind !== "confirm") return; return bindPressSelect((target) => { if (target.closest(".rdw-dialog-backdrop") !== null) return null; const thumb = target.closest(SITE_SELECTORS.thumb); if (!(thumb instanceof HTMLElement) || !document.body.contains(thumb)) return null; const postId = resolveFavoriteThumbPostId(thumb); if (postId === null) return null; if (phase.kind === "confirm") return () => void 0; return () => { setNote(""); setSelected((prev) => { const next = new Set(prev); if (next.has(postId)) next.delete(postId); else next.add(postId); return next; }); }; }); }, [phase.kind]); const resetToIdle = () => { abortRef.current?.abort(); abortRef.current = null; clearThumbSelectionChrome(); setNote(""); setSelected(/* @__PURE__ */ new Set()); setPhase({ kind: "idle" }); }; useEscape(phase.kind === "selecting", resetToIdle); const enterSelecting = () => { setSelected(/* @__PURE__ */ new Set()); setPhase({ kind: "selecting" }); }; const selectPage = () => { const ids = listFavoriteThumbEntries(favoritesGridRoot()).map((entry) => entry.postId); setSelected(new Set(ids)); }; const clearSelection = () => { setSelected(/* @__PURE__ */ new Set()); }; const beginConfirm = () => { const count = selectedRef.current.size; if (count === 0) return; setPhase({ kind: "confirm", count }); }; const closeConfirm = () => { setPhase({ kind: "selecting" }); }; const runRemoval = async () => { const ids = [...selectedRef.current]; if (ids.length === 0) { setPhase({ kind: "selecting" }); return; } const controller = new AbortController(); abortRef.current = controller; const { signal } = controller; const total = ids.length; let done = 0; setPhase({ kind: "removing", done, total }); try { for (let index = 0; index < ids.length; index += 1) { if (signal.aborted) { setPhase({ kind: "stopped", message: stoppedMessage(done, total) }); return; } const postId = ids[index]; if (postId === void 0) continue; const result = await removeFavorite(postId, { signal }); if (signal.aborted) { setPhase({ kind: "stopped", message: stoppedMessage(done, total) }); return; } if (result.status !== "removed") { setPhase({ kind: "error", message: errorMessage(done, total, postId) }); return; } removeFav(postId); removeDomCellForPost(postId); done += 1; setSelected((prev) => { const next = new Set(prev); next.delete(postId); return next; }); setPhase({ kind: "removing", done, total }); if (index < ids.length - 1) await delay(FAVORITES_SYNC_PAGE_PAUSE_MS, signal); } clearThumbSelectionChrome(); setSelected(/* @__PURE__ */ new Set()); setPhase({ kind: "idle" }); } catch (error) { if (isAbortError(error) || signal.aborted) { setPhase({ kind: "stopped", message: stoppedMessage(done, total) }); return; } log.warn("favorites-bulk: unexpected removal failure", error); const failedId = ids[done] ?? "?"; setPhase({ kind: "error", message: errorMessage(done, total, failedId) }); } finally { if (abortRef.current === controller) abortRef.current = null; } }; const stopRemoval = () => { abortRef.current?.abort(); }; if (phase.kind === "idle") return props.headSlot === null ? null : U(/* @__PURE__ */ a(IdleActions, { onSelect: enterSelecting, stacked: props.headSlot.classList.contains(FAVORITES_SIDE_ACTIONS_CLASS), summary: props.summary }), props.headSlot); if (phase.kind === "removing") { const ratio = phase.total === 0 ? 0 : phase.done / phase.total; return /* @__PURE__ */ a("div", { className: BAR_CLASS$1, children: [ /* @__PURE__ */ a("div", { className: PROGRESS_WRAP_CLASS, children: /* @__PURE__ */ a(ProgressBar, { value: ratio, label: progressLabel(phase.done, phase.total) }) }), /* @__PURE__ */ a("span", { className: STATUS_CLASS$1, children: progressLabel(phase.done, phase.total) }), /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: stopRemoval, children: TEXT_STOP }) ] }); } if (phase.kind === "error" || phase.kind === "stopped") return /* @__PURE__ */ a("div", { className: BAR_CLASS$1, children: [/* @__PURE__ */ a("span", { className: STATUS_CLASS$1, children: phase.message }), /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: resetToIdle, children: TEXT_DISMISS })] }); const count = selected.size; const confirmOpen = phase.kind === "confirm"; const browsing = document.body.classList.contains(FAVORITES_BROWSING_BODY_CLASS); return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("div", { className: SELECT_WRAP_CLASS, children: [/* @__PURE__ */ a(SelectionBar, { layout: props.inColumn ? "stack" : "row", count, selectAllLabel: browsing ? TEXT_SELECT_LOADED : TEXT_SELECT_PAGE, onSelectAll: selectPage, onClear: clearSelection, onCancel: resetToIdle, danger: /* @__PURE__ */ a(Button, { variant: "danger-quiet", disabled: count === 0 || confirmOpen, onClick: beginConfirm, children: [/* @__PURE__ */ a(IconTrash, { size: 14 }), TEXT_REMOVE_SELECTED] }), children: [/* @__PURE__ */ a(Button, { variant: "secondary", disabled: count === 0 || confirmOpen, onClick: () => { setCollectionPosts(selectedPostsOnPage(selectedRef.current)); }, children: TEXT_ADD_TO_COLLECTION }), downloadsAvailable() ? /* @__PURE__ */ a(Button, { variant: "secondary", disabled: count === 0 || confirmOpen, onClick: () => { const ids = selectedPostsOnPage(selectedRef.current).map((post) => post.id); resetToIdle(); if (ids.length > 0 && !isDownloadBusy()) startDownload(DOWNLOAD_SELECTED_JOB_NAME, { kind: "ids", ids }, "selection"); }, children: TEXT_DOWNLOAD_SELECTED }) : null] }), note.length > 0 || props.summary.length > 0 ? /* @__PURE__ */ a("span", { className: SUMMARY_CLASS, role: note.length > 0 ? "status" : void 0, children: note.length > 0 ? note : props.summary }) : null] }), /* @__PURE__ */ a(BulkCollectionDialog, { open: collectionPosts !== null, posts: collectionPosts ?? [], onClose: () => { setCollectionPosts(null); }, onDone: (result) => { refreshAddButtons(); setNote(bulkCollectionSummary(result)); } }), /* @__PURE__ */ a(Dialog, { open: confirmOpen, onClose: closeConfirm, "aria-label": TEXT_CONFIRM_ARIA, className: CONFIRM_CLASS, children: [/* @__PURE__ */ a("p", { className: STATUS_CLASS$1, children: confirmMessage(count) }), /* @__PURE__ */ a("div", { className: CONFIRM_ROW_CLASS, children: [/* @__PURE__ */ a(Button, { variant: "danger", size: "s", onClick: () => { runRemoval(); }, children: `${TEXT_CONFIRM_PREFIX}${String(selected.size)}` }), /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: closeConfirm, children: TEXT_CANCEL })] })] }) ] }); } /** * The page's heading, kept for screen readers only, and, through a portal, the * pinned row: search, filters, the count and the buttons. The row is its own * element of the page: a sticky element cannot leave its parent, so it has to * be a child of the same block the grid is in. */ function FavoritesPanel(props) { const [headActions, setHeadActions] = d(null); const [busy, setBusy] = d(false); const [summary, setSummary] = d(""); return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("h1", { className: TITLE_CLASS$2, children: TITLE_TEXT }), U(/* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("div", { className: FILTERS_CLASS, hidden: busy && props.side === null, children: /* @__PURE__ */ a(FavoritesBrowser, { actionsRef: setHeadActions, onSummary: setSummary, sideHost: props.side, locked: busy }) }), /* @__PURE__ */ a(FavoritesBulkBar, { onSelectionModeChange: props.onSelectionModeChange, headSlot: headActions, summary, onBusyChange: setBusy, inColumn: props.side !== null })] }), props.pin)] }); } function mountFavoritesBulk(_ctx) { if (document.getElementById(ROOT_ID$2) !== null) return; const host = findBarHost(); const root = document.createElement("div"); root.id = ROOT_ID$2; root.className = ROOT_CLASS$2; const pin = document.createElement("div"); pin.id = PIN_ID; pin.className = PIN_CLASS; host.parent.insertBefore(root, host.before); host.parent.insertBefore(pin, host.before); const siteGrid = document.querySelector(SITE_SELECTORS.imageList); if (siteGrid !== null) bindInPlaceRemoval(siteGrid); const onSelectionModeChange = (active) => { document.body.classList.toggle(BODY_SELECTING_CLASS, active); }; let side = null; if (host.parent instanceof HTMLElement && host.parent !== document.body) { const slot = document.createElement("div"); slot.className = FAVORITES_SIDE_SLOT_CLASS; const column = document.createElement("div"); column.id = FAVORITES_SIDE_ID; column.className = FAVORITES_SIDE_CLASS; const barHost = document.createElement("div"); barHost.className = FAVORITES_SIDE_BAR_CLASS; side = document.createElement("div"); side.className = FAVORITES_SIDE_CARD_CLASS; column.append(barHost, side); slot.append(column); host.parent.insertBefore(slot, root); host.parent.classList.add(FAVORITES_LAYOUT_CLASS); pin.remove(); Q$1(/* @__PURE__ */ a(FavoritesPanel, { pin: barHost, side, onSelectionModeChange }), root); return; } Q$1(/* @__PURE__ */ a(FavoritesPanel, { pin, side, onSelectionModeChange }), root); } var favoritesBulkFeature = { id: FEATURE_ID$16, label: FEATURE_LABEL$16, pages: [...FEATURE_PAGES$10], defaultEnabled: true, css: FEATURE_CSS$14, mount: mountFavoritesBulk }; /** * Document-level CSS for grid fav buttons, artist Follow, updates bar. * Owned with cards / preview chrome (not panel Shadow DOM). */ var CARD_CSS = ` .${CSS_CLASS.cardFav} { position: absolute; top: 4px; right: 4px; z-index: 5; box-sizing: border-box; min-width: 28px; min-height: 28px; width: 28px; height: 28px; padding: 0; border: 1px solid #333; border-radius: 4px; background: rgba(255, 255, 255, 0.92); color: #333; cursor: pointer; font-size: 14px; line-height: 1; opacity: 0; } @supports (anchor-name: --a) { .${CSS_CLASS.cardFav} { position-anchor: --rdw-img; top: calc(anchor(top) + 4px); right: calc(anchor(right) + 4px); } } .${CSS_CLASS.thumb}:hover .${CSS_CLASS.cardFav}, .${CSS_CLASS.cardFav}:focus-visible { opacity: 0.65; } .${CSS_CLASS.thumb} .${CSS_CLASS.cardFav}:hover, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavMarked}, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavError}, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavPending} { opacity: 1; } .${CSS_CLASS.cardFav}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavMarked} { background: #ffe08a; border-color: #a67c00; color: #5c4500; } .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavError} { background: #f8d7da; border-color: #a12828; color: #a12828; } .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavPending}, .${CSS_CLASS.cardFav}:disabled { cursor: wait; } .${CSS_CLASS.thumb}:has(> a[style*="display: none"]) .${CSS_CLASS.cardFav}, .${CSS_CLASS.thumb}:has(> a[style*="display:none"]) .${CSS_CLASS.cardFav} { display: none !important; } body.${CSS_CLASS.gridFavsHidden} .${CSS_CLASS.cardFav} { display: none !important; } .${CSS_CLASS.artistFollow} { margin-left: 4px; box-sizing: border-box; min-height: 18px; padding: 0 5px; border: 1px solid #666; border-radius: 3px; background: #fff; color: #333; cursor: pointer; font-size: 11px; line-height: 1.2; vertical-align: middle; } .${CSS_CLASS.artistFollow}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } .${CSS_CLASS.artistFollow}.${CSS_CLASS.artistFollowMarked} { background: #ffe08a; border-color: #a67c00; color: #5c4500; } .${CSS_CLASS.updatesBar} { margin: 8px 0; padding: 8px 10px; border: 1px solid var(--rdw-border); border-radius: 6px; background: var(--rdw-surface); font-family: Segoe UI, system-ui, sans-serif; font-size: 14px; color: var(--rdw-text); } .${CSS_CLASS.updatesBar} .${CSS_CLASS.hint} { margin: 0; color: var(--rdw-muted); font-size: 12px; } .${CSS_CLASS.updatesBar} .${CSS_CLASS.primaryButton} { border: 1px solid var(--rdw-accent); background: var(--rdw-accent); color: var(--rdw-surface); border-radius: 4px; cursor: pointer; min-height: 32px; padding: 4px 10px; font: inherit; } .${CSS_CLASS.updatesBar} .${CSS_CLASS.primaryButton}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } .${CSS_CLASS.updatesBar} .${CSS_CLASS.itemName} { color: var(--rdw-accent); font-weight: 600; text-decoration: underline; } .${CSS_CLASS.updatesBarActions} { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } `; var unsubscribeThumbsAdded$3; /** * Document overlays for preview badges + feed bar (mock layout 1). * Appended after CARD_CSS so hover-only visibility wins over marked-always-visible. */ var DOCUMENT_OVERLAY_CSS = ` ${ICON_BUTTON_CSS} .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavMarked}, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavError}, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavPending} { opacity: 0; } .${CSS_CLASS.thumb}:hover .${CSS_CLASS.cardFav}, .${CSS_CLASS.cardFav}:focus-visible { opacity: 0.65; } .${CSS_CLASS.thumb} .${CSS_CLASS.cardFav}:hover, .${CSS_CLASS.thumb}:hover .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavMarked}, .${CSS_CLASS.thumb}:hover .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavError}, .${CSS_CLASS.thumb}:hover .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavPending}, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavMarked}:focus-visible, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavError}:focus-visible, .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavPending}:focus-visible { opacity: 1; } .${CSS_CLASS.cardFav}.rdw-icon-btn { border-radius: 8px; background: rgba(255, 255, 255, 0.93); border: 1px solid rgba(0, 0, 0, 0.13); box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2); color: #1c2228; font-size: 13px; } .${CSS_CLASS.cardFav}.${CSS_CLASS.cardFavMarked}.rdw-icon-btn { background: #ffd75e; border-color: #c79a00; color: #5c4500; } /* As wide as what it holds, not the whole row. */ .${CSS_CLASS.updatesBar} { display: flex; align-items: center; gap: 10px; box-sizing: border-box; width: fit-content; max-width: 100%; white-space: nowrap; } .${CSS_CLASS.updatesBarActions} { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } .${CSS_CLASS.updatesBar} .${CSS_CLASS.hint} { margin: 0; font-weight: 700; font-size: 12px; color: var(--rdw-text); } .${CSS_CLASS.updatesBar} .${CSS_CLASS.primaryButton} { margin-left: auto; background: var(--rdw-accent); border: 1px solid var(--rdw-accent); border-radius: 8px; height: 28px; min-height: 28px; padding: 0 12px; font-weight: 600; font-size: 12px; } .${CSS_CLASS.updatesBar} .${CSS_CLASS.secondaryButton} { box-sizing: border-box; display: inline-grid; place-items: center; border: 1px solid var(--rdw-border); background: var(--rdw-surface); color: var(--rdw-text); border-radius: 8px; height: 28px; min-height: 28px; padding: 0 10px; font-size: 12px; font-weight: 400; text-decoration: none; cursor: pointer; white-space: nowrap; } .${CSS_CLASS.updatesBar} .${CSS_CLASS.secondaryButton}:focus-visible, .${CSS_CLASS.updatesBar} .${CSS_CLASS.primaryButton}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } `; function ensureThumbsAddedSubscription() { if (unsubscribeThumbsAdded$3 !== void 0) return; unsubscribeThumbsAdded$3 = onThumbsAdded((root) => { mountCards(root); }); } function ensureDocumentStyles() { if (document.getElementById("ruledesk-web-document-style") !== null) return; const style = document.createElement("style"); style.id = DOCUMENT_STYLE_ID; style.textContent = `${BASE_GRID_CSS}\n${CARD_CSS}\n${DOCUMENT_OVERLAY_CSS}`; document.head.append(style); } function findThumbLink$1(thumb, postId) { const byId = thumb.querySelector(`#p${postId}`); if (byId instanceof HTMLAnchorElement) return byId; const byHref = thumb.querySelector(SITE_SELECTORS.thumbLink); return byHref instanceof HTMLAnchorElement ? byHref : null; } function attachFavButton(thumb, postId, marked) { if (thumb.querySelector(SITE_SELECTORS.cardFavButton) !== null) return; const link = findThumbLink$1(thumb, postId); if (link === null) return; ensureThumbAnchor(thumb); const button = createFavButton(postId, marked); button.classList.add(KIT_ICON_BUTTON_CLASS); link.after(button); } function applyGridFavVisibilityClass(visible) { document.body.classList.toggle(CSS_CLASS.gridFavsHidden, !visible); } function setGridFavButtonsVisible(visible) { applyGridFavVisibilityClass(visible); if (visible && detectPageKind(window.location.search) === "list") mountCards(); } function mountCards(root = document, search = window.location.search) { ensureThumbsAddedSubscription(); if (detectPageKind(search) !== "list") return; ensureDocumentStyles(); const enabled = getGridFavButtonsEnabled(); applyGridFavVisibilityClass(enabled); if (!enabled) return; const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) { if (!(thumb instanceof HTMLElement)) continue; const postId = extractPostIdFromThumb(thumb); if (postId === null) continue; attachFavButton(thumb, postId, isFav(postId)); } } /** Keep in sync with `FEED_NEW_CLASS` in features/feed.ts. */ var FEED_NEW_CLASS$1 = "new"; var ID_FILTER_PATTERN = /^id:>(\d+)$/; var TEXT_NEW_SUFFIX = " new"; var TEXT_MARKED_SEEN_PREFIX = "Marked as seen up to #"; var TEXT_ONLY_NEW = "Only new"; var TEXT_SHOW_ALL = "Show all"; /** * Followed artists for feed-bar recognition. * Mirror first — GM_getValue on bfcache pages can be a frozen snapshot. */ function resolveFollowedArtistTags$2() { const mirrored = readArtistsMirror(); if (mirrored !== null && mirrored.length > 0) return [...mirrored]; return listArtistTags(); } /** * store load syncs the mirror from GM; restore a non-empty pre-read mirror so a * bfcache-stale GM snapshot cannot wipe tags followed on another page. */ function reloadStoragePreservingArtistsMirror$1() { const mirrored = readArtistsMirror(); loadRecent(); if (mirrored !== null && mirrored.length > 0) writeArtistsMirror(mirrored); } function readPid(search) { const raw = new URLSearchParams(search).get("pid"); if (raw === null || raw.trim().length === 0) return 0; const value = Number(raw); if (!Number.isFinite(value) || value < 0) return 0; return Math.floor(value); } function maxThumbPostId(root) { let maxId = 0; const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) { const postId = extractPostIdFromThumb(thumb); if (postId === null) continue; const numeric = Number(postId); if (Number.isFinite(numeric) && numeric > maxId) maxId = numeric; } return maxId; } function countNewThumbs$1(root, seenPostId) { let count = 0; const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) { const postId = extractPostIdFromThumb(thumb); if (postId === null) continue; const numeric = Number(postId); if (Number.isFinite(numeric) && numeric > seenPostId) count += 1; } return count; } function tagsHaveIdFilter(tagsParam) { const tokens = tagsParam.trim().split(/\s+/).filter((token) => token.length > 0); const last = tokens[tokens.length - 1]; return last !== void 0 && ID_FILTER_PATTERN.test(last); } function removeExistingBar$1(root) { const existing = root instanceof Document ? root.getElementById(UPDATES_BAR_ID) : root.querySelector(`#${UPDATES_BAR_ID}`); if (existing !== null) existing.remove(); } function createBarShell() { const bar = document.createElement("div"); bar.id = UPDATES_BAR_ID; bar.className = CSS_CLASS.updatesBar; return bar; } function insertBeforeImageList(imageList, bar) { imageList.parentElement?.insertBefore(bar, imageList); } function findEmptyUpdatesHost(root) { return root.querySelector(SITE_SELECTORS.postListContent) ?? root.querySelector(SITE_SELECTORS.contentRoot); } function clearNewHighlights(root) { const thumbs = root.querySelectorAll(`${SITE_SELECTORS.thumb}.${FEED_NEW_CLASS$1}`); for (const thumb of thumbs) thumb.classList.remove(FEED_NEW_CLASS$1); } function createToggleLink(tagsParam, seenPostId) { if (tagsHaveIdFilter(tagsParam)) { const link = document.createElement("a"); link.className = CSS_CLASS.secondaryButton; link.href = buildUpdatesSearchUrl(stripUpdatesIdFilter(tagsParam)); link.textContent = TEXT_SHOW_ALL; return link; } if (seenPostId === 0) return null; const onlyNewQuery = `${stripUpdatesIdFilter(tagsParam)} ${UPDATES_ID_PREFIX}${String(seenPostId)}`; const link = document.createElement("a"); link.className = CSS_CLASS.secondaryButton; link.href = buildUpdatesSearchUrl(onlyNewQuery); link.textContent = TEXT_ONLY_NEW; return link; } function appendToggle(parent, tagsParam, seenPostId) { const toggle = createToggleLink(tagsParam, seenPostId); if (toggle !== null) parent.append(toggle); } function mountEmptyPageBar(root, tagsParam) { const host = findEmptyUpdatesHost(root); if (host === null) { log.warn(UI_TEXT.updatesBarMissingHost); return; } const bar = createBarShell(); const seen = getSeenPostId(); const text = document.createElement("p"); text.className = CSS_CLASS.hint; text.textContent = `${UI_TEXT.noNewPostsSince}${String(seen)}`; const showAll = document.createElement("a"); showAll.className = CSS_CLASS.secondaryButton; showAll.href = buildUpdatesSearchUrl(stripUpdatesIdFilter(tagsParam)); showAll.textContent = TEXT_SHOW_ALL; const wrap = document.createElement("div"); wrap.className = CSS_CLASS.updatesBarActions; wrap.append(text, showAll); bar.append(wrap); host.insertBefore(bar, host.firstChild); } function mountPartialBar(imageList) { const bar = createBarShell(); const hint = document.createElement("p"); hint.className = CSS_CLASS.hint; hint.textContent = UI_TEXT.updatesPartialHint; bar.append(hint); insertBeforeImageList(imageList, bar); } function mountFullBar(imageList, search, tagsParam, merged) { const bar = createBarShell(); const seen = getSeenPostId(); if (readPid(search) > 0) { const hint = document.createElement("p"); hint.className = CSS_CLASS.hint; hint.textContent = UI_TEXT.goToPageOneToMark; bar.append(hint); insertBeforeImageList(imageList, bar); return; } const newCount = countNewThumbs$1(imageList, seen); const actions = document.createElement("div"); actions.className = CSS_CLASS.updatesBarActions; if (newCount === 0) { const hint = document.createElement("p"); hint.className = CSS_CLASS.hint; hint.textContent = `${UI_TEXT.noNewPostsSince}${String(seen)}`; actions.append(hint); if (!merged) appendToggle(actions, tagsParam, seen); bar.append(actions); insertBeforeImageList(imageList, bar); return; } const summary = document.createElement("p"); summary.className = CSS_CLASS.hint; summary.textContent = `${String(newCount)}${TEXT_NEW_SUFFIX}`; const markButton = document.createElement("button"); markButton.type = "button"; markButton.className = CSS_CLASS.primaryButton; markButton.textContent = UI_TEXT.markAllSeen; markButton.addEventListener("click", () => { const nextSeen = Math.max(getSeenPostId(), maxThumbPostId(imageList)); setSeenPostId(nextSeen); clearNewHighlights(document); if (!merged && tagsHaveIdFilter(tagsParam)) { const base = stripUpdatesIdFilter(tagsParam); window.location.assign(buildUpdatesSearchUrl(`${base} ${UPDATES_ID_PREFIX}${String(nextSeen)}`)); return; } bar.replaceChildren(); const confirm = document.createElement("p"); confirm.className = CSS_CLASS.hint; confirm.textContent = `${TEXT_MARKED_SEEN_PREFIX}${String(nextSeen)}`; const wrap = document.createElement("div"); wrap.className = CSS_CLASS.updatesBarActions; wrap.append(confirm); if (!merged) appendToggle(wrap, tagsParam, nextSeen); bar.append(wrap); }); actions.append(summary, markButton); if (!merged) appendToggle(actions, tagsParam, seen); bar.append(actions); insertBeforeImageList(imageList, bar); } function mountUpdatesBar(root = document, search = window.location.search, options = {}) { if (detectPageKind(search) !== "list") return; const tagsParam = new URLSearchParams(search).get(SEARCH_PARAM_TAGS); if (tagsParam === null || tagsParam.trim().length === 0) return; const artistTags = resolveFollowedArtistTags$2(); reloadStoragePreservingArtistsMirror$1(); const merged = options.merged === true; const isFull = merged || isFullUpdatesQuery(tagsParam, artistTags); const isPartial = !merged && isPartialUpdatesQuery(tagsParam, artistTags); if (!isFull && !isPartial) { removeExistingBar$1(root); return; } removeExistingBar$1(root); ensureDocumentStyles(); const imageList = root.querySelector(SITE_SELECTORS.imageList); if (imageList === null) { mountEmptyPageBar(root, tagsParam); return; } if (isPartial) { mountPartialBar(imageList); return; } mountFullBar(imageList, search, tagsParam, merged); } /** What a results page of one artist tag tells about the artist. */ function readArtistSnapshot(root, tag) { return { cover: readFirstThumbUrls(root, 4), postCount: readResultCount(root, tag), lastPostId: readNewestPostId(root) }; } /** * Reads the first results page of one artist tag. One request. * Only the "Refresh" run of the Following page calls it, started by the user, * one artist at a time with a pause. Throws on a network error or a non-OK * status (the site answers 429 when asked too often). */ async function fetchArtistSnapshot(tag) { const url = buildSearchUrl([{ tag, type: TAG_TYPE_INCLUDE }]); const response = await fetch(url, { method: "GET", credentials: FETCH_CREDENTIALS }); if (!response.ok) throw new Error(`HTTP ${String(response.status)}`); const html = await response.text(); return readArtistSnapshot(new DOMParser().parseFromString(html, "text/html"), tag); } /** * Keeps what the Following page shows about each followed artist (cover, post * count, newest post) up to date from pages the user opens anyway. * Nothing here makes a request. */ var FIRST_PAGE_PID$2 = "0"; var unsubscribe; /** * Newest post per followed artist among the thumbs under `root`. * A thumb's tags come from its preview title, so any results page counts: * the feed, a search, pages appended while scrolling. */ function rememberFromThumbs(root, followed) { const newest = /* @__PURE__ */ new Map(); for (const thumb of root.querySelectorAll(SITE_SELECTORS.thumb)) { const raw = extractPostIdFromThumb(thumb); const id = raw === null ? NaN : Number(raw); if (!Number.isFinite(id)) continue; for (const tag of readThumbTags(thumb)) if (followed.has(tag) && id > (newest.get(tag) ?? 0)) newest.set(tag, id); } if (newest.size > 0) rememberArtistLastPosts(newest); } function isFirstPage(search) { const pid = new URLSearchParams(search).get("pid"); return pid === null || pid.length === 0 || pid === FIRST_PAGE_PID$2; } /** Call once per results page. Does nothing while no artist is followed. */ function rememberArtistsFromPage(search) { const followed = new Set(listArtistTags()); if (followed.size === 0) return; const tagsParam = new URLSearchParams(search).get("tags") ?? ""; const single = readSingleTag(tagsParam); if (single !== null && followed.has(single) && isFirstPage(search) && !queryHasSortRandom(tagsParam)) rememberArtistSnapshot(single, readArtistSnapshot(document, single)); rememberFromThumbs(document, followed); if (unsubscribe === void 0) unsubscribe = onThumbsAdded((root) => { rememberFromThumbs(root, new Set(listArtistTags())); }); } var IMAGE_LIST_SELECTOR = SITE_SELECTORS.imageList; var THUMB_SELECTOR = SITE_SELECTORS.thumb; var PAGINATION_SELECTOR = "div.pagination"; var NEXT_LINK_SELECTOR$1 = "a[alt=\"next\"]"; function resolveSameOriginUrl(url) { const absolute = new URL(url, window.location.href); if (absolute.origin !== window.location.origin) throw new Error(`Cross-origin next page URL rejected: ${absolute.origin}`); return absolute.href; } function readNextUrl(doc) { const pagination = doc.querySelector(PAGINATION_SELECTOR); if (pagination === null) return null; const nextLink = pagination.querySelector(NEXT_LINK_SELECTOR$1); if (!(nextLink instanceof HTMLAnchorElement)) return null; const href = nextLink.getAttribute("href"); if (href === null || href.length === 0 || href === "#") return null; try { return resolveSameOriginUrl(href); } catch { return null; } } function collectThumbs(doc) { const imageList = doc.querySelector(IMAGE_LIST_SELECTOR); if (imageList === null) return []; return Array.from(imageList.querySelectorAll(THUMB_SELECTOR)); } /** * Fetches a list page HTML document and extracts thumbs + the next-page URL. * Throws on network failure or non-OK HTTP status. */ async function fetchNextPage(url) { const requestUrl = resolveSameOriginUrl(url); const response = await fetch(requestUrl, { method: "GET", credentials: FETCH_CREDENTIALS }); if (!response.ok) throw new Error(`HTTP ${String(response.status)}`); const html = await response.text(); const doc = new DOMParser().parseFromString(html, "text/html"); return { thumbs: collectThumbs(doc), nextUrl: readNextUrl(doc) }; } /** * Feed for more followed artists than one site search can hold. * * The site search takes a limited OR-group, so the followed artists are split * into groups and every group is its own search, newest post first. The feed * page is the first group's search. This module reads the other groups' result * pages (one request at a time, with a pause) and shows all groups as one list * ordered by post id, newest first. */ /** Set on body while the merged feed owns the grid; infinite scroll stays off. */ var FEED_MERGE_BODY_CLASS = "rdw-feed-merged"; var PENDING_CLASS = "rdw-feed-merge-pending"; var BLACKLISTED_CLASS = "rdw-blacklisted"; var STATUS_CLASS = "rdw-feed-merge-status"; var SENTINEL_CLASS = "rdw-feed-merge-sentinel"; var RETRY_CLASS = "rdw-feed-merge-retry"; var MIN_REQUEST_INTERVAL_MS$1 = 1e3; var PREFETCH_VIEWPORT_HEIGHTS = 2; var FIRST_PAGE_PID$1 = "0"; var NEXT_LINK_SELECTOR = "div.pagination a[alt=\"next\"]"; var EMPTY_HREF = "#"; var SCORE_TOKEN_PREFIX$2 = "score:"; var RATING_TOKEN_PREFIX$1 = "rating:"; var TOKEN_SPLIT$1 = /\s+/; var TEXT_LOADING_PREFIX = "Loading feed: part "; var TEXT_LOADING_JOIN = " of "; var TEXT_END$1 = "End of feed"; var TEXT_ERROR$1 = "Failed to load a part of the feed"; var TEXT_RETRY$1 = "Retry"; var FEED_MERGE_CSS = ` body.${FEED_MERGE_BODY_CLASS} ${SITE_SELECTORS.pagination} { display: none; } body.${FEED_MERGE_BODY_CLASS} ${SITE_SELECTORS.thumb}.${PENDING_CLASS}, body.${FEED_MERGE_BODY_CLASS} ${SITE_SELECTORS.thumb}.${BLACKLISTED_CLASS} { display: none !important; } .${SENTINEL_CLASS} { display: block; width: 100%; height: 1px; } .${STATUS_CLASS} { display: block; width: 100%; margin: 12px 0; text-align: center; font-size: 13px; color: var(--rdw-muted); } .${RETRY_CLASS} { margin-left: 8px; padding: 2px 8px; font: inherit; color: var(--rdw-text); background: var(--rdw-surface); border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); cursor: pointer; } `; /** * Takes from the groups every item whose place in the common order is already * certain. An item is certain while each group that still has pages also has a * buffered item: only then no unread page can hold something newer. * `seen` collects the ids already emitted, so a post of two followed artists * from different groups shows once. Mutates the buffers and `seen`. */ function drainMerged(sources, idOf, seen) { const emitted = []; for (;;) { let best = -1; let bestId = -1; for (let index = 0; index < sources.length; index += 1) { const source = sources[index]; if (source === void 0) continue; const head = source.buffer[0]; if (head === void 0) { if (source.nextUrl !== null) return { emitted, starving: index }; continue; } const id = idOf(head); if (id > bestId) { bestId = id; best = index; } } const item = sources[best]?.buffer.shift(); if (item === void 0) return { emitted, starving: null }; if (!seen.has(bestId)) { seen.add(bestId); emitted.push(item); } } } function thumbPostId(thumb) { const raw = extractPostIdFromThumb(thumb); const id = raw === null ? NaN : Number(raw); return Number.isFinite(id) ? id : 0; } function byNewest(a, b) { return thumbPostId(b) - thumbPostId(a); } function sleep$1(ms) { return new Promise((resolve) => { window.setTimeout(resolve, ms); }); } function readPagerNextUrl() { const href = document.querySelector(NEXT_LINK_SELECTOR)?.getAttribute("href") ?? ""; if (href.length === 0 || href === EMPTY_HREF) return null; try { return new URL(href, window.location.href).href; } catch { return null; } } /** Fetched thumbs get the same blacklist treatment as infinite scroll gives. */ function applyBlacklist$1(thumb, list) { const image = thumb.querySelector(SITE_SELECTORS.previewImage); const text = image?.getAttribute("title")?.trim() ?? image?.getAttribute("alt")?.trim() ?? ""; const tags = []; let score = 0; let rating = ""; for (const token of text.split(TOKEN_SPLIT$1)) { const lower = token.toLowerCase(); if (lower.startsWith(SCORE_TOKEN_PREFIX$2)) { const parsed = Number(token.slice(6)); score = Number.isFinite(parsed) ? parsed : score; } else if (lower.startsWith(RATING_TOKEN_PREFIX$1)) rating = token.slice(7); else if (token.length > 0) tags.push(token); } if (isBlacklisted(tags, score, rating, list)) thumb.classList.add(BLACKLISTED_CLASS); } /** * True when this results page is the feed that must be merged: the first * group's search, first page, with more than one group of followed artists. */ function isMergedFeedPage(search, artistTags, groupSize) { const params = new URLSearchParams(search); const pid = params.get("pid"); if (pid !== null && pid.length > 0 && pid !== FIRST_PAGE_PID$1) return false; const tagsParam = params.get("tags") ?? ""; return findFeedGroupIndex(tagsParam, artistTags, groupSize) === 0; } /** * Starts the merged feed on a page for which {@link isMergedFeedPage} is true. * Returns false when the page has no grid to merge into. */ function mountFeedMerge(options) { const imageList = document.querySelector(SITE_SELECTORS.imageList); if (imageList === null) return false; const queries = feedGroupQueries(options.artistTags, options.groupSize); document.body.classList.add(FEED_MERGE_BODY_CLASS); const own = Array.from(imageList.querySelectorAll(SITE_SELECTORS.thumb)); for (const thumb of own) thumb.classList.add(PENDING_CLASS); const sources = queries.map((query, index) => index === 0 ? { buffer: own.sort(byNewest), nextUrl: readPagerNextUrl() } : { buffer: [], nextUrl: buildUpdatesSearchUrl(query) }); const sentinel = document.createElement("div"); sentinel.className = SENTINEL_CLASS; sentinel.setAttribute("aria-hidden", "true"); const status = document.createElement("div"); status.className = STATUS_CLASS; status.setAttribute("role", "status"); imageList.after(sentinel, status); const seen = /* @__PURE__ */ new Set(); let shown = 0; let running = false; let lastRequestAt = 0; const sentinelNear = () => { const margin = PREFETCH_VIEWPORT_HEIGHTS * window.innerHeight; return sentinel.getBoundingClientRect().top < window.innerHeight + margin; }; const show = (thumbs) => { if (thumbs.length === 0) return; for (const thumb of thumbs) { thumb.classList.remove(PENDING_CLASS); imageList.append(thumb); } shown += thumbs.length; notifyThumbsAdded(imageList); options.onChange(); }; const readGroup = async (index) => { const source = sources[index]; if (source === void 0 || source.nextUrl === null) return; const wait = MIN_REQUEST_INTERVAL_MS$1 - (Date.now() - lastRequestAt); if (lastRequestAt > 0 && wait > 0) await sleep$1(wait); lastRequestAt = Date.now(); status.textContent = `${TEXT_LOADING_PREFIX}${String(index + 1)}${TEXT_LOADING_JOIN}${String(sources.length)}…`; alignSiteAiFilter(AI_SCOPE_FEED); const page = await fetchNextPage(source.nextUrl); const blacklist = readSiteBlacklist(); const fresh = []; for (const thumb of page.thumbs) { const node = document.importNode(thumb, true); applyBlacklist$1(node, blacklist); fresh.push(node); } source.buffer.push(...fresh.sort(byNewest)); source.nextUrl = page.nextUrl; status.textContent = ""; }; const pump = async () => { if (running) return; running = true; try { for (;;) { const result = drainMerged(sources, thumbPostId, seen); show(result.emitted); if (result.starving === null) { status.textContent = TEXT_END$1; return; } if (shown > 0 && !sentinelNear()) return; try { await readGroup(result.starving); } catch (error) { log.warn("feed-merge: fetch failed", error); status.textContent = TEXT_ERROR$1; const retry = document.createElement("button"); retry.type = "button"; retry.className = RETRY_CLASS; retry.textContent = TEXT_RETRY$1; retry.addEventListener("click", () => { status.textContent = ""; pump(); }); status.append(retry); return; } } } finally { running = false; } }; if (typeof IntersectionObserver === "function") { const margin = `${String(PREFETCH_VIEWPORT_HEIGHTS * window.innerHeight)}px`; new IntersectionObserver((entries) => { if (entries.some((entry) => entry.isIntersecting)) pump(); }, { root: null, rootMargin: margin, threshold: 0 }).observe(sentinel); } pump(); return true; } var FEATURE_ID$15 = "feed"; var FEATURE_LABEL$15 = "Feed in site menu"; var FEATURE_PAGES$9 = [ "list", "post", "favorites", "other" ]; var CONTENT_ID$2 = "content"; var POSTS_LINK_TEXT = "Posts"; var FEED_LINK_TEXT = "Feed"; var CURRENT_PAGE_CLASS = "current-page"; var NO_ARTISTS_TITLE = "Follow artists to build your feed"; var MISSING_POSTS_WARN = "feed: Posts menu item not found"; /** * Followed artists for Feed href / page recognition. * Prefers the localStorage mirror (fresh across pages); GM_getValue on bfcache * pages can return a frozen snapshot, so reloadFromStorage alone is not enough. */ function resolveFollowedArtistTags$1() { const mirrored = readArtistsMirror(); if (mirrored !== null && mirrored.length > 0) return [...mirrored]; return listArtistTags(); } /** * store load/save syncs the mirror from GM. On bfcache pages that GM snapshot * is stale and would wipe tags followed on another page — restore afterward. */ function reloadStoragePreservingArtistsMirror() { const mirrored = readArtistsMirror(); loadRecent(); if (mirrored !== null && mirrored.length > 0) writeArtistsMirror(mirrored); } var NEW_PLAQUE_LEFT_PX = 6; var NEW_PLAQUE_TOP_PX = 6; var EVENT_PAGESHOW$1 = "pageshow"; var EVENT_CLICK$2 = "click"; var BODY_CLASS$8 = featureBodyClass(FEATURE_ID$15); var FEATURE_CSS$13 = ` body.${BODY_CLASS$8} span.thumb.new.${THUMB_CLASS} { position: relative; } body.${BODY_CLASS$8} span.thumb.new.${THUMB_CLASS}::after { content: "NEW"; position: absolute; z-index: 4; left: ${String(NEW_PLAQUE_LEFT_PX)}px; top: ${String(NEW_PLAQUE_TOP_PX)}px; background: var(--rdw-accent); color: var(--rdw-surface); font: 700 9.5px system-ui, Segoe UI, sans-serif; letter-spacing: 0.05em; padding: 2px 6px; border-radius: 9px; pointer-events: none; } @supports (anchor-name: --a) { body.${BODY_CLASS$8} span.thumb.new.${THUMB_CLASS}::after { position-anchor: ${THUMB_ANCHOR_NAME}; left: calc(anchor(left) + ${String(NEW_PLAQUE_LEFT_PX)}px); top: calc(anchor(top) + ${String(NEW_PLAQUE_TOP_PX)}px); } } `; var unsubscribeThumbsAdded$2; var pageshowBound$1 = false; var boundFeedLink = null; function findPostsMenuItem() { const content = document.getElementById(CONTENT_ID$2); const anchors = document.querySelectorAll("a"); for (const node of anchors) { if (!(node instanceof HTMLAnchorElement)) continue; if ((node.textContent?.trim() ?? "") !== POSTS_LINK_TEXT) continue; const listItem = node.closest("li"); if (listItem === null) continue; if (content !== null && content.contains(listItem)) continue; return listItem; } return null; } function resolveFeedHref() { const artistTags = resolveFollowedArtistTags$1(); if (artistTags.length === 0) return RDW_HASH_FOLLOWING; return buildFeedUrl(artistTags, getUpdatesGroupSize()); } function findFeedLink() { const feedItem = document.getElementById(FEED_MENU_ITEM_ID); if (!(feedItem instanceof HTMLLIElement)) return null; const feedLink = feedItem.querySelector("a"); return feedLink instanceof HTMLAnchorElement ? feedLink : null; } /** * Recalculate Feed href from current followed artists (bfcache / late follow). * Uses the artists mirror first; falls back to a fresh GM read when the mirror * is missing or empty (GM alone is unreliable after Follow + Back / bfcache). */ function refreshFeedHref() { const feedLink = findFeedLink(); if (feedLink === null) return; feedLink.href = resolveFeedHref(); if (resolveFollowedArtistTags$1().length === 0) feedLink.title = NO_ARTISTS_TITLE; else feedLink.removeAttribute("title"); } function onPageShow$1() { refreshFeedHref(); } function onFeedClick() { refreshFeedHref(); } function ensureFeedHrefListeners(feedLink) { if (!pageshowBound$1) { pageshowBound$1 = true; window.addEventListener(EVENT_PAGESHOW$1, onPageShow$1); } if (boundFeedLink === feedLink) return; if (boundFeedLink !== null) boundFeedLink.removeEventListener(EVENT_CLICK$2, onFeedClick); feedLink.addEventListener(EVENT_CLICK$2, onFeedClick); boundFeedLink = feedLink; } function ensureFeedMenuItem() { const existing = document.getElementById(FEED_MENU_ITEM_ID); if (existing instanceof HTMLLIElement) { const existingLink = existing.querySelector("a"); if (existingLink instanceof HTMLAnchorElement) { refreshFeedHref(); ensureFeedHrefListeners(existingLink); } return existing; } const postsItem = findPostsMenuItem(); if (postsItem === null) { log.warn(MISSING_POSTS_WARN); return null; } const feedItem = document.createElement("li"); feedItem.id = FEED_MENU_ITEM_ID; const feedLink = document.createElement("a"); feedLink.textContent = FEED_LINK_TEXT; feedLink.href = resolveFeedHref(); if (resolveFollowedArtistTags$1().length === 0) feedLink.title = NO_ARTISTS_TITLE; feedItem.append(feedLink); postsItem.after(feedItem); ensureFeedHrefListeners(feedLink); return feedItem; } function isFeedPage(search, artistTags) { const tagsParam = new URLSearchParams(search).get(SEARCH_PARAM_TAGS); if (tagsParam === null || tagsParam.trim().length === 0) return false; return isFullUpdatesQuery(tagsParam, artistTags) || isPartialUpdatesQuery(tagsParam, artistTags) || findFeedGroupIndex(tagsParam, artistTags, getUpdatesGroupSize()) >= 0; } function applyCurrentPageHighlight(feedItem, onFeed, pageKind) { const postsItem = findPostsMenuItem(); if (onFeed) { postsItem?.classList.remove(CURRENT_PAGE_CLASS); feedItem.classList.add(CURRENT_PAGE_CLASS); return; } feedItem.classList.remove(CURRENT_PAGE_CLASS); if (pageKind === "list") postsItem?.classList.add(CURRENT_PAGE_CLASS); } function markNewThumbs(root, seenPostId) { if (seenPostId === 0) return; ensureDocumentStyles(); const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) { if (!(thumb instanceof HTMLElement)) continue; const postId = extractPostIdFromThumb(thumb); if (postId === null) continue; const numeric = Number(postId); if (!Number.isFinite(numeric) || numeric <= seenPostId) continue; ensureThumbAnchor(thumb); thumb.classList.add("new"); } } function ensureNewThumbsSubscription() { if (unsubscribeThumbsAdded$2 !== void 0) return; unsubscribeThumbsAdded$2 = onThumbsAdded((root) => { markNewThumbs(root, getSeenPostId()); }); } function mountFeed(ctx) { const feedItem = ensureFeedMenuItem(); if (feedItem === null) return; const artistTags = resolveFollowedArtistTags$1(); reloadStoragePreservingArtistsMirror(); const onFeed = isFeedPage(ctx.search, artistTags); applyCurrentPageHighlight(feedItem, onFeed, ctx.pageKind); if (ctx.pageKind === "list") rememberArtistsFromPage(ctx.search); if (!onFeed || ctx.pageKind !== "list") return; markNewThumbs(document, getSeenPostId()); ensureNewThumbsSubscription(); const merged = isMergedFeedPage(ctx.search, artistTags, getUpdatesGroupSize()); mountUpdatesBar(document, ctx.search, { merged }); if (merged) mountFeedMerge({ artistTags, groupSize: getUpdatesGroupSize(), onChange: () => { mountUpdatesBar(document, ctx.search, { merged }); } }); } var feedFeature = { id: FEATURE_ID$15, label: FEATURE_LABEL$15, pages: [...FEATURE_PAGES$9], defaultEnabled: true, css: `${FEATURE_CSS$13}\n${FEED_MERGE_CSS}`, mount: mountFeed }; /** * A number beside "Feed" in the menu: how many posts of the first page of the * feed are newer than the newest you have seen there. * * This is the one thing the script asks the site for without being told to: * one request, of the feed's first page, when a page loads (Kaze's decision). * The answer is kept for a while, so going from page to page does not repeat * it. With several feed groups only the first is counted. */ var FEATURE_ID$14 = "feed-counter"; var FEATURE_LABEL$14 = "New posts counter beside Feed"; var FEED_COUNT_CLASS = "rdw-feed-count"; var FEED_COUNT_CACHE_KEY = "ruledesk-web.feed-count"; var BODY_CLASS$7 = featureBodyClass(FEATURE_ID$14); /** Every post of the page is new: there are more behind it. */ var MORE_MARK = "+"; var FEATURE_CSS$12 = ` body.${BODY_CLASS$7} .${FEED_COUNT_CLASS} { display: inline-block; min-width: 16px; margin-left: 6px; padding: 0 5px; border-radius: 999px; background: var(--rdw-accent); /* The site's dark theme colours everything in the menu with a rule stronger than this one would be; the number was the link's green on a green pill. */ color: var(--rdw-surface) !important; font: 700 10.5px/16px var(--rdw-font); text-align: center; vertical-align: middle; } body:not(.${BODY_CLASS$7}) .${FEED_COUNT_CLASS} { display: none; } `.trim(); function isCachedCount(value) { if (typeof value !== "object" || value === null) return false; return "count" in value && typeof value.count === "number" && "more" in value && typeof value.more === "boolean" && "at" in value && typeof value.at === "number" && "seen" in value && typeof value.seen === "number" && "href" in value && typeof value.href === "string"; } function readCache() { try { const raw = window.localStorage.getItem(FEED_COUNT_CACHE_KEY); const parsed = raw === null ? null : JSON.parse(raw); return isCachedCount(parsed) ? parsed : null; } catch { return null; } } function writeCache(value) { try { window.localStorage.setItem(FEED_COUNT_CACHE_KEY, JSON.stringify(value)); } catch {} } /** How many of the thumbs are newer than `seenPostId`. */ function countNewThumbs(thumbs, seenPostId) { let count = 0; for (const thumb of thumbs) { const raw = extractPostIdFromThumb(thumb); const id = raw === null ? NaN : Number(raw); if (Number.isFinite(id) && id > seenPostId) count += 1; } return { count, more: thumbs.length > 0 && count === thumbs.length }; } /** "12", "42+", or nothing for none. */ function feedCountText(value) { if (value.count <= 0) return ""; return value.more ? `${String(value.count)}${MORE_MARK}` : String(value.count); } /** True while a kept answer still stands for this feed and this "seen" mark. */ function isFreshCount(cached, now, seen, href) { return cached !== null && cached.seen === seen && cached.href === href && now - cached.at >= 0 && now - cached.at < 9e5; } function show(link, value) { const text = feedCountText(value); const existing = link.parentElement?.querySelector(`.rdw-feed-count`) ?? null; if (text.length === 0) { existing?.remove(); return; } const badge = existing ?? document.createElement("span"); badge.className = FEED_COUNT_CLASS; badge.textContent = text; badge.setAttribute("aria-label", `${text} new posts in the feed`); if (existing === null) link.append(badge); } function sameSearch(a, b) { try { return new URL(a, window.location.href).search === new URL(b, window.location.href).search; } catch { return false; } } function mountFeedCounter(_ctx) { const link = document.getElementById(FEED_MENU_ITEM_ID)?.querySelector("a"); if (!(link instanceof HTMLAnchorElement)) return; const seen = getSeenPostId(); const href = link.href; if (seen <= 0 || listArtistTags().length === 0 || !href.includes("tags=") || sameSearch(href, window.location.href)) return; const now = Date.now(); const cached = readCache(); if (cached !== null && isFreshCount(cached, now, seen, href)) { show(link, cached); return; } withSiteAiFilter(AI_SCOPE_FEED, () => fetchNextPage(href)).then((page) => { const value = countNewThumbs(page.thumbs, seen); writeCache({ ...value, at: Date.now(), seen, href }); show(link, value); }).catch((error) => { writeCache({ count: 0, more: false, at: Date.now(), seen, href }); log.warn("feed-counter: request failed", error); }); } var feedCounterFeature = { id: FEATURE_ID$14, label: FEATURE_LABEL$14, pages: [ "list", "post", "favorites", "other" ], defaultEnabled: true, settingsCaption: "Asks the site for the first page of the feed when a page loads, at most once in 15 minutes. Counts the first feed group only.", css: FEATURE_CSS$12, mount: mountFeedCounter }; /** Read-only helpers for native post-page markup used by the side panel. */ var LINK_LIST_SELECTOR = "div.link-list ul"; var STATS_SELECTOR = "div#stats"; var FLEXI_SELECTOR = "#fit-to-screen div.flexi, div#right-col div.flexi, div.flexi"; var IMAGE_ID = "image"; var HEADER_SELECTOR = "div#header"; var POST_COMMENTS_ID = "post-comments"; var COMMENT_LIST_ID = "comment-list"; var MORE_LINK_TEXTS = [ "Edit", "Resize image", "Report to moderation", "Add Note" ]; var SCORE_SPAN_ID_PREFIX = "psc"; var STAT_PREFIX_RE = /^(Id|Posted|Size|Source|Rating|Score)\s*:/i; var WHITESPACE_RE = /\s+/g; var BY_SPLIT_RE = /\bby\b/i; var DIGITS_ONLY_RE = /^\d+$/; var COUNTER_CANDIDATE_SELECTOR = "span, b, strong, em, small"; var SOURCE_REL = "nofollow noreferrer"; function isMoreLinkText(value) { for (const entry of MORE_LINK_TEXTS) if (entry === value) return true; return false; } function normalizeSpace(value) { return value.replace(WHITESPACE_RE, " ").trim(); } function liPrefixLabel(li) { const full = normalizeSpace(li.textContent ?? ""); const match = STAT_PREFIX_RE.exec(full); if (match === null) return null; const raw = match[1]; if (raw === void 0) return null; return raw.charAt(0).toUpperCase() + raw.slice(1).toLowerCase(); } function findFlexi() { const node = document.querySelector(FLEXI_SELECTOR); return node instanceof HTMLElement ? node : null; } /** * Media / player wrapper = flexi child that holds video or img#image * (never the panel host). Video posts have no img#image — use the player block. */ function findMediaWrapper(flexi, panelId) { for (const child of flexi.children) { if (!(child instanceof HTMLElement)) continue; if (child.id === panelId) continue; if (child.querySelector("video") !== null) return child; } for (const child of flexi.children) { if (!(child instanceof HTMLElement)) continue; if (child.id === panelId) continue; if (child.querySelector(`#image`) !== null) return child; } for (const child of flexi.children) { if (!(child instanceof HTMLElement)) continue; if (child.id === panelId) continue; return child; } return null; } function findOriginalAnchor() { const list = document.querySelector(LINK_LIST_SELECTOR); const roots = list !== null ? [list, document] : [document]; for (const root of roots) { const links = root.querySelectorAll("a[href]"); for (const node of links) { if (!(node instanceof HTMLAnchorElement)) continue; if (node.textContent?.trim() !== "Original image") continue; const href = node.getAttribute("href"); if (href === null || href.length === 0 || href === "#") continue; return node; } } return null; } function collectMoreLinks() { const list = document.querySelector(LINK_LIST_SELECTOR); if (list === null) return []; const result = []; const links = list.querySelectorAll("a[href]"); for (const node of links) { if (!(node instanceof HTMLAnchorElement)) continue; const text = node.textContent?.trim() ?? ""; if (!isMoreLinkText(text)) continue; result.push({ text, anchor: node }); } return result; } function scoreSpanId(postId) { return `${SCORE_SPAN_ID_PREFIX}${postId}`; } function findScoreSpan(postId) { const span = document.getElementById(scoreSpanId(postId)); return span instanceof HTMLElement ? span : null; } function readScoreText(postId) { const span = findScoreSpan(postId); if (span === null) return null; const text = span.textContent?.trim() ?? ""; return text.length > 0 ? text : null; } function writeScoreText(postId, score) { const span = findScoreSpan(postId); if (span !== null) span.textContent = String(score); } /** Keep panel score in sync when the site mutates span#psc{ID}. */ function observeScoreSpan(postId, onChange) { const span = findScoreSpan(postId); if (span === null) return () => {}; const emit = () => { onChange(span.textContent?.trim() ?? ""); }; const observer = new MutationObserver(emit); observer.observe(span, { characterData: true, childList: true, subtree: true }); return () => { observer.disconnect(); }; } function parsePostedRows(li) { const rows = []; const authorLink = li.querySelector("a[href]"); let authorName = null; let authorHref = null; if (authorLink instanceof HTMLAnchorElement) { const href = authorLink.getAttribute("href"); const name = authorLink.textContent?.trim() ?? ""; if (href !== null && href.length > 0 && name.length > 0) { authorName = name; authorHref = href; } } const clone = li.cloneNode(true); if (!(clone instanceof HTMLElement)) return rows; for (const node of clone.querySelectorAll("a")) node.remove(); for (const node of clone.querySelectorAll("br")) node.replaceWith(" "); let dateText = normalizeSpace(clone.textContent ?? ""); dateText = dateText.replace(/^Posted\s*:\s*/i, ""); dateText = dateText.replace(BY_SPLIT_RE, "").trim(); dateText = normalizeSpace(dateText); if (dateText.length > 0) rows.push({ label: "Posted", value: dateText, href: null }); if (authorName !== null && authorHref !== null) rows.push({ label: "By", value: authorName, href: authorHref }); return rows; } function parseSourceRow(li) { const link = li.querySelector("a[href]"); if (!(link instanceof HTMLAnchorElement)) return null; const href = link.getAttribute("href"); if (href === null || href.length === 0 || href === "#") return null; const text = link.textContent?.trim() ?? ""; return { label: "Source", value: text.length > 0 ? text : href, href }; } function parseSimpleRow(li, label) { const full = normalizeSpace(li.textContent ?? ""); const prefix = `${label}:`; const lower = full.toLowerCase(); const prefixLower = prefix.toLowerCase(); if (!lower.startsWith(prefixLower)) return null; const value = full.slice(prefix.length).trim(); if (value.length === 0) return null; return { label, value, href: null }; } /** * Parse statistics lis by prefix before colon. * Posted → date + By (author link) as separate rows. Score is not a stats row. */ function readStatRows() { const stats = document.querySelector(STATS_SELECTOR); if (stats === null) return []; const rows = []; const seen = /* @__PURE__ */ new Set(); const items = stats.querySelectorAll("li"); for (const node of items) { if (!(node instanceof HTMLElement)) continue; const prefix = liPrefixLabel(node); if (prefix === null || prefix === "Score") continue; if (prefix === "Posted") { for (const row of parsePostedRows(node)) if (!seen.has(row.label)) { seen.add(row.label); rows.push(row); } continue; } if (prefix === "Source") { if (seen.has("Source")) continue; const row = parseSourceRow(node); if (row !== null) { seen.add("Source"); rows.push(row); } continue; } if (prefix === "Id" || prefix === "Size" || prefix === "Rating") { if (seen.has(prefix)) continue; const row = parseSimpleRow(node, prefix); if (row !== null) { seen.add(prefix); rows.push(row); } } } return rows; } var SOURCE_LINK_REL = SOURCE_REL; function readDigitsCandidate(node) { const text = normalizeSpace(node.textContent ?? ""); if (DIGITS_ONLY_RE.test(text)) return text; return null; } function readCountInElement(root) { for (const node of root.querySelectorAll(COUNTER_CANDIDATE_SELECTOR)) { const digits = readDigitsCandidate(node); if (digits !== null) return digits; } const own = readDigitsCandidate(root); if (own !== null) return own; return null; } /** * Look for a numeric counter in the same li or immediate neighbor lis/elements. * Does not scan the whole stats ul (would false-match span#psc{ID}). * No known site counter element → returns null (report «нужна разметка»). */ function findICameCount(anchor) { const li = anchor.closest("li"); if (li !== null) { for (const node of li.querySelectorAll(COUNTER_CANDIDATE_SELECTOR)) { if (anchor.contains(node)) continue; const digits = readDigitsCandidate(node); if (digits !== null) return digits; } for (const child of li.childNodes) { if (child.nodeType !== Node.TEXT_NODE) continue; const digits = normalizeSpace(child.textContent ?? ""); if (DIGITS_ONLY_RE.test(digits)) return digits; } const neighborLis = [li.previousElementSibling, li.nextElementSibling]; for (const neighbor of neighborLis) { if (!(neighbor instanceof HTMLElement)) continue; if (neighbor.querySelector("a[onclick^=\"iCame(\"]") !== null) continue; if (liPrefixLabel(neighbor) !== null) continue; const digits = readCountInElement(neighbor); if (digits !== null) return digits; } } const sibling = anchor.nextElementSibling; if (sibling !== null) { const digits = readCountInElement(sibling); if (digits !== null) return digits; } return null; } function findICameTarget() { const scoped = document.querySelector("div#stats > ul")?.querySelector("a[onclick^=\"iCame(\"]") ?? document.querySelector("a[onclick^=\"iCame(\"]"); if (!(scoped instanceof HTMLAnchorElement)) return null; return { anchor: scoped, count: findICameCount(scoped) }; } function measureHeaderOffsetPx(gapPx) { const header = document.querySelector(HEADER_SELECTOR); if (!(header instanceof HTMLElement)) return gapPx; return header.getBoundingClientRect().height + gapPx; } /** Native comments block on the post page (moved into the panel, not cloned). */ function findPostComments() { const node = document.getElementById(POST_COMMENTS_ID); return node instanceof HTMLElement ? node : null; } var COMMENT_COUNT_RE = /^(\d+)\s+comments?\b/i; /** * Parse leading «N comment(s)» from the first non-empty text node under * div#comment-list (not full textContent — child nodes glue into one word * and break the trailing word-boundary). * Returns null when the list is missing or the prefix is unparseable. */ function readCommentCount() { const list = document.getElementById(COMMENT_LIST_ID); if (list === null) return null; for (const child of list.childNodes) { if (child.nodeType !== Node.TEXT_NODE) continue; const text = normalizeSpace(child.textContent ?? ""); if (text.length === 0) continue; const match = COMMENT_COUNT_RE.exec(text); if (match === null) return null; const raw = match[1]; if (raw === void 0) return null; const parsed = Number(raw); if (!Number.isFinite(parsed)) return null; return Math.trunc(parsed); } return null; } /** * A post that is an animated GIF moves on its page. * * The site puts a still, scaled-down copy on the page * (`/samples/…/sample_.jpg`) and keeps the GIF itself behind the * "Original image" link, so nothing moves until the original is opened. Here * the picture of the page is pointed at the original. The size the site gave * the picture stays, so the page does not jump. * * The one thing this asks the site for is the GIF itself, the file of the * post the user has opened. */ var FEATURE_ID$13 = "gif-post"; var FEATURE_LABEL$13 = "Play GIFs on the post page"; var GIF_PATH = /\.gif$/i; var GIF_PLAYING_ATTRIBUTE = "data-rdw-gif"; function pathOf$1(url) { try { return new URL(url, window.location.href).pathname; } catch { return url; } } /** True when the address ends in `.gif`, whatever follows the question mark. */ function isGifUrl(url) { return GIF_PATH.test(pathOf$1(url)); } /** * Points the picture of the page at the original GIF. Returns true when it * did: the original is a GIF and the picture shows something else. */ function playGifOnPage(root = document, originalHref) { const image = root.querySelector(`img#${IMAGE_ID}`); const original = findOriginalAnchor()?.href ?? ""; if (!(image instanceof HTMLImageElement) || !isGifUrl(original)) return false; if (isGifUrl(image.currentSrc || image.src)) return false; image.setAttribute(GIF_PLAYING_ATTRIBUTE, ""); image.src = original; return true; } function mountGifPost(_ctx) { if (document.body.classList.contains(featureBodyClass(FEATURE_ID$13))) playGifOnPage(); } var gifPostFeature = { id: FEATURE_ID$13, label: FEATURE_LABEL$13, pages: ["post"], defaultEnabled: true, settingsCaption: "The site shows a still copy of a GIF until its original is opened. With this on, the original is loaded at once.", css: "", mount: mountGifPost }; /** * The picture of a post in its full size (the designer's variant C, * 18.11.2026; a request Kaze agreed to the same day). * * The site puts a scaled-down copy on the page, some 850 px wide, and keeps * the file itself behind the "Original image" link. With this on, the file is * loaded and put in place of the copy: sharper, and as wide as the room * between the columns lets it be, never wider than it is. It is off unless * turned on: an original is often several megabytes. * * The copy stays on the page until the original has come whole, so nothing is * blank meanwhile and the page changes once. Beside the panel the block of the * picture gives way, not the panel: the row is kept from wrapping, or a wide * original would push the panel under itself. The one thing asked of the site * is the file of the post the user has opened, and it is asked once. */ var FEATURE_ID$12 = "full-image"; var FEATURE_LABEL$12 = "Load full-size image"; var FEATURE_CAPTION$1 = "Sharper and larger, but the page opens slower: originals are often several MB."; /** On the picture once it shows the original. */ var FULL_IMAGE_ATTRIBUTE = "data-rdw-full"; /** What an original has to be for this: a still picture. A GIF is the other feature's. */ var STILL_PATH = /\.(?:jpe?g|png|webp|bmp)$/i; /** As in post-actions.ts: from this width the panel stands beside the picture. */ var WIDE_MEDIA_QUERY$1 = "(min-width: 1100px)"; var BODY_SELECTOR$3 = `body.${featureBodyClass(FEATURE_ID$12)}`; var FULL_SELECTOR = `img#${IMAGE_ID}[${FULL_IMAGE_ATTRIBUTE}]`; var FEATURE_CSS$11 = ` ${BODY_SELECTOR$3} ${FULL_SELECTOR} { width: auto !important; height: auto !important; max-width: 100%; } @media ${WIDE_MEDIA_QUERY$1} { ${BODY_SELECTOR$3} div#post-view > div#right-col { flex-grow: 1; min-width: 0; } ${BODY_SELECTOR$3} div.flexi:has(${FULL_SELECTOR}) { flex-wrap: nowrap; } ${BODY_SELECTOR$3} div.flexi > :has(${FULL_SELECTOR}) { flex: 0 1 auto; min-width: 0; } ${BODY_SELECTOR$3} div.flexi:has(${FULL_SELECTOR}) > #${POST_ACTIONS_ID} { flex-shrink: 0; } } `.trim(); function pathOf(url) { try { return new URL(url, window.location.href).pathname; } catch { return url; } } /** * The address of the original when it is worth loading: a still picture, and * not the one the page already shows. Null otherwise. */ function fullImageUrl(image, originalHref) { if (originalHref.length === 0 || isGifUrl(originalHref)) return null; const path = pathOf(originalHref); if (!STILL_PATH.test(path) || pathOf(image.currentSrc || image.src) === path) return null; return originalHref; } /** * Loads the original beside the page and, once it has come, shows it in place * of the copy. Returns true when the loading was started. */ function loadFullImage(root = document, originalHref) { const image = root.querySelector(`img#${IMAGE_ID}`); if (!(image instanceof HTMLImageElement)) return false; const url = fullImageUrl(image, findOriginalAnchor()?.href ?? ""); if (url === null) return false; const loader = new Image(); loader.addEventListener("load", () => { if (!image.isConnected) return; image.setAttribute(FULL_IMAGE_ATTRIBUTE, ""); image.src = url; }); loader.src = url; return true; } function mountFullImage(_ctx) { if (document.body.classList.contains(featureBodyClass(FEATURE_ID$12))) loadFullImage(); } var fullImageFeature = { id: FEATURE_ID$12, label: FEATURE_LABEL$12, pages: ["post"], defaultEnabled: false, settingsCaption: FEATURE_CAPTION$1, css: FEATURE_CSS$11, mount: mountFullImage }; var FEATURE_ID$11 = "grid-density"; var COMPACT_PX = 150; var LARGE_PX = 250; var CHOICE_DEFAULT = "default"; var CHOICE_COMPACT = "compact"; var CHOICE_LARGE = "large"; function sizeCss(choiceValue, px) { const bodyClass = featureChoiceBodyClass(FEATURE_ID$11, choiceValue); return [ `body.${bodyClass} span.thumb,`, `body.${bodyClass} span.thumb > a {`, ` width: ${String(px)}px !important;`, ` height: ${String(px)}px !important;`, `}`, `body.${bodyClass} img.preview {`, ` max-width: ${String(px)}px !important;`, ` max-height: ${String(px)}px !important;`, `}` ].join("\n"); } /** Same gap on both axes for Default, Compact, and Large. Does not set cell size. */ function gapCss() { return [ `body.${featureBodyClass(FEATURE_ID$11)} div.image-list {`, ` column-gap: ${String(4)}px !important;`, ` row-gap: ${String(4)}px !important;`, `}` ].join("\n"); } var gridDensityFeature = exports("cg",{ id: FEATURE_ID$11, label: "Grid size", pages: ["list", "favorites"], defaultEnabled: true, cssOnly: true, choice: { options: [ { value: CHOICE_DEFAULT, label: "Default" }, { value: CHOICE_COMPACT, label: "Compact (150)" }, { value: CHOICE_LARGE, label: "Large (250)" } ], defaultValue: CHOICE_DEFAULT }, css: [ sizeCss(CHOICE_COMPACT, COMPACT_PX), sizeCss(CHOICE_LARGE, LARGE_PX), gapCss() ].join("\n"), mount: () => void 0 }); var SEEN_DIM_FEATURE_ID = "seen-dim"; var SEEN_CLASS = "rdw-seen"; var SEEN_DIM_LABEL = "Dim seen posts"; var SEEN_DIM_OPACITY = "0.65"; var SEEN_DIM_HOVER_OPACITY = "1"; var EVENT_PAGESHOW = "pageshow"; var unsubscribeThumbsAdded$1; var pageshowBound = false; function stampSeenOnThumbs(root = document) { const marks = load$1().marks; const thumbs = root.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) { if (!(thumb instanceof HTMLElement)) continue; const postId = extractPostIdFromThumb(thumb); if (postId === null) continue; thumb.classList.toggle(SEEN_CLASS, marks[postId]?.seen === true); } } function onPageShow(event) { if (!event.persisted) return; reloadFromStorage(); stampSeenOnThumbs(document); } function ensureListSubscriptions() { if (unsubscribeThumbsAdded$1 === void 0) unsubscribeThumbsAdded$1 = onThumbsAdded((root) => { stampSeenOnThumbs(root); }); if (!pageshowBound) { pageshowBound = true; window.addEventListener(EVENT_PAGESHOW, onPageShow); } } function mountSeenDim(ctx) { if (ctx.pageKind === "post") { const postId = readPostIdFromSearch(ctx.search); if (postId === null) { log.warn("seen-dim: missing post id in search", ctx.search); return; } setPostSeenMark(postId); return; } if (ctx.pageKind !== "list") return; stampSeenOnThumbs(document); ensureListSubscriptions(); } var seenDimFeature = { id: SEEN_DIM_FEATURE_ID, label: SEEN_DIM_LABEL, pages: ["list", "post"], defaultEnabled: true, cssOnly: true, css: ` body.${featureBodyClass(SEEN_DIM_FEATURE_ID)} .${SEEN_CLASS} img.preview { opacity: ${SEEN_DIM_OPACITY}; } body.${featureBodyClass(SEEN_DIM_FEATURE_ID)} .${SEEN_CLASS}:hover img.preview { opacity: ${SEEN_DIM_HOVER_OPACITY}; } `, mount: mountSeenDim }; /** * A click on the picture of a post opens it over the page, where it can be * zoomed with the wheel and dragged. Pictures and GIFs only: a video post has * no `img#image`, and its player is left alone. * * The viewer shows the original file (the site's own "Original image" link), * so the one thing it asks the site for is that file, and only on the click. */ var FEATURE_ID$10 = "image-zoom"; var FEATURE_LABEL$11 = "Zoom the picture on click"; var BODY_CLASS$6 = featureBodyClass(FEATURE_ID$10); var VIEWER_ID = "rdw-image-viewer"; var STAGE_CLASS = "rdw-image-viewer-stage"; var IMAGE_CLASS = "rdw-image-viewer-image"; var BAR_CLASS = "rdw-image-viewer-bar"; var BUTTON_CLASS = "rdw-image-viewer-button"; var SCALE_CLASS = "rdw-image-viewer-scale"; var DRAGGING_CLASS = "rdw-image-viewer--dragging"; var VIEWER_Z_INDEX = 2147483e3; /** Space kept around a picture fitted to the window. */ var FIT_MARGIN_PX = 24; /** One step of the wheel or of the buttons. */ var ZOOM_STEP = 1.2; /** A press that moves less than this is a click, not a drag. */ var DRAG_SLOP_PX = 4; var LABEL_VIEWER = "Picture viewer"; var LABEL_ZOOM_IN = "Zoom in"; var LABEL_ZOOM_OUT = "Zoom out"; var LABEL_FIT = "Fit to window"; var LABEL_ACTUAL = "Actual size"; var LABEL_CLOSE = "Close"; var TEXT_ZOOM_IN = "+"; var TEXT_ZOOM_OUT = "−"; var TEXT_FIT = "Fit"; var TEXT_ACTUAL = "1:1"; var TEXT_CLOSE = "✕"; var FEATURE_CSS$10 = ` body.${BODY_CLASS$6} img#${IMAGE_ID} { cursor: zoom-in; } #${VIEWER_ID} { position: fixed; inset: 0; z-index: ${String(VIEWER_Z_INDEX)}; background: rgba(0, 0, 0, 0.88); overflow: hidden; touch-action: none; cursor: grab; } #${VIEWER_ID}.${DRAGGING_CLASS} { cursor: grabbing; } #${VIEWER_ID} .${STAGE_CLASS} { position: absolute; inset: 0; } #${VIEWER_ID} .${IMAGE_CLASS} { position: absolute; left: 50%; top: 50%; max-width: none; max-height: none; transform-origin: center; user-select: none; -webkit-user-drag: none; } #${VIEWER_ID} .${BAR_CLASS} { position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%); display: flex; align-items: center; gap: 4px; padding: 4px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); background: var(--rdw-surface); color: var(--rdw-text); font: 12px var(--rdw-font); cursor: default; } #${VIEWER_ID} .${BUTTON_CLASS} { min-width: 30px; height: 28px; padding: 0 8px; border: 0; border-radius: var(--rdw-radius-s); background: transparent; color: var(--rdw-text); font: 600 12px var(--rdw-font); cursor: pointer; } #${VIEWER_ID} .${BUTTON_CLASS}:hover, #${VIEWER_ID} .${BUTTON_CLASS}:focus-visible { background: var(--rdw-surface-2); } #${VIEWER_ID} .${BUTTON_CLASS}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: -2px; } #${VIEWER_ID} .${SCALE_CLASS} { min-width: 44px; text-align: center; color: var(--rdw-muted); font-variant-numeric: tabular-nums; } `.trim(); /** The scale at which a picture of this size fits the window, never above 1. */ function fitScale(imageWidth, imageHeight, viewWidth, viewHeight) { if (imageWidth <= 0 || imageHeight <= 0) return 1; const roomWidth = Math.max(1, viewWidth - 48); const roomHeight = Math.max(1, viewHeight - 48); return Math.min(1, roomWidth / imageWidth, roomHeight / imageHeight); } /** A picture this many windows tall at the window's width is read, not looked at whole. */ var TALL_WINDOWS = 2; /** * How a picture is shown when the viewer opens. One that fits is fitted. A * tall one, a comic of several screens, fitted whole is a narrow strip nobody * can read (smaller than on the post page itself): it opens at the width of * the window, from its top, and is dragged or zoomed from there. "Fit" and * zooming out still give the whole picture. */ function openingState(imageWidth, imageHeight, viewWidth, viewHeight) { const whole = fitScale(imageWidth, imageHeight, viewWidth, viewHeight); if (imageWidth <= 0 || imageHeight <= 0) return { scale: whole, x: 0, y: 0 }; const byWidth = Math.min(1, Math.max(1, viewWidth - 48) / imageWidth); const shownHeight = imageHeight * byWidth; if (byWidth <= whole || shownHeight < viewHeight * TALL_WINDOWS) return { scale: whole, x: 0, y: 0 }; return { scale: byWidth, x: 0, y: (shownHeight - viewHeight) / 2 + FIT_MARGIN_PX }; } /** How far the picture may be moved up or down from the centre, at this scale. */ function verticalReach(imageHeight, scale, viewHeight) { const over = imageHeight * scale - viewHeight; return over > 0 ? over / 2 + FIT_MARGIN_PX : 0; } /** True when the picture, as shown, is taller than the window: it is then read by scrolling. */ function isTallerThanWindow(imageHeight, scale, viewHeight) { return imageHeight * scale > viewHeight; } /** * The picture moved by `dy` pixels up (a positive `dy`, as the wheel gives * it), never past its top or its bottom. */ function scrollPicture(state, dy, imageHeight, viewHeight) { const reach = verticalReach(imageHeight, state.scale, viewHeight); if (reach === 0) return { ...state, y: 0 }; return { ...state, y: Math.min(reach, Math.max(-reach, state.y - dy)) }; } /** The least scale: the fitted one, so a picture cannot be lost by zooming out. */ function clampScale(scale, fit) { return Math.min(8, Math.max(fit, scale)); } /** * Zooms by `factor` so that the point of the picture under (`px`, `py`), * given from the window's centre, stays under it. */ function zoomAt(state, factor, px, py, fit) { const scale = clampScale(state.scale * factor, fit); const ratio = scale / state.scale; if (scale === fit) return { scale, x: 0, y: 0 }; return { scale, x: px - (px - state.x) * ratio, y: py - (py - state.y) * ratio }; } var viewer = null; function render(target) { const { state } = target; target.image.style.transform = `translate(-50%, -50%) translate(${String(state.x)}px, ${String(state.y)}px) scale(${String(state.scale)})`; target.scaleLabel.textContent = `${String(Math.round(state.scale * 100))}%`; } function refit(target, reset) { target.fit = fitScale(target.image.naturalWidth, target.image.naturalHeight, window.innerWidth, window.innerHeight); target.state = reset ? { scale: target.fit, x: 0, y: 0 } : { ...target.state, scale: clampScale(target.state.scale, target.fit) }; render(target); } function zoomBy(target, factor, px, py) { target.state = zoomAt(target.state, factor, px, py, target.fit); render(target); } function closeImageViewer() { if (viewer === null) return; const { root, opener } = viewer; viewer = null; root.remove(); document.removeEventListener("keydown", onKeyDown$1, true); window.removeEventListener("resize", onResize); opener?.focus(); } function onKeyDown$1(event) { if (viewer === null) return; if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); closeImageViewer(); } else if (event.key === "+" || event.key === "=") zoomBy(viewer, ZOOM_STEP, 0, 0); else if (event.key === "-") zoomBy(viewer, 1 / ZOOM_STEP, 0, 0); else if (event.key === "0") refit(viewer, true); else { const step = SCROLL_KEYS.get(event.key); if (step !== void 0 && scrollViewer(viewer, step * window.innerHeight)) event.preventDefault(); } } /** Keys that move a tall picture, in windows: down is positive. */ var SCROLL_KEYS = /* @__PURE__ */ new Map([ ["ArrowDown", .15], ["ArrowUp", -0.15], ["PageDown", .9], ["PageUp", -0.9], [" ", .9], ["End", Number.MAX_SAFE_INTEGER], ["Home", -Number.MAX_SAFE_INTEGER] ]); /** Moves the picture when it is taller than the window. Returns false when it is not. */ function scrollViewer(target, dy) { const height = target.image.naturalHeight; if (!isTallerThanWindow(height, target.state.scale, window.innerHeight)) return false; target.state = scrollPicture(target.state, dy, height, window.innerHeight); render(target); return true; } function onResize() { if (viewer !== null) refit(viewer, false); } function barButton(text, label, onClick) { const button = document.createElement("button"); button.type = "button"; button.className = BUTTON_CLASS; button.textContent = text; button.setAttribute("aria-label", label); button.title = label; button.addEventListener("click", (event) => { event.stopPropagation(); onClick(); }); return button; } /** Opens the viewer on `url`. `opener` gets the focus back when it closes. */ function openImageViewer(url, opener) { closeImageViewer(); const root = document.createElement("div"); root.id = VIEWER_ID; root.setAttribute("role", "dialog"); root.setAttribute("aria-modal", "true"); root.setAttribute("aria-label", LABEL_VIEWER); root.tabIndex = -1; const stage = document.createElement("div"); stage.className = STAGE_CLASS; const image = document.createElement("img"); image.className = IMAGE_CLASS; image.alt = ""; image.draggable = false; stage.append(image); const scaleLabel = document.createElement("span"); scaleLabel.className = SCALE_CLASS; const bar = document.createElement("div"); bar.className = BAR_CLASS; const created = { root, image, scaleLabel, opener, state: { scale: 1, x: 0, y: 0 }, fit: 1 }; bar.append(barButton(TEXT_ZOOM_OUT, LABEL_ZOOM_OUT, () => { zoomBy(created, 1 / ZOOM_STEP, 0, 0); }), scaleLabel, barButton(TEXT_ZOOM_IN, LABEL_ZOOM_IN, () => { zoomBy(created, ZOOM_STEP, 0, 0); }), barButton(TEXT_FIT, LABEL_FIT, () => { refit(created, true); }), barButton(TEXT_ACTUAL, LABEL_ACTUAL, () => { created.state = { scale: clampScale(1, created.fit), x: 0, y: 0 }; render(created); }), barButton(TEXT_CLOSE, LABEL_CLOSE, closeImageViewer)); bar.addEventListener("pointerdown", (event) => { event.stopPropagation(); }); root.append(stage, bar); image.addEventListener("load", () => { refit(created, true); created.state = openingState(image.naturalWidth, image.naturalHeight, window.innerWidth, window.innerHeight); render(created); }); image.src = url; root.addEventListener("wheel", (event) => { event.preventDefault(); if (!event.ctrlKey && scrollViewer(created, event.deltaY)) return; const px = event.clientX - window.innerWidth / 2; const py = event.clientY - window.innerHeight / 2; zoomBy(created, event.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP, px, py); }, { passive: false }); let drag = null; root.addEventListener("pointerdown", (event) => { if (event.button !== 0) return; drag = { startX: event.clientX, startY: event.clientY, x: created.state.x, y: created.state.y, moved: false }; root.setPointerCapture?.(event.pointerId); }); root.addEventListener("pointermove", (event) => { if (drag === null) return; const dx = event.clientX - drag.startX; const dy = event.clientY - drag.startY; if (!drag.moved && Math.hypot(dx, dy) < DRAG_SLOP_PX) return; drag.moved = true; root.classList.add(DRAGGING_CLASS); created.state = { ...created.state, x: drag.x + dx, y: drag.y + dy }; render(created); }); root.addEventListener("pointerup", (event) => { const ended = drag; drag = null; root.classList.remove(DRAGGING_CLASS); if (ended !== null && !ended.moved && event.target !== image) closeImageViewer(); }); root.addEventListener("dblclick", (event) => { if (event.target !== image) return; if (created.state.scale > created.fit) refit(created, true); else { const px = event.clientX - window.innerWidth / 2; const py = event.clientY - window.innerHeight / 2; zoomBy(created, 1 / created.state.scale, px, py); } }); viewer = created; document.body.append(root); document.addEventListener("keydown", onKeyDown$1, true); window.addEventListener("resize", onResize); render(created); root.focus(); } function onImageClick(event) { if (!document.body.classList.contains(BODY_CLASS$6)) return; const target = event.target; if (!(target instanceof HTMLImageElement) || target.id !== "image") return; if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; event.preventDefault(); event.stopPropagation(); const original = findOriginalAnchor()?.href ?? ""; openImageViewer(original.length > 0 ? original : target.currentSrc || target.src, target); } var bound = false; function mountImageZoom(_ctx) { if (bound) return; bound = true; document.addEventListener("click", onImageClick, true); } var imageZoomFeature = { id: FEATURE_ID$10, label: FEATURE_LABEL$11, pages: ["post"], defaultEnabled: true, cssOnly: true, settingsCaption: "Pictures and GIFs. Scroll to zoom, drag to move, Esc to close.", css: FEATURE_CSS$10, mount: mountImageZoom }; var FEATURE_ID$9 = "infinite-scroll"; var FEATURE_LABEL$10 = "Infinite scroll"; var FEATURE_PAGES$8 = ["list"]; var BODY_FEATURE_CLASS$2 = featureBodyClass(FEATURE_ID$9); /** Prefetch when remaining distance to list end ≤ this many viewport heights. */ var PREFETCH_REMAINING_VIEWPORT_HEIGHTS = 2; var MIN_REQUEST_INTERVAL_MS = 1e3; var CLASS_SENTINEL = "rdw-infinite-sentinel"; var CLASS_STATUS = "rdw-infinite-status"; var CLASS_SEPARATOR = "rdw-infinite-page"; var CLASS_RETRY = "rdw-infinite-retry"; var CLASS_BLACKLISTED = "rdw-blacklisted"; var TEXT_LOADING$1 = "Loading…"; var TEXT_END = "End of results"; var TEXT_ERROR = "Failed to load more"; var TEXT_RETRY = "Retry"; var TEXT_STALLED = "Paused: the last pages added nothing to the screen"; var TEXT_LOAD_MORE = "Load more"; var PAGE_LABEL_PREFIX = "Page "; var PAGINATION_NEXT_SELECTOR = "div.pagination a[alt=\"next\"]"; var WARN_MISSING = "infinite-scroll: missing image-list or next link; not mounted"; var SCORE_TOKEN_PREFIX$1 = "score:"; var RATING_TOKEN_PREFIX = "rating:"; var FEATURE_CSS$9 = ` body.${BODY_FEATURE_CLASS$2} .${CLASS_SENTINEL} { display: block; width: 100%; height: 1px; margin: 0; padding: 0; border: 0; pointer-events: none; } body.${BODY_FEATURE_CLASS$2} .${CLASS_STATUS} { display: block; width: 100%; margin: 0.75rem 0; text-align: center; font-size: 0.875rem; line-height: 1.4; } body.${BODY_FEATURE_CLASS$2} .${CLASS_SEPARATOR} { display: block; width: 100%; margin: 0.75rem 0 0.5rem; text-align: center; font-size: 0.8125rem; font-weight: 600; opacity: 0.75; } body.${BODY_FEATURE_CLASS$2} .${CLASS_RETRY} { margin-left: 0.5rem; color: inherit; background: transparent; border: 1px solid currentColor; border-radius: 2px; padding: 0.15rem 0.5rem; cursor: pointer; font: inherit; } body.${BODY_FEATURE_CLASS$2} .${CLASS_RETRY}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } body.${BODY_FEATURE_CLASS$2} span.thumb.${CLASS_BLACKLISTED} { display: none !important; } `.trim(); function sleep(ms) { return new Promise((resolve) => { window.setTimeout(resolve, ms); }); } function readInitialNextUrl() { const nextLink = document.querySelector(PAGINATION_NEXT_SELECTOR); if (!(nextLink instanceof HTMLAnchorElement)) return null; const href = nextLink.getAttribute("href"); if (href === null || href.length === 0 || href === "#") return null; try { return new URL(href, window.location.href).href; } catch { return null; } } function parseThumbMeta(thumb) { const img = thumb.querySelector(SITE_SELECTORS.previewImage); const title = img?.getAttribute("title")?.trim() ?? ""; const alt = img?.getAttribute("alt")?.trim() ?? ""; const source = title.length > 0 ? title : alt; if (source.length === 0) return { tags: [], score: 0, rating: "" }; const tags = []; let score = 0; let rating = ""; for (const token of source.split(/\s+/)) { if (token.length === 0) continue; const lower = token.toLowerCase(); if (lower.startsWith(SCORE_TOKEN_PREFIX$1)) { const raw = token.slice(6); const parsed = Number(raw); if (Number.isFinite(parsed)) score = parsed; continue; } if (lower.startsWith(RATING_TOKEN_PREFIX)) { rating = token.slice(7); continue; } tags.push(token); } return { tags, score, rating }; } function collectExistingThumbIds() { const ids = /* @__PURE__ */ new Set(); const thumbs = document.querySelectorAll(SITE_SELECTORS.thumb); for (const thumb of thumbs) if (thumb.id.length > 0) ids.add(thumb.id); return ids; } function applyBlacklist(thumb, list) { if (!(thumb instanceof HTMLElement)) return; const meta = parseThumbMeta(thumb); if (isBlacklisted(meta.tags, meta.score, meta.rating, list)) thumb.classList.add(CLASS_BLACKLISTED); } function createSeparator(pageNumber) { const separator = document.createElement("div"); separator.className = CLASS_SEPARATOR; separator.textContent = `${PAGE_LABEL_PREFIX}${String(pageNumber)}`; return separator; } function createUi(imageList) { const sentinel = document.createElement("div"); sentinel.className = CLASS_SENTINEL; sentinel.setAttribute("aria-hidden", "true"); const status = document.createElement("div"); status.className = CLASS_STATUS; status.setAttribute("role", "status"); status.setAttribute("aria-live", "polite"); imageList.after(sentinel, status); return { sentinel, status }; } function setStatusLoading(status) { status.replaceChildren(); status.textContent = TEXT_LOADING$1; } function setStatusEnd(status) { status.replaceChildren(); status.textContent = TEXT_END; } function setStatusError(status, onRetry) { status.replaceChildren(); const message = document.createElement("span"); message.textContent = TEXT_ERROR; const retry = document.createElement("button"); retry.type = "button"; retry.className = CLASS_RETRY; retry.textContent = TEXT_RETRY; retry.addEventListener("click", (event) => { event.preventDefault(); onRetry(); }); status.append(message, retry); } /** Shown when loading was paused because the pages add nothing to the screen. */ function setStatusStalled(status, onContinue) { status.replaceChildren(); const message = document.createElement("span"); message.textContent = TEXT_STALLED; const more = document.createElement("button"); more.type = "button"; more.className = CLASS_RETRY; more.textContent = TEXT_LOAD_MORE; more.addEventListener("click", (event) => { event.preventDefault(); onContinue(); }); status.append(message, more); } /** Height of the whole page; 0 where there is no layout to measure. */ function pageHeight() { return document.documentElement.scrollHeight; } function clearStatus(status) { status.replaceChildren(); } function prefetchRootMarginPx() { return PREFETCH_REMAINING_VIEWPORT_HEIGHTS * window.innerHeight; } function prefetchRootMarginCss() { return `${String(prefetchRootMarginPx())}px`; } /** True when the sentinel is within the prefetch margin of the viewport (IO may not re-fire). */ function isSentinelNear(sentinel) { const rect = sentinel.getBoundingClientRect(); const marginPx = prefetchRootMarginPx(); const viewBottom = window.innerHeight + marginPx; const viewTop = -marginPx; return rect.top < viewBottom && rect.bottom > viewTop; } function mountInfiniteScroll(_ctx) { if (document.body.classList.contains("rdw-feed-merged")) return; const imageList = document.querySelector(SITE_SELECTORS.imageList); if (imageList === null) { log.warn(WARN_MISSING); return; } let nextUrl = readInitialNextUrl(); if (nextUrl === null) { log.warn(WARN_MISSING); return; } const { sentinel, status } = createUi(imageList); let inFlight = false; let lastRequestAt = 0; let pageNumber = 1; let ended = false; let stalledLoads = 0; let observer = null; const finish = () => { ended = true; nextUrl = null; setStatusEnd(status); if (observer !== null) { observer.disconnect(); observer = null; } }; const appendBatch = async (requestUrl) => { alignSiteAiFilter(currentListScope() ?? "posts"); const result = await fetchNextPage(requestUrl); let added = 0; pageNumber += 1; imageList.append(createSeparator(pageNumber)); const existingIds = collectExistingThumbIds(); const blacklist = readSiteBlacklist(); for (const thumb of result.thumbs) { if (thumb.id.length > 0 && existingIds.has(thumb.id)) continue; const node = document.importNode(thumb, true); if (node.id.length > 0) existingIds.add(node.id); applyBlacklist(node, blacklist); imageList.append(node); added += 1; } notifyThumbsAdded(imageList); return { nextUrl: result.nextUrl, added }; }; const loadMore = async (options) => { if (ended || inFlight || nextUrl === null) return; inFlight = true; let bypassRateLimit = options?.bypassRateLimit === true; try { while (!ended && nextUrl !== null && (options?.single === true || isSentinelNear(sentinel))) { const elapsed = Date.now() - lastRequestAt; if (!bypassRateLimit && lastRequestAt > 0 && elapsed < MIN_REQUEST_INTERVAL_MS) { await sleep(MIN_REQUEST_INTERVAL_MS - elapsed); continue; } bypassRateLimit = false; const requestUrl = nextUrl; lastRequestAt = Date.now(); setStatusLoading(status); try { const heightBefore = pageHeight(); const batch = await appendBatch(requestUrl); nextUrl = batch.nextUrl; clearStatus(status); if (nextUrl === null) { finish(); return; } const grew = heightBefore === 0 || pageHeight() > heightBefore; const useful = batch.added > 0 && grew; stalledLoads = useful ? 0 : stalledLoads + 1; const single = options?.single === true; if (stalledLoads >= 2 || single && !useful) { stalledLoads = 0; setStatusStalled(status, () => { loadMore({ bypassRateLimit: true, single: true }); }); return; } if (single) return; } catch (error) { log.warn("infinite-scroll: fetch failed", requestUrl, error); setStatusError(status, () => { loadMore({ bypassRateLimit: true }); }); return; } } } finally { inFlight = false; } }; observer = new IntersectionObserver((entries) => { for (const entry of entries) { if (!entry.isIntersecting) continue; loadMore(); break; } }, { root: null, rootMargin: prefetchRootMarginCss(), threshold: 0 }); observer.observe(sentinel); } var infiniteScrollFeature = { id: FEATURE_ID$9, label: FEATURE_LABEL$10, pages: [...FEATURE_PAGES$8], defaultEnabled: true, css: FEATURE_CSS$9, mount: mountInfiniteScroll }; /** * Two switches of RuleDesk → Page that are styles and nothing else: * * - "Sidebar on the right": the tag sidebar of Posts and of a post page goes * to the right of the content; * - "Motion": thumbnails lift a little under the pointer, buttons change * state smoothly, menus and dialogs fade in. * * No imports but the feature type: the first is applied before the first * paint, with the rest of the layout. */ var SIDEBAR_RIGHT_FEATURE_ID = "sidebar-right"; var MOTION_FEATURE_ID = "motion"; var MOTION_BODY_CLASS = featureBodyClass(MOTION_FEATURE_ID); var SIDEBAR_RIGHT_BODY = `body.${featureBodyClass(SIDEBAR_RIGHT_FEATURE_ID)}`; var MOTION_BODY = `body.${MOTION_BODY_CLASS}`; /** How long a control takes to change state. */ var MOTION_FAST = "120ms"; /** How long a thumbnail takes to lift, a menu to appear. */ var MOTION_BASE = "160ms"; var MOTION_EASE = "cubic-bezier(0.2, 0, 0, 1)"; var LIFT = "translateY(-2px)"; /** * The site lays `div#post-list` and `div#post-view` out as a flex row with * the sidebar first; `order` moves it without touching the page. */ var SIDEBAR_RIGHT_CSS = ` ${SIDEBAR_RIGHT_BODY} div#post-list > div.sidebar, ${SIDEBAR_RIGHT_BODY} div#post-view > div.sidebar { order: 2; margin-right: 0 !important; margin-left: 1em; } ${SIDEBAR_RIGHT_BODY} div#post-list > div.content { flex: 1 1 auto; min-width: 0; } `.trim(); /** The controls of the script's kit that change state under the pointer. */ var KIT_CONTROLS = [ ".rdw-btn", ".rdw-icon-btn", ".rdw-seg__btn", ".rdw-chip", ".rdw-field__input", ".rdw-switch__track", ".rdw-switch__thumb" ]; function transitionRule(scope) { return `${KIT_CONTROLS.map((control) => `${scope} ${control}`).join(",\n")} { transition: background-color ${MOTION_FAST} ${MOTION_EASE}, border-color ${MOTION_FAST} ${MOTION_EASE}, color ${MOTION_FAST} ${MOTION_EASE}, opacity ${MOTION_FAST} ${MOTION_EASE}, transform ${MOTION_FAST} ${MOTION_EASE}; } ${scope} .rdw-btn:active, ${scope} .rdw-icon-btn:active { transform: scale(0.97); }`; } var APPEAR_KEYFRAMES = ` @keyframes rdw-appear { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } } @keyframes rdw-fade { from { opacity: 0; } to { opacity: 1; } }`.trim(); function appearRule(scope) { return `${scope} .rdw-popover { animation: rdw-appear ${MOTION_BASE} ${MOTION_EASE}; } ${scope} .rdw-dialog-backdrop { animation: rdw-fade ${MOTION_BASE} ${MOTION_EASE}; }`; } /** * Everything is inside `prefers-reduced-motion: no-preference`: someone who * asked their system for less motion gets none, whatever the switch says. */ var MOTION_CSS = ` @media (prefers-reduced-motion: no-preference) { ${APPEAR_KEYFRAMES} ${MOTION_BODY} span.thumb img { transition: transform ${MOTION_BASE} ${MOTION_EASE}, opacity ${MOTION_FAST} ${MOTION_EASE}; } /* Not a video thumb: its hover preview is laid over the picture by measured position, and a picture that moves would slip from under it. */ ${MOTION_BODY} span.thumb:not(.rdw-video-thumb):hover img:not(.webm-thumb) { transform: ${LIFT}; } ${MOTION_BODY} div#header ul#navbar li a, ${MOTION_BODY} div#header ul#navbar li button { transition: color ${MOTION_FAST} ${MOTION_EASE}, box-shadow ${MOTION_FAST} ${MOTION_EASE}; } ${transitionRule(MOTION_BODY)} ${appearRule(MOTION_BODY)} } `.trim(); /** * The same for the script's own pages. They live in a shadow root, where a * class on is reached only through `:host-context`. */ var MOTION_PAGE_CSS = exports("av",` @media (prefers-reduced-motion: no-preference) { ${APPEAR_KEYFRAMES} ${transitionRule(`:host-context(${MOTION_BODY})`)} ${appearRule(`:host-context(${MOTION_BODY})`)} } `.trim()); var sidebarRightFeature = { id: SIDEBAR_RIGHT_FEATURE_ID, label: "Sidebar on the right", pages: ["list", "post"], defaultEnabled: false, cssOnly: true, css: SIDEBAR_RIGHT_CSS, mount: () => void 0 }; var motionFeature = { id: MOTION_FEATURE_ID, label: "Motion", pages: [ "list", "post", "favorites", "other" ], defaultEnabled: true, cssOnly: true, settingsCaption: "Thumbnails lift under the pointer; buttons, menus and dialogs change smoothly.", css: MOTION_CSS, mount: () => void 0 }; var FEATURE_ID$8 = "menu-cleanup"; var FEATURE_LABEL$9 = "Clean header menu"; var CONTENT_ID$1 = "content"; var HIDDEN_CLASS = "rdw-menu-hidden"; var BODY_FEATURE_CLASS$1 = featureBodyClass(FEATURE_ID$8); var MISSING_MENU_WARN = "Header menu not found"; var HIDE_LINK_TEXT_SET = /* @__PURE__ */ new Set([ "iCame Top 100", "Discord", "X", "Other Sites", "Contact Us", "DMCA", "About", "TOS", "My Favorites" ]); var FEATURE_PAGES$7 = [ "list", "post", "favorites", "other" ]; var FEATURE_CSS$8 = `body.${BODY_FEATURE_CLASS$1} li.${HIDDEN_CLASS} { display:none !important; }`; function isHeaderMenuLink(anchor, content) { const listItem = anchor.closest("li"); if (listItem === null) return false; if (content !== null && content.contains(listItem)) return false; return true; } function collectHeaderMenuLinks() { const content = document.getElementById(CONTENT_ID$1); const anchors = document.querySelectorAll("a"); const headerLinks = []; for (const node of anchors) { if (!(node instanceof HTMLAnchorElement)) continue; if (!isHeaderMenuLink(node, content)) continue; headerLinks.push(node); } return headerLinks; } function mountMenuCleanup(_ctx) { const headerLinks = collectHeaderMenuLinks(); if (headerLinks.length === 0) { log.warn(MISSING_MENU_WARN); return; } for (const anchor of headerLinks) { const text = anchor.textContent?.trim() ?? ""; if (!HIDE_LINK_TEXT_SET.has(text)) continue; const listItem = anchor.closest("li"); if (listItem === null) continue; listItem.classList.add(HIDDEN_CLASS); } } var menuCleanupFeature = { id: FEATURE_ID$8, label: FEATURE_LABEL$9, pages: [...FEATURE_PAGES$7], defaultEnabled: true, cssOnly: true, css: FEATURE_CSS$8, mount: mountMenuCleanup }; var FEATURE_ID$7 = "playlist-bar"; var FEATURE_LABEL$8 = "Collection header"; var FEATURE_PAGES$6 = ["list"]; var ROOT_ID$1 = "rdw-playlist-bar"; var ROOT_CLASS$1 = "rdw-playlist-bar"; var TITLE_CLASS$1 = "rdw-playlist-bar-title"; var NAME_CLASS = "rdw-playlist-bar-name"; var BACK_CLASS = "rdw-playlist-bar-back"; var KIND_CLASS = "rdw-playlist-bar-kind"; var TEXT_BACK = "← Collections"; var TEXT_KIND = "Saved search"; var COUNT_CLASS = "rdw-playlist-bar-count"; var PARTS_CLASS = "rdw-playlist-bar-parts"; var PART_LABEL_CLASS = "rdw-playlist-bar-part-label"; var PART_LINK_CLASS = "rdw-playlist-bar-part-link"; var CAPTION_CLASS = "rdw-playlist-bar-caption"; var DYNAMIC_ROOT_ID = "rdw-dynamic-collection-bar"; var ACTIONS_CLASS = "rdw-dynamic-collection-actions"; var TEXT_POSTS_SUFFIX = " posts"; var TEXT_PART_PREFIX = "Part "; var TEXT_PART_OF = " of "; var TEXT_CAPTION = "Posts are ordered by the site (newest first)."; var TEXT_PREV = "Previous"; var TEXT_NEXT = "Next"; var TEXT_SHUFFLE = "Shuffle"; var TEXT_ORIGINAL_ORDER = "Original order"; var TEXT_EDIT_QUERY = "Edit query"; var TEXT_QUERY_LABEL = "Query"; var DIALOG_NONE = "none"; var DIALOG_EDIT_QUERY = "edit-query"; var DIALOG_RENAME = "rename"; var DIALOG_DELETE = "delete"; var DIALOG_VARIANT_FIELDS = "fields"; var DIALOG_VARIANT_CONFIRM = "confirm"; var DIALOG_TONE_DANGER = "danger"; var DIALOG_ONLY_NAME = "name"; var DIALOG_ONLY_QUERY = "query"; var BAR_BUTTON_VARIANT = "secondary"; var BAR_DELETE_VARIANT = "danger-quiet"; var BAR_BUTTON_SIZE = "s"; /** Same heading size and button gap as the custom collection page. */ var NAME_FONT_PX = 18; var ACTIONS_GAP_PX = 8; var WARN_MISSING_HOST = "playlist-bar: image-list not found; playlist bar not mounted"; var BODY_CLASS$5 = featureBodyClass(FEATURE_ID$7); var FEATURE_CSS$7 = ` body.${BODY_CLASS$5} .${ROOT_CLASS$1} { display: flex; flex-direction: column; gap: 0.35rem; max-width: 100%; margin: 0.5rem 0; color: var(--rdw-text); box-sizing: border-box; } body.${BODY_CLASS$5} .${TITLE_CLASS$1} { display: flex; flex-wrap: wrap; align-items: baseline; gap: 0.35rem 0.75rem; max-width: 100%; font: inherit; line-height: 1.3; } body.${BODY_CLASS$5} .${BACK_CLASS} { color: var(--rdw-muted); font-size: 12px; text-decoration: none; } body.${BODY_CLASS$5} .${BACK_CLASS}:hover { color: var(--rdw-text); } body.${BODY_CLASS$5} .${KIND_CLASS} { color: var(--rdw-muted); font-size: 12px; } body.${BODY_CLASS$5} .${NAME_CLASS} { font-size: ${String(NAME_FONT_PX)}px; font-weight: 700; } body.${BODY_CLASS$5} .${COUNT_CLASS} { opacity: 0.85; } body.${BODY_CLASS$5} .${PARTS_CLASS} { display: flex; flex-wrap: wrap; align-items: center; gap: 0.35rem 0.75rem; max-width: 100%; font: inherit; line-height: 1.3; } body.${BODY_CLASS$5} .${PART_LABEL_CLASS} { flex: 0 0 auto; } body.${BODY_CLASS$5} a.${PART_LINK_CLASS} { color: inherit; text-decoration: underline; } body.${BODY_CLASS$5} a.${PART_LINK_CLASS}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } body.${BODY_CLASS$5} .${CAPTION_CLASS} { margin: 0; font: inherit; font-size: 0.875rem; line-height: 1.35; opacity: 0.8; } body.${BODY_CLASS$5} .${ACTIONS_CLASS} { display: flex; flex-wrap: wrap; align-items: center; gap: ${String(ACTIONS_GAP_PX)}px; max-width: 100%; } `.trim(); function readTagsParam(search) { return new URLSearchParams(search).get("tags") ?? ""; } function idsEqualAsSet(left, right) { if (left.length !== right.length) return false; const set = new Set(left); if (set.size !== left.length) return false; for (const id of right) if (!set.has(id)) return false; return true; } function containsAllIds(postIds, queryIds) { const set = new Set(postIds); for (const id of queryIds) if (!set.has(id)) return false; return true; } function findPlaylistMatch(queryIds) { const chunkSize = getPlaylistChunkSize(); const candidates = []; for (const playlist of listPlaylists()) { const postIds = playlist.postIds ?? []; if (!containsAllIds(postIds, queryIds)) continue; const partQueries = buildPlaylistQueries(postIds, chunkSize); let partIndex = -1; for (let index = 0; index < partQueries.length; index += 1) { const chunkQuery = partQueries[index]; if (chunkQuery === void 0) continue; const chunkIds = parsePlaylistQuery(chunkQuery); if (chunkIds !== null && idsEqualAsSet(queryIds, chunkIds)) { partIndex = index; break; } } candidates.push({ playlist, partIndex, partQueries }); } if (candidates.length === 0) return null; return candidates.find((entry) => entry.partIndex >= 0) ?? candidates[0] ?? null; } function buildPlaylistSearchUrl(query) { return buildSearchUrl(parseTags(query)); } function removeExistingBar(root) { const existing = root instanceof Document ? root.getElementById(ROOT_ID$1) : root.querySelector(`#${ROOT_ID$1}`); if (existing !== null) existing.remove(); } function findImageList(root) { return root.querySelector(SITE_SELECTORS.imageList); } function findFallbackHost(root) { return root.querySelector(SITE_SELECTORS.postListContent) ?? root.querySelector(SITE_SELECTORS.contentRoot); } function insertBar(host, bar, before) { if (before !== null && before.parentElement === host) { host.insertBefore(bar, before); return; } if (before !== null) { before.parentElement?.insertBefore(bar, before); return; } host.insertBefore(bar, host.firstChild); } function formatPostCount(count) { return `${String(count)}${TEXT_POSTS_SUFFIX}`; } function formatPartLabel(partIndex, total) { return `${TEXT_PART_PREFIX}${String(partIndex + 1)}${TEXT_PART_OF}${String(total)}`; } function appendNeighborLink(parent, label, query) { if (query === void 0) return; const link = document.createElement("a"); link.className = PART_LINK_CLASS; link.href = buildPlaylistSearchUrl(query); link.textContent = label; parent.append(link); } function buildPartsRow(match) { const { partIndex, partQueries } = match; if (partQueries.length === 0 || partIndex < 0) return null; const row = document.createElement("div"); row.className = PARTS_CLASS; const label = document.createElement("span"); label.className = PART_LABEL_CLASS; label.textContent = formatPartLabel(partIndex, partQueries.length); row.append(label); if (partQueries.length > 1) { appendNeighborLink(row, TEXT_PREV, partQueries[partIndex - 1]); appendNeighborLink(row, TEXT_NEXT, partQueries[partIndex + 1]); } return row; } function createBar(match) { const bar = document.createElement("div"); bar.id = ROOT_ID$1; bar.className = ROOT_CLASS$1; const title = document.createElement("div"); title.className = TITLE_CLASS$1; const name = document.createElement("span"); name.className = NAME_CLASS; name.textContent = match.playlist.name; const count = document.createElement("span"); count.className = COUNT_CLASS; count.textContent = formatPostCount(match.playlist.postIds?.length ?? 0); title.append(name, count); bar.append(title); const parts = buildPartsRow(match); if (parts !== null) bar.append(parts); const caption = document.createElement("p"); caption.className = CAPTION_CLASS; caption.textContent = TEXT_CAPTION; bar.append(caption); return bar; } function placeBar(bar) { const imageList = findImageList(document); if (imageList !== null) { const host = imageList.parentElement; if (host === null) { log.warn(WARN_MISSING_HOST); return false; } insertBar(host, bar, imageList); return true; } const fallback = findFallbackHost(document); if (fallback === null) { log.warn(WARN_MISSING_HOST); return false; } log.warn(WARN_MISSING_HOST); insertBar(fallback, bar, null); return true; } function storedDynamicQuery(collection) { if (collection.query !== void 0) return collection.query; return serialize(collection.tags); } /** The saved search this results page shows, for remembering its cover. */ function findDynamicCollection(tagsParam) { if (isUnfilteredQuery(tagsParam)) return null; for (const collection of load$1().collections) { if (isPlaylist(collection)) continue; const stored = storedDynamicQuery(collection); if (isUnfilteredQuery(stored)) continue; if (queriesMatchIgnoringSortRandom(tagsParam, stored)) return collection; } return null; } /** * The dynamic collection this page was opened for: the address carries its * mark (`#rdw-dc=`, set by the collection's card) and the page shows its * query. An ordinary search that happens to equal a saved one has no mark. */ function findOpenedCollection(tagsParam) { const markedId = readDynamicCollectionMark(window.location.hash); if (markedId === null) return null; for (const collection of load$1().collections) { if (collection.id !== markedId || isPlaylist(collection)) continue; const stored = storedDynamicQuery(collection); if (isUnfilteredQuery(stored)) return isUnfilteredQuery(tagsParam) ? collection : null; return queriesMatchIgnoringSortRandom(tagsParam, stored) ? collection : null; } return null; } var HASH_MARK = "#"; /** Other result pages of an opened collection keep its mark, and so its bar. */ function keepMarkOnPager(collectionId) { const mark = dynamicCollectionMarkHash(collectionId); for (const link of document.querySelectorAll(SITE_SELECTORS.paginationPageLink)) { const href = link.getAttribute("href"); if (href === null || href.includes(HASH_MARK)) continue; link.setAttribute("href", `${href}${mark}`); } } function removeDynamicBar(root) { const existing = root instanceof Document ? root.getElementById(DYNAMIC_ROOT_ID) : root.querySelector(`#${DYNAMIC_ROOT_ID}`); if (!(existing instanceof HTMLElement)) return; Q$1(null, existing); existing.remove(); } function deleteConfirmMessage(collectionName) { return `${UI_TEXT.confirmDelete} (${collectionName})`; } /** Opens another search of the same collection, keeping its mark. */ function navigateToQuery(query, collectionId) { window.location.assign(`${buildSearchUrl(parseTags(query))}${dynamicCollectionMarkHash(collectionId)}`); } function DynamicCollectionBar(props) { const [name, setName] = d(props.initialName); const [query, setQuery] = d(props.storedQuery); const [dialog, setDialog] = d(DIALOG_NONE); const [fields, setFields] = d({ name: props.initialName, query: props.storedQuery }); const shuffled = queryHasSortRandom(props.pageQuery); function closeDialog() { setDialog(DIALOG_NONE); } function openFields(kind) { setFields({ name, query }); setDialog(kind); } function onShuffle() { if (shuffled) { window.location.reload(); return; } navigateToQuery(withSortRandom(props.pageQuery), props.collectionId); } function onOriginalOrder() { navigateToQuery(withoutSortRandom(props.pageQuery), props.collectionId); } function onEditSubmit() { if (isUnfilteredQuery(fields.query)) return; const updated = updateDynamicQuery(props.collectionId, fields.query); if (updated === null) return; const nextQuery = updated.query ?? serialize(updated.tags); setQuery(nextQuery); navigateToQuery(nextQuery, props.collectionId); } function onRenameSubmit() { const trimmedName = fields.name.trim(); if (trimmedName.length === 0) return; const renamed = renameCollection(props.collectionId, trimmedName); if (renamed === null) return; setName(renamed.name); closeDialog(); } function onConfirmDelete() { if (!deleteCollection(props.collectionId)) { closeDialog(); return; } const root = document.getElementById(DYNAMIC_ROOT_ID); if (!(root instanceof HTMLElement)) return; root.remove(); Q$1(null, root); } const fieldsOpen = dialog === DIALOG_EDIT_QUERY || dialog === DIALOG_RENAME; const fieldsTitle = dialog === DIALOG_RENAME ? UI_TEXT.rename : TEXT_EDIT_QUERY; const onFieldsSubmit = dialog === DIALOG_RENAME ? onRenameSubmit : onEditSubmit; return k$1($$1, null, k$1("div", { className: TITLE_CLASS$1 }, k$1("a", { className: BACK_CLASS, href: RDW_HASH_COLLECTIONS }, TEXT_BACK), k$1("span", { className: NAME_CLASS }, name), k$1("span", { className: KIND_CLASS }, TEXT_KIND)), k$1("div", { className: ACTIONS_CLASS }, k$1(Button, { variant: BAR_BUTTON_VARIANT, size: BAR_BUTTON_SIZE, onClick: onShuffle }, TEXT_SHUFFLE), shuffled ? k$1(Button, { variant: BAR_BUTTON_VARIANT, size: BAR_BUTTON_SIZE, onClick: onOriginalOrder }, TEXT_ORIGINAL_ORDER) : null, k$1(Button, { variant: BAR_BUTTON_VARIANT, size: BAR_BUTTON_SIZE, onClick: () => { openFields(DIALOG_EDIT_QUERY); } }, TEXT_EDIT_QUERY), k$1(Button, { variant: BAR_BUTTON_VARIANT, size: BAR_BUTTON_SIZE, onClick: () => { openFields(DIALOG_RENAME); } }, UI_TEXT.rename), k$1(Button, { variant: BAR_DELETE_VARIANT, size: BAR_BUTTON_SIZE, onClick: () => { setDialog(DIALOG_DELETE); } }, UI_TEXT.delete)), fieldsOpen ? k$1(Dialog, { variant: DIALOG_VARIANT_FIELDS, open: true, title: fieldsTitle, fields, onFieldsChange: setFields, onSubmit: onFieldsSubmit, onClose: closeDialog, submitLabel: UI_TEXT.save, cancelLabel: UI_TEXT.cancel, nameLabel: UI_TEXT.nameLabel, queryLabel: TEXT_QUERY_LABEL, only: dialog === DIALOG_RENAME ? DIALOG_ONLY_NAME : DIALOG_ONLY_QUERY, renderQueryField: (field) => k$1(QueryField, field) }) : null, dialog === DIALOG_DELETE ? k$1(Dialog, { variant: DIALOG_VARIANT_CONFIRM, open: true, title: UI_TEXT.delete, message: deleteConfirmMessage(name), confirmLabel: UI_TEXT.confirm, cancelLabel: UI_TEXT.cancel, confirmTone: DIALOG_TONE_DANGER, onConfirm: onConfirmDelete, onClose: closeDialog }) : null); } var FIRST_PAGE_PID = "0"; function isFirstResultsPage(search) { const pid = new URLSearchParams(search).get("pid"); return pid === null || pid.length === 0 || pid === FIRST_PAGE_PID; } /** * The card cover of a dynamic collection is whatever its first results page * showed last. Shuffled pages and later pages are skipped. No request is made. */ function rememberDynamicCover(collectionId, tagsParam, search) { if (isUnfilteredQuery(tagsParam) || queryHasSortRandom(tagsParam) || !isFirstResultsPage(search)) return; setDynamicCover(collectionId, readFirstThumbUrls(document, 4)); const count = readResultCount(document, tagsParam); if (count !== null) setDynamicPostCount(collectionId, count); setDynamicNewest(collectionId, readNewestPostId(document), true); } function mountDynamicBar(tagsParam, search) { const opened = findOpenedCollection(tagsParam); const shown = opened ?? findDynamicCollection(tagsParam); if (shown !== null) rememberDynamicCover(shown.id, tagsParam, search); if (opened === null) return; const collection = opened; keepMarkOnPager(collection.id); const bar = document.createElement("div"); bar.id = DYNAMIC_ROOT_ID; bar.className = ROOT_CLASS$1; if (!placeBar(bar)) return; Q$1(k$1(DynamicCollectionBar, { collectionId: collection.id, initialName: collection.name, storedQuery: storedDynamicQuery(collection), pageQuery: tagsParam }), bar); } /** * Takes the cover and post count of a just-saved search from the results page * that already shows it. No request is made. */ function rememberDynamicCoverFromPage(collectionId, search) { rememberDynamicCover(collectionId, readTagsParam(search), search); } var EVENT_HASHCHANGE$1 = "hashchange"; var hashBound = false; /** The mark the bars were last drawn for; "" for none. */ var drawnMark = ""; /** * A card of Collections is a link to the search with the collection's mark in * the hash. When the page under Collections already shows that very search * (the search was saved a moment ago, and Collections was opened over it), the * link changes nothing but the hash: the browser loads nothing, and the page * that comes back into view was drawn without the bar. So the bar is drawn * again whenever the mark in the address changes. */ function bindHashRedraw(ctx) { if (hashBound) return; hashBound = true; window.addEventListener(EVENT_HASHCHANGE$1, () => { if ((readDynamicCollectionMark(window.location.hash) ?? "") !== drawnMark) mountPlaylistBar({ ...ctx, search: window.location.search }); }); } function mountPlaylistBar(ctx) { bindHashRedraw(ctx); drawnMark = readDynamicCollectionMark(window.location.hash) ?? ""; removeExistingBar(document); removeDynamicBar(document); const tagsParam = readTagsParam(ctx.search); const queryIds = parsePlaylistQuery(tagsParam); if (queryIds !== null) { const match = findPlaylistMatch(queryIds); if (match !== null) placeBar(createBar(match)); } mountDynamicBar(tagsParam, ctx.search); } var playlistBarFeature = { id: FEATURE_ID$7, label: FEATURE_LABEL$8, settingsCaption: "A bar over the grid of an opened dynamic collection: its name, Shuffle, Edit query, Rename and Delete.", pages: [...FEATURE_PAGES$6], defaultEnabled: true, css: FEATURE_CSS$7, mount: mountPlaylistBar }; var EVENT_KEYDOWN = "keydown"; /** Where a letter is typed or belongs to what is open, not to the page. */ var TYPING_SELECTOR = [ "input", "textarea", "select", "[contenteditable]", "[role=\"dialog\"]", "[role=\"listbox\"]", "[role=\"menu\"]" ].join(", "); var OPEN_DIALOG_SELECTOR = "[role=\"dialog\"]"; var VIDEO_SELECTOR$1 = "video"; /** * True when the key is not the page's: pressed with a modifier, held down, * taken by something else, typed into a field, pressed while a dialog is open, * or pressed in a video or in the player around one, which has its own keys. */ function notForThePage(event) { if (event.defaultPrevented || event.repeat || event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return true; if (document.querySelector(OPEN_DIALOG_SELECTOR) !== null) return true; const origin = event.composedPath()[0]; if (!(origin instanceof Element)) return false; if (origin.closest(TYPING_SELECTOR) !== null) return true; if (origin === document.body || origin === document.documentElement) return false; return origin.closest(VIDEO_SELECTOR$1) !== null || origin.querySelector(VIDEO_SELECTOR$1) !== null; } /** * Runs `run` when the key with this `code` is pressed on the page. The code * is the place of the key, not its letter: "KeyF" is the same key in the * Russian layout, where it types another letter. */ function useHotkey(code, active, run) { const latest = T(run); latest.current = run; A(() => { if (!active) return; const onKeyDown = (event) => { if (event.code !== code || notForThePage(event)) return; event.preventDefault(); latest.current(); }; document.addEventListener(EVENT_KEYDOWN, onKeyDown); return () => { document.removeEventListener(EVENT_KEYDOWN, onKeyDown); }; }, [active, code]); } var CLASS_STRIP = "rdw-post-panel-collection-queue"; var CLASS_NAME = "rdw-post-panel-collection-queue-name"; var CLASS_POSITION = "rdw-post-panel-collection-queue-position"; var CLASS_NAV = "rdw-post-panel-collection-queue-nav"; var CLASS_FOCUSABLE = "rdw-kit-focusable"; var GLYPH_PREVIOUS = "‹"; var GLYPH_NEXT = "›"; var LABEL_PREVIOUS = "Previous post in collection"; var LABEL_NEXT = "Next post in collection"; var ARIA_QUEUE = "Collection queue"; var POSITION_SEPARATOR = " / "; var INDEX_NOT_FOUND = -1; var POSITION_BASE = 1; var EVENT_HASHCHANGE = "hashchange"; var EVENT_CLICK$1 = "click"; var MOUSE_BUTTON_PRIMARY = 0; var QUEUE_GAP_PX = 8; var NAME_FONT_WEIGHT = 600; var NAV_DISABLED_OPACITY = .55; var POST_VIEW_QUERY = `${SEARCH_PARAM_PAGE}=${SEARCH_PAGE}&s=${SEARCH_SECTION_VIEW}`; var QUEUE_CSS = ` ${KIT_FOCUS_CSS} .${CLASS_STRIP} { display: flex; align-items: center; gap: ${String(QUEUE_GAP_PX)}px; min-width: 0; } .${CLASS_NAME} { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rdw-accent); font-weight: ${String(NAME_FONT_WEIGHT)}; text-decoration: none; } .${CLASS_POSITION} { flex: 0 0 auto; color: var(--rdw-muted); font-variant-numeric: tabular-nums; } a.${CLASS_NAV}, button.${CLASS_NAV} { box-sizing: border-box; flex: 0 0 auto; display: inline-grid; place-items: center; width: ${String(28)}px; height: ${String(28)}px; margin: 0; padding: 0; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); font: inherit; line-height: 1; text-decoration: none; cursor: pointer; } button.${CLASS_NAV}:disabled { opacity: ${String(NAV_DISABLED_OPACITY)}; cursor: not-allowed; } `; function readCollectionQueueId(hash) { if (!hash.startsWith("#rdw-c=")) return null; const raw = hash.slice(RDW_COLLECTION_QUEUE_HASH_PREFIX.length).trim(); if (raw.length === 0) return null; try { return decodeURIComponent(raw); } catch { return raw; } } function readLocationHash() { return window.location.hash; } function collectionName(collectionId) { for (const playlist of listPlaylists()) if (playlist.id === collectionId) return playlist.name; return null; } function indexOfPost(order, postId) { for (let index = 0; index < order.length; index += 1) if (order[index] === postId) return index; return INDEX_NOT_FOUND; } function neighborPostHref(postId, queueHash) { return `${SEARCH_PATH}?${POST_VIEW_QUERY}&id=${String(postId)}${queueHash}`; } function hrefAt(order, index, queueHash) { if (index < 0 || index >= order.length) return null; const postId = order[index]; if (postId === void 0) return null; return neighborPostHref(postId, queueHash); } function readQueue(postId, hash) { if (postId === null) return null; const collectionId = readCollectionQueueId(hash); if (collectionId === null) return null; const order = getCollectionOrder(collectionId); if (order === null) return null; const index = indexOfPost(order, postId); if (index === INDEX_NOT_FOUND) return null; const name = collectionName(collectionId); if (name === null) return null; const position = index + POSITION_BASE; return { name, collectionHref: collectionDetailHash(collectionId), positionLabel: `${String(position)}${POSITION_SEPARATOR}${String(order.length)}`, previousHref: hrefAt(order, index - 1, hash), nextHref: hrefAt(order, index + 1, hash) }; } /** * Steps inside a collection replace the history entry, so the browser Back * button returns to the collection page instead of the previous post. */ function goToQueuePost(href) { window.location.replace(href); } function QueueStep(props) { const className = `${CLASS_NAV} ${CLASS_FOCUSABLE}`; if (props.href === null) return /* @__PURE__ */ a("button", { type: "button", className, disabled: true, "aria-label": props.label, title: props.label, children: props.glyph }); const href = props.href; return /* @__PURE__ */ a("a", { className, href, "aria-label": props.label, title: props.label, onClick: (event) => { if (!isPlainPrimaryClick(event)) return; event.preventDefault(); goToQueuePost(href); }, children: props.glyph }); } function isPlainPrimaryClick(event) { return event.button === MOUSE_BUTTON_PRIMARY && !event.metaKey && !event.ctrlKey && !event.shiftKey && !event.altKey; } function clickedSiteStep(event, steps) { const target = event.target; if (!(target instanceof Element)) return null; for (const step of steps) if (target.closest(step.selector) !== null) return step; return null; } /** * While a post is open from a collection, the site's own "< previous / next >" * links step through the collection instead of the last search. The click is * taken in the capture phase so the site handler never runs; at either end of * the collection the click does nothing. The links themselves are not changed. */ function useSiteStepLinks(previousHref, nextHref, active) { A(() => { if (!active) return; const steps = [{ selector: SITE_SELECTORS.postPrevSearchLink, href: previousHref }, { selector: SITE_SELECTORS.postNextSearchLink, href: nextHref }]; const onClick = (event) => { if (!isPlainPrimaryClick(event)) return; const step = clickedSiteStep(event, steps); if (step === null) return; event.preventDefault(); event.stopImmediatePropagation(); if (step.href !== null) goToQueuePost(step.href); }; document.addEventListener(EVENT_CLICK$1, onClick, true); return () => { document.removeEventListener(EVENT_CLICK$1, onClick, true); }; }, [ previousHref, nextHref, active ]); } function CollectionQueue(props) { const [hash, setHash] = d(readLocationHash); A(() => { const onHashChange = () => { setHash(readLocationHash()); }; window.addEventListener(EVENT_HASHCHANGE, onHashChange); return () => { window.removeEventListener(EVENT_HASHCHANGE, onHashChange); }; }, []); const queue = readQueue(props.postId, hash); useSiteStepLinks(queue === null ? null : queue.previousHref, queue === null ? null : queue.nextHref, queue !== null); if (queue === null) return null; return /* @__PURE__ */ a("nav", { className: CLASS_STRIP, "aria-label": ARIA_QUEUE, children: [ /* @__PURE__ */ a("style", { children: QUEUE_CSS }), /* @__PURE__ */ a("a", { className: `${CLASS_NAME} ${CLASS_FOCUSABLE}`, href: queue.collectionHref, children: queue.name }), /* @__PURE__ */ a("span", { className: CLASS_POSITION, children: queue.positionLabel }), /* @__PURE__ */ a(QueueStep, { label: LABEL_PREVIOUS, glyph: GLYPH_PREVIOUS, href: queue.previousHref }), /* @__PURE__ */ a(QueueStep, { label: LABEL_NEXT, glyph: GLYPH_NEXT, href: queue.nextHref }) ] }); } /** * DOM-ready scheduling helpers. Favorites sync resume lives in deferred app start * so this module stays off the favs/storage import path. */ /** * Run `callback` once the document is interactive enough for body mounts. * At document-start, waits for DOMContentLoaded; if already past that, runs now. */ function whenDomReady(callback) { if (document.readyState === "interactive" || document.readyState === "complete") { callback(); return; } document.addEventListener("DOMContentLoaded", callback, { once: true }); } /** * After first paint: rAF → zero-delay task → callback. * Use for feature mounts and heavy module work. */ function scheduleAfterFirstPaint(callback) { requestAnimationFrame(() => { setTimeout(callback, 0); }); } /** * Post-page Fluid Player tweaks: persist volume/mute/rate, and CSS/JS size * modes (Fit height / Fit width / Original). * * Does not replace the Fluid wrapper or rename its classes — only the * wrapper size via explicit width/height (overrides Fluid's intrinsic px). */ var FEATURE_ID$6 = VIDEO_PLAYER_FEATURE_ID; var FEATURE_LABEL$7 = "Video player tweaks"; var FEATURE_PAGES$5 = ["post"]; var VIDEO_ELEMENT_ID = "gelcomVideoPlayer"; var FLUID_WRAPPER_ID = "fluid_video_wrapper_gelcomVideoPlayer"; var FLUID_WRAPPER_CLASS = "fluid_video_wrapper"; var VOLUME_MIN = 0; var VOLUME_MAX = 1; var CHROME_GAP_PX = 12; var BODY_CLASS$4 = featureBodyClass(FEATURE_ID$6); var BODY_SELECTOR$2 = `body.${BODY_CLASS$4}`; var WRAPPER_SELECTOR = `#${FLUID_WRAPPER_ID}.${FLUID_WRAPPER_CLASS}`; var SIZE_LABEL_FIT_HEIGHT = "Fit height"; var SIZE_LABEL_FIT_WIDTH = "Fit width"; var SIZE_LABEL_ORIGINAL = "Original"; var SIZE_MODE_VALUES = [ VIDEO_SIZE_FIT_HEIGHT, VIDEO_SIZE_FIT_WIDTH, VIDEO_SIZE_ORIGINAL ]; /** Settings caption under the Video player tweaks switch. */ var VIDEO_PLAYER_SETTING_CAPTION = "Fit height fills under the header (may upscale). Fit width uses the media column. Original is native pixels."; var FEATURE_CSS$6 = [ `${BODY_SELECTOR$2} ${WRAPPER_SELECTOR} {`, ` box-sizing: border-box;`, `}` ].join("\n"); /** * Pure size calculator for the three Video size modes. * Fit height may upscale; Fit width always uses full column width; * Original is videoWidth × videoHeight with no scaling. */ function computeVideoPlayerSize(input) { const { mode, videoWidth, videoHeight, columnWidthPx, availableHeightPx } = input; if (videoWidth <= 0 || videoHeight <= 0 || columnWidthPx <= 0 || availableHeightPx <= 0) return { widthPx: 0, heightPx: 0 }; if (mode === "original") return { widthPx: videoWidth, heightPx: videoHeight }; if (mode === "fit-width") return sizeForColumnWidth(videoWidth, videoHeight, columnWidthPx); const widthIfFullHeight = Math.round(availableHeightPx * videoWidth / videoHeight); if (widthIfFullHeight <= columnWidthPx) return { widthPx: widthIfFullHeight, heightPx: availableHeightPx }; return sizeForColumnWidth(videoWidth, videoHeight, columnWidthPx); } function sizeForColumnWidth(videoWidth, videoHeight, columnWidthPx) { return { widthPx: columnWidthPx, heightPx: Math.round(columnWidthPx * videoHeight / videoWidth) }; } function clampVolume(value) { if (!Number.isFinite(value)) return VOLUME_MIN; return Math.min(VOLUME_MAX, Math.max(VOLUME_MIN, value)); } function readStoredState(ctx) { return ctx.getState(parseVideoPlayerState); } function writeStoredState(ctx, state) { ctx.setState({ volume: state.volume, muted: state.muted, playbackRate: state.playbackRate }); } function findVideo() { const node = document.getElementById(VIDEO_ELEMENT_ID); return node instanceof HTMLVideoElement ? node : null; } function findWrapper() { const node = document.getElementById(FLUID_WRAPPER_ID); if (!(node instanceof HTMLElement)) return null; if (!node.classList.contains("fluid_video_wrapper")) return null; return node; } function readSizeModeFromBody() { for (const value of SIZE_MODE_VALUES) if (document.body.classList.contains(featureChoiceBodyClass(FEATURE_ID$6, value))) return value; return resolveVideoSize(DEFAULT_VIDEO_SIZE); } function measureMediaColumnWidthPx(wrapper) { const parent = wrapper.parentElement; if (parent !== null && parent.clientWidth > 0) return parent.clientWidth; return wrapper.clientWidth; } function measureAvailableHeightPx() { const chromeOffsetPx = measureHeaderOffsetPx(CHROME_GAP_PX); return Math.max(0, window.innerHeight - chromeOffsetPx); } function clearWrapperSize(wrapper) { wrapper.style.removeProperty("width"); wrapper.style.removeProperty("height"); } function applyWrapperSize(wrapper, video) { if (!document.body.classList.contains(BODY_CLASS$4)) { clearWrapperSize(wrapper); return; } const videoWidth = video.videoWidth; const videoHeight = video.videoHeight; if (videoWidth <= 0 || videoHeight <= 0) return; const size = computeVideoPlayerSize({ mode: readSizeModeFromBody(), videoWidth, videoHeight, columnWidthPx: measureMediaColumnWidthPx(wrapper), availableHeightPx: measureAvailableHeightPx() }); if (size.widthPx <= 0 || size.heightPx <= 0) return; wrapper.style.width = `${String(size.widthPx)}px`; wrapper.style.height = `${String(size.heightPx)}px`; } /** * Apply persisted volume/mute/rate. Fluid's own volume UI may not mirror * programmatic `video.volume` / `video.muted` — see LIVE-CHECK note. */ function applyPersistedPlayback(video, state) { const volume = state.volume ?? VOLUME_MAX; const muted = state.muted ?? false; const playbackRate = state.playbackRate ?? 1; video.volume = clampVolume(volume); video.muted = muted; video.playbackRate = playbackRate; } function persistFromVideo(ctx, video) { writeStoredState(ctx, { volume: clampVolume(video.volume), muted: video.muted, playbackRate: video.playbackRate }); } function bindPlayer(ctx, video) { const wrapper = findWrapper(); const state = readStoredState(ctx); const applyLayout = () => { if (wrapper !== null) applyWrapperSize(wrapper, video); }; const onLoadedMetadata = () => { applyPersistedPlayback(video, readStoredState(ctx)); applyLayout(); }; if (video.readyState >= HTMLMediaElement.HAVE_METADATA) { applyPersistedPlayback(video, state); applyLayout(); } video.addEventListener("loadedmetadata", onLoadedMetadata); video.addEventListener("volumechange", () => { persistFromVideo(ctx, video); }); video.addEventListener("ratechange", () => { persistFromVideo(ctx, video); }); const onResize = () => { applyLayout(); }; window.addEventListener("resize", onResize); new MutationObserver(() => { applyLayout(); }).observe(document.body, { attributes: true, attributeFilter: ["class"] }); } /** * A click on the picture of the player plays and pauses, every time. The * site's player does that only through its own play mark, which is gone once * playback has started. The controls keep their own clicks: only a click that * lands on the video itself is taken. */ function bindClickToToggle(video) { video.addEventListener("click", (event) => { if (!document.body.classList.contains(BODY_CLASS$4) || event.button !== 0) return; event.preventDefault(); event.stopImmediatePropagation(); if (video.paused) video.play().catch(() => void 0); else video.pause(); }, true); } function mountVideoPlayer(ctx) { scheduleAfterFirstPaint(() => { const video = findVideo(); if (video === null) return; bindPlayer(ctx, video); bindClickToToggle(video); }); } var videoPlayerFeature = { id: FEATURE_ID$6, label: FEATURE_LABEL$7, pages: [...FEATURE_PAGES$5], defaultEnabled: true, cssOnly: true, settingsCaption: VIDEO_PLAYER_SETTING_CAPTION, choice: { label: "Video size", options: [ { value: VIDEO_SIZE_FIT_HEIGHT, label: SIZE_LABEL_FIT_HEIGHT }, { value: VIDEO_SIZE_FIT_WIDTH, label: SIZE_LABEL_FIT_WIDTH }, { value: VIDEO_SIZE_ORIGINAL, label: SIZE_LABEL_ORIGINAL } ], defaultValue: DEFAULT_VIDEO_SIZE }, css: FEATURE_CSS$6, mount: mountVideoPlayer }; var TEXT_COLLECTIONS = "Collections"; var ARIA_COLLECTIONS = "Custom collections"; var SINGLE = 1; /** "In 1 collection", "In 3 collections": the button of a post that some collections hold. */ function collectionsHeldLabel(count) { return `In ${String(count)} ${count === SINGLE ? "collection" : "collections"}`; } var TRIGGER_ICON_PX = 14; var VIDEO_SOURCE_SELECTOR = "source"; var POST_ANCHOR_ID_PREFIX = "p"; var CLASS_WRAP$1 = "rdw-post-panel-collections"; var CLASS_TRIGGER = "rdw-post-panel-collections-btn"; function readAttributeSrc(element) { if (!(element instanceof HTMLSourceElement)) { const current = element.currentSrc.trim(); if (current.length > 0) return current; } const attribute = element.getAttribute("src"); if (attribute === null) return null; const trimmed = attribute.trim(); if (trimmed.length === 0) return null; return trimmed; } function postAnchorElement(postId) { const anchor = document.getElementById(`${POST_ANCHOR_ID_PREFIX}${String(postId)}`); return anchor instanceof Element ? anchor : null; } function isInsidePostAnchor(node, postId) { const anchor = postAnchorElement(postId); return anchor !== null && anchor.contains(node); } function readVideoElementUrl(video) { const source = video.querySelector(VIDEO_SOURCE_SELECTOR); if (source instanceof HTMLSourceElement) { const sourceUrl = readAttributeSrc(source); if (sourceUrl !== null) return sourceUrl; } return readAttributeSrc(video); } function readVideoMediaUrl(postId) { const candidates = []; const byId = document.getElementById(VIDEO_ELEMENT_ID); if (byId instanceof HTMLVideoElement) candidates.push(byId); for (const node of document.querySelectorAll("video")) if (node instanceof HTMLVideoElement && node !== byId) candidates.push(node); for (const video of candidates) { if (isInsidePostAnchor(video, postId)) continue; const url = readVideoElementUrl(video); if (url !== null) return url; } return null; } function thumbFromMedia(mediaUrl, postId) { if (mediaUrl === null) return null; return deriveThumbUrlFromMedia(mediaUrl, postId); } /** Post-page thumb from img#image, otherwise the video source. Null when neither yields one. */ function readPostPageThumbUrl(postId) { const image = document.getElementById(IMAGE_ID); if (image instanceof HTMLImageElement && !isInsidePostAnchor(image, postId)) { const fromImage = thumbFromMedia(readAttributeSrc(image), postId); if (fromImage !== null) return fromImage; } return thumbFromMedia(readVideoMediaUrl(postId), postId); } function CollectionsMenu(props) { const [open, setOpen] = d(false); const triggerRef = T(null); const [held, setHeld] = d(() => playlistsContaining(props.postId).length); const close = b(() => { setOpen(false); setHeld(playlistsContaining(props.postId).length); }, [props.postId]); const bindTrigger = b((node) => { const button = node?.querySelector("button"); triggerRef.current = button instanceof HTMLButtonElement ? button : null; }, []); const postId = props.postId; const readThumbUrl = b(() => readPostPageThumbUrl(postId), [postId]); return /* @__PURE__ */ a("div", { className: CLASS_WRAP$1, ref: bindTrigger, children: [/* @__PURE__ */ a(Button, { variant: "secondary", size: "m", className: CLASS_TRIGGER, pressed: held > 0, "aria-label": held > 0 ? collectionsHeldLabel(held) : TEXT_COLLECTIONS, onClick: () => { if (open) close(); else setOpen(true); }, children: [held > 0 ? /* @__PURE__ */ a(IconCheck, { size: TRIGGER_ICON_PX }) : /* @__PURE__ */ a(IconPlus, { size: TRIGGER_ICON_PX }), held > 0 ? collectionsHeldLabel(held) : TEXT_COLLECTIONS] }), /* @__PURE__ */ a(Popover, { open, onClose: close, anchorRef: triggerRef, widthPx: 260, "aria-label": ARIA_COLLECTIONS, children: /* @__PURE__ */ a(CollectionPicker, { postId, readThumbUrl }) })] }); } /** * Saves the original file of the open post. Its address is already in the * page (the player's source, the site's "Original image" link, the picture * itself), so this needs neither the API nor a key, and asks the site for * nothing but the file. */ var DOWNLOAD_ONE_CLASS = "rdw-post-panel-download"; var VIDEO_SELECTOR = "video#gelcomVideoPlayer"; var LABEL_IDLE = "Download the original file"; var LABEL_BUSY = "Downloading…"; var LABEL_DONE = "Saved to your downloads folder"; var LABEL_FAILED = "Could not download. Press to try again"; var ICON_SIZE$2 = 16; var LABELS = { idle: LABEL_IDLE, busy: LABEL_BUSY, done: LABEL_DONE, failed: LABEL_FAILED }; function videoSource(root) { const video = root.querySelector(VIDEO_SELECTOR); if (!(video instanceof HTMLVideoElement)) return ""; const source = video.querySelector("source"); return video.currentSrc || video.src || (source instanceof HTMLSourceElement ? source.src : ""); } /** * The address of the post's file: the first of the candidates that ends like * a picture or a video. A video post is taken from its player; the "Original * image" link is next; the picture on the page is the last resort. An address * that is a page, not a file, is never downloaded: it would save as HTML. */ function resolvePostFileUrl(originalHref, root = document) { const image = root.querySelector(`img#${IMAGE_ID}`); return [ videoSource(root), originalHref ?? "", image instanceof HTMLImageElement ? image.currentSrc || image.src : "" ].find((url) => url.length > 0 && isMediaFileUrl(url)) ?? null; } function DownloadOne(props) { const [phase, setPhase] = d("idle"); if (!canDownload() || resolvePostFileUrl(props.originalHref) === null) return null; const label = LABELS[phase]; return /* @__PURE__ */ a("button", { type: "button", className: `${props.className} ${DOWNLOAD_ONE_CLASS} rdw-kit-focusable`, "aria-label": label, title: label, "aria-busy": phase === "busy" ? true : void 0, disabled: phase === "busy", "data-phase": phase, onClick: () => { const url = resolvePostFileUrl(props.originalHref); if (url === null) { setPhase("failed"); return; } setPhase("busy"); downloadFile(url, buildFileName(readFileMask(), { ...props.info, url })).then(() => { setPhase("done"); }).catch((error) => { log.warn("post-panel: download failed", props.info.postId, error); setPhase("failed"); }); }, children: phase === "done" ? /* @__PURE__ */ a(IconCheck, { size: ICON_SIZE$2 }) : /* @__PURE__ */ a(IconDownload, { size: ICON_SIZE$2 }) }); } var DISPLAY_EDIT = "Edit"; var DISPLAY_RESIZE = "Resize image"; var DISPLAY_REPORT = "Report to moderation"; var DISPLAY_ADD_NOTE = "Add note"; var CLASS_WRAP = "rdw-post-panel-post-actions"; var CLASS_ITEM = "rdw-post-panel-post-action"; var ICON_SIZE$1 = 14; function buttonLabel(text) { if (text === "Edit") return DISPLAY_EDIT; if (text === "Resize image") return DISPLAY_RESIZE; if (text === "Report to moderation") return DISPLAY_REPORT; return DISPLAY_ADD_NOTE; } function actionIcon(text) { if (text === "Edit") return /* @__PURE__ */ a(IconPencil, { size: ICON_SIZE$1 }); if (text === "Resize image") return /* @__PURE__ */ a(IconImage, { size: ICON_SIZE$1 }); if (text === "Report to moderation") return /* @__PURE__ */ a(IconFlag, { size: ICON_SIZE$1 }); return /* @__PURE__ */ a(IconNote, { size: ICON_SIZE$1 }); } /** Full-width open buttons that proxy native link-list clicks. No Popover. */ function PostActionsList(props) { if (props.links.length === 0) return null; return /* @__PURE__ */ a("div", { className: CLASS_WRAP, children: props.links.map((link) => /* @__PURE__ */ a(Button, { variant: "secondary", size: "m", className: CLASS_ITEM, "aria-label": buttonLabel(link.text), onClick: () => { link.anchor.click(); }, children: [actionIcon(link.text), buttonLabel(link.text)] }, link.text)) }); } var POST_PANEL_TAB_INFO = "info"; var POST_PANEL_TAB_COMMENTS = "comments"; var TEXT_FAVORITE = "Favorite"; var TEXT_IN_FAVORITES = "In favorites"; var TEXT_VOTE_PREFIX = "Vote"; var TEXT_ICAME = "I came"; var TEXT_COMMENTS = "Comments"; var TEXT_INFO = "Info"; var TEXT_POST = "Post"; var TEXT_COMMENTS_COUNTED_SEP = " · "; var LABEL_ORIGINAL = "Original"; var LABEL_VOTE = "Vote"; var LABEL_ICAME = "I came"; /** * The key of the Favorite button (the designer, 18.11.2026): the place of the * letter F. The site's own keys on a post are the left and right arrows only * (docs/site.md), and the script had none on F. */ var FAVORITE_KEY_CODE = "KeyF"; var TITLE_FAVORITE = "Add to favorites (F)"; var TITLE_UNFAVORITE = "Remove from favorites (F)"; var TITLE_VOTE = "Vote up"; var TITLE_VOTED = "Voted up"; var ARIA_PANEL_TABS = "Post details"; var ICON_SIZE = 14; var ORIGINAL_ICON_SIZE = 14; var CLASS_ROOT = "rdw-post-panel"; var CLASS_CARD = "rdw-post-panel-card"; var CLASS_ACTIONS$1 = "rdw-post-panel-actions"; var CLASS_ACTIONS_ROW = "rdw-post-panel-actions-row"; var CLASS_FAV = "rdw-post-panel-fav"; var CLASS_ORIGINAL = "rdw-post-panel-original"; var CLASS_VOTE = "rdw-post-panel-vote"; var CLASS_STATS = "rdw-post-panel-stats"; var CLASS_STAT_LABEL = "rdw-post-panel-stat-label"; var CLASS_STAT_VALUE = "rdw-post-panel-stat-value"; var CLASS_SOURCE = "rdw-post-panel-source"; var CLASS_ICAME = "rdw-post-panel-icame"; var CLASS_COMMENTS = "rdw-post-panel-comments"; var CLASS_COMMENTS_HOST = "rdw-post-panel-comments-host"; var CLASS_INFO = "rdw-post-panel-info"; var CLASS_TABS = "rdw-post-panel-tabs"; var CLASS_TAB_PANEL = "rdw-post-panel-tabpanel"; function parseNumericPostId(postId) { if (postId === null || postId.length === 0) return null; const parsed = Number(postId); if (!Number.isFinite(parsed)) return null; const truncated = Math.trunc(parsed); return truncated < 0 ? null : truncated; } var SIZE_PATTERN = /^(\d+)\s*x\s*(\d+)$/i; function statValue(stats, label) { return stats.find((row) => row.label === label)?.value.trim() ?? ""; } /** What the panel knows about the post that a file name mask may use. */ function fileNameInfo(postId, stats, scoreText) { const size = SIZE_PATTERN.exec(statValue(stats, "Size")); const score = Number(scoreText); const rating = statValue(stats, "Rating").toLowerCase(); const owner = statValue(stats, "By"); return { postId, ...rating.length > 0 ? { rating } : {}, ...scoreText.trim().length > 0 && Number.isFinite(score) ? { score } : {}, ...size === null ? {} : { width: Number(size[1]), height: Number(size[2]) }, ...owner.length > 0 ? { owner } : {} }; } function voteLabel(scoreText) { return `${TEXT_VOTE_PREFIX} ${scoreText}`; } function commentsTabLabel(count) { if (count === null) return TEXT_COMMENTS; return `${TEXT_COMMENTS}${TEXT_COMMENTS_COUNTED_SEP}${String(count)}`; } function PostPanel(props) { const numericId = parseNumericPostId(props.postId); const [favorited, setFavorited] = d(() => props.postId !== null ? isFav(props.postId) : false); const [favPending, setFavPending] = d(false); const [scoreText, setScoreText] = d(() => { if (props.postId === null) return "—"; return readScoreText(props.postId) ?? "—"; }); const [votePending, setVotePending] = d(false); const [voted, setVoted] = d(false); const [cameDone, setCameDone] = d(false); const [stats] = d(() => readStatRows()); const [moreLinks] = d(() => collectMoreLinks()); const [originalHref] = d(() => { return findOriginalAnchor()?.href ?? null; }); const [iCame] = d(() => findICameTarget()); const [hasComments] = d(() => findPostComments() !== null); const [commentCount] = d(() => hasComments ? readCommentCount() : null); const [activeTab, setActiveTab] = d(() => hasComments && takeCommentsReturn() ? POST_PANEL_TAB_COMMENTS : POST_PANEL_TAB_INFO); A(() => { if (props.postId === null) return; return observeScoreSpan(props.postId, (text) => { setScoreText(text.length > 0 ? text : "—"); }); }, [props.postId]); const onFavClick = b(async () => { if (props.postId === null || favPending) return; setFavPending(true); try { if (favorited) { const result = await removeFavorite(props.postId); if (result.status === "removed") { removeFav(props.postId); setFavorited(false); return; } log.warn("post-actions: remove favorite failed", props.postId, result); return; } const result = await addFavorite(props.postId); if (result.status === "added" || result.status === "already") { addFav(props.postId); indexFavoriteFromPostPage(props.postId); setFavorited(true); if (result.status === "added" && result.score !== void 0) { writeScoreText(props.postId, result.score); setScoreText(String(result.score)); } return; } if (result.status === "not_logged_in") { log.warn("post-actions: favorite requires login", props.postId); return; } log.warn("post-actions: favorite failed", props.postId, result); } finally { setFavPending(false); } }, [ favPending, favorited, props.postId ]); useHotkey(FAVORITE_KEY_CODE, props.postId !== null, () => { onFavClick(); }); const onVoteClick = b(async () => { if (props.postId === null || votePending) return; setVotePending(true); try { const score = await voteUp(props.postId); if (score !== null) { writeScoreText(props.postId, score); setScoreText(String(score)); setVoted(true); } } finally { setVotePending(false); } }, [props.postId, votePending]); const onICameClick = b(() => { iCame?.anchor.click(); setCameDone(true); }, [iCame]); const onTabChange = b((id) => { setActiveTab(id); }, []); const tabItems = w$1(() => { const items = [{ id: POST_PANEL_TAB_INFO, label: TEXT_INFO }]; if (hasComments) items.push({ id: POST_PANEL_TAB_COMMENTS, label: commentsTabLabel(commentCount) }); return items; }, [commentCount, hasComments]); const showInfoCard = stats.length > 0 || moreLinks.length > 0 || hasComments; const showActionsRow2 = props.postId !== null || iCame !== null || originalHref !== null; return /* @__PURE__ */ a("div", { className: CLASS_ROOT, children: [ /* @__PURE__ */ a(CollectionQueue, { postId: numericId }), /* @__PURE__ */ a("div", { className: CLASS_ACTIONS$1, children: [props.postId !== null || numericId !== null ? /* @__PURE__ */ a("div", { className: CLASS_ACTIONS_ROW, children: [props.postId !== null ? /* @__PURE__ */ a(Button, { variant: favorited ? "secondary" : "primary", size: "m", className: CLASS_FAV, loading: favPending, pressed: favorited, title: favorited ? TITLE_UNFAVORITE : TITLE_FAVORITE, "aria-label": favorited ? `${UI_TEXT.cardFavRemoveLabel} ${props.postId}` : `${UI_TEXT.cardFavAddLabel} ${props.postId}`, onClick: () => { onFavClick(); }, children: [favorited ? /* @__PURE__ */ a(IconStarFilled, { size: ICON_SIZE }) : /* @__PURE__ */ a(IconStar, { size: ICON_SIZE }), favorited ? TEXT_IN_FAVORITES : TEXT_FAVORITE] }) : null, numericId !== null ? /* @__PURE__ */ a(CollectionsMenu, { postId: numericId }) : null] }) : null, showActionsRow2 ? /* @__PURE__ */ a("div", { className: CLASS_ACTIONS_ROW, children: [ props.postId !== null ? /* @__PURE__ */ a(Button, { variant: "secondary", size: "m", className: CLASS_VOTE, loading: votePending, pressed: voted, title: voted ? TITLE_VOTED : TITLE_VOTE, "aria-label": LABEL_VOTE, onClick: () => { onVoteClick(); }, children: [/* @__PURE__ */ a(IconArrowUp, { size: ICON_SIZE }), voteLabel(scoreText)] }) : null, iCame !== null ? /* @__PURE__ */ a(Button, { variant: "secondary", size: "m", className: CLASS_ICAME, pressed: cameDone, "aria-label": LABEL_ICAME, onClick: onICameClick, children: [/* @__PURE__ */ a(IconDroplet, { size: ICON_SIZE }), TEXT_ICAME] }) : null, originalHref !== null ? /* @__PURE__ */ a("a", { className: CLASS_ORIGINAL, href: originalHref, target: "_blank", rel: "noopener", "aria-label": LABEL_ORIGINAL, title: LABEL_ORIGINAL, children: /* @__PURE__ */ a(IconExternalLink, { size: ORIGINAL_ICON_SIZE }) }) : null, numericId !== null ? /* @__PURE__ */ a(DownloadOne, { originalHref, info: fileNameInfo(numericId, stats, scoreText), className: CLASS_ORIGINAL }) : null ] }) : null] }), showInfoCard ? /* @__PURE__ */ a(Card, { className: CLASS_CARD, as: "section", children: [ hasComments ? /* @__PURE__ */ a(Tabs, { className: CLASS_TABS, "aria-label": ARIA_PANEL_TABS, items: tabItems, value: activeTab, onChange: onTabChange }) : null, /* @__PURE__ */ a("div", { className: CLASS_TAB_PANEL, role: "tabpanel", id: kitTabPanelId(POST_PANEL_TAB_INFO), "aria-labelledby": kitTabId(POST_PANEL_TAB_INFO), hidden: hasComments && activeTab !== "info", children: /* @__PURE__ */ a(InfoPanel, { stats, moreLinks }) }), hasComments ? /* @__PURE__ */ a("div", { className: `${CLASS_TAB_PANEL} ${CLASS_COMMENTS}`, role: "tabpanel", id: kitTabPanelId(POST_PANEL_TAB_COMMENTS), "aria-labelledby": kitTabId(POST_PANEL_TAB_COMMENTS), hidden: activeTab !== POST_PANEL_TAB_COMMENTS, children: /* @__PURE__ */ a(CommentsHost, {}) }) : null ] }) : null ] }); } function InfoPanel(props) { return /* @__PURE__ */ a("div", { className: CLASS_INFO, children: [props.stats.length > 0 ? /* @__PURE__ */ a("div", { className: CLASS_STATS, children: props.stats.map((row) => /* @__PURE__ */ a(StatRowView, { row }, row.label)) }) : null, props.moreLinks.length > 0 ? /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a(SectionLabel, { children: TEXT_POST }), /* @__PURE__ */ a(PostActionsList, { links: props.moreLinks })] }) : null] }); } /** A comment in the site's list: `div#c{id}` (docs/site.md). */ var COMMENT_SELECTOR = "div#comment-list > div[id^=\"c\"]"; /** The site's link that shows the hidden comments; "(0 hidden)" when there are none. */ var HIDDEN_LINK_SELECTOR = "div#comment-list > a#ci"; var NO_HIDDEN_TEXT = "(0 hidden)"; var RESPOND_TEXT = "Respond"; var TEXT_NO_COMMENTS = "No comments yet"; var TEXT_WRITE_COMMENT = "Write a comment"; var CLASS_COMMENTS_EMPTY = "rdw-post-panel-comments-empty"; /** On the site's "Edit | Respond" line under the picture. */ var CLASS_REPLY_LINKS = "rdw-post-reply-links"; /** The site's link that changes the order of the comments; the page is loaded again for it. */ var SORT_LINK_SELECTOR = "div#comment-list > div:not([id]) > a"; /** Holds the address the Comments tab is to be opened on after that reload. */ var COMMENTS_RETURN_KEY = "ruledesk-web.comments-return"; function rememberCommentsReturn() { try { window.sessionStorage.setItem(COMMENTS_RETURN_KEY, window.location.search); } catch {} } /** True once, on the load that follows "Change" on this very post. */ function takeCommentsReturn() { try { const kept = window.sessionStorage.getItem(COMMENTS_RETURN_KEY); window.sessionStorage.removeItem(COMMENTS_RETURN_KEY); return kept !== null && kept === window.location.search; } catch { return false; } } /** The site's "Respond" link, which opens its form for a comment; it stands under the picture. */ function findRespondLink() { for (const link of document.querySelectorAll("a")) if (link.textContent.trim() === RESPOND_TEXT) return link; return null; } /** The site's form for a comment: `form#comment_form` in `div#right-col` (docs/site.md). */ var COMMENT_FORM_ID = "comment_form"; function CommentsHost() { const hostRef = T(null); const formOriginRef = T(null); A(() => () => { const origin = formOriginRef.current; const form = document.getElementById(COMMENT_FORM_ID); if (origin !== null && origin.parent !== null && form !== null) origin.parent.insertBefore(form, origin.next); }, []); const [empty] = d(() => { const comments = findPostComments(); return comments !== null && comments.querySelector(COMMENT_SELECTOR) === null; }); const [respond] = d(() => findRespondLink()); F(() => { const comments = findPostComments(); const hidden = comments?.querySelector(HIDDEN_LINK_SELECTOR); if (hidden instanceof HTMLElement && hidden.textContent.trim() === NO_HIDDEN_TEXT) hidden.hidden = true; const line = respond?.parentElement ?? null; if (line !== null && Array.from(line.children).every((child) => child.tagName === "A")) line.classList.add(CLASS_REPLY_LINKS); const change = comments?.querySelector(SORT_LINK_SELECTOR); change?.addEventListener("click", rememberCommentsReturn); return () => { change?.removeEventListener("click", rememberCommentsReturn); }; }, [respond]); F(() => { const host = hostRef.current; const comments = findPostComments(); if (host === null || comments === null) return; if (comments.parentElement === host) return; const originParent = comments.parentNode; const originNext = comments.nextSibling; host.append(comments); return () => { if (originParent === null) return; if (comments.parentElement === host || comments.parentNode === null) originParent.insertBefore(comments, originNext); }; }, []); const writeComment = () => { const host = hostRef.current; const form = document.getElementById(COMMENT_FORM_ID); if (host === null || respond === null) return; if (!(form instanceof HTMLFormElement)) { respond.click(); respond.scrollIntoView({ block: "center" }); return; } if (window.getComputedStyle(form).display === "none") respond.click(); if (form.parentElement !== host) { formOriginRef.current = { parent: form.parentNode, next: form.nextSibling }; host.append(form); } form.querySelector("textarea")?.focus(); }; return /* @__PURE__ */ a($$1, { children: [empty || respond !== null ? /* @__PURE__ */ a("div", { className: CLASS_COMMENTS_EMPTY, children: [/* @__PURE__ */ a("span", { children: empty ? TEXT_NO_COMMENTS : "" }), respond !== null ? /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", onClick: writeComment, children: TEXT_WRITE_COMMENT }) : null] }) : null, /* @__PURE__ */ a("div", { className: CLASS_COMMENTS_HOST, ref: hostRef })] }); } function StatRowView(props) { const { row } = props; return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("span", { className: CLASS_STAT_LABEL, children: row.label }), row.label === "Source" && row.href !== null ? /* @__PURE__ */ a("a", { className: `${CLASS_STAT_VALUE} ${CLASS_SOURCE}`, href: row.href, title: row.href, rel: SOURCE_LINK_REL, children: row.value }) : row.href !== null ? /* @__PURE__ */ a("a", { className: CLASS_STAT_VALUE, href: row.href, children: row.value }) : /* @__PURE__ */ a("div", { className: CLASS_STAT_VALUE, children: row.value })] }); } var FEATURE_ID$5 = "post-actions"; var FEATURE_LABEL$6 = "Post side panel"; var FEATURE_PAGES$4 = ["post"]; /** Body class while the panel host is in the document — CSS hide handoff for G. */ var POST_PANEL_MOUNTED_CLASS = "rdw-post-panel-mounted"; var NARROW_BREAKPOINT_PX = 1100; var NARROW_MEDIA_QUERY = `(max-width: ${String(1099)}px)`; var WIDE_MEDIA_QUERY = `(min-width: ${String(NARROW_BREAKPOINT_PX)}px)`; var PANEL_WIDTH_PX$1 = 360; var PANEL_MIN_WIDTH_PX = 320; var PANEL_MAX_WIDTH_PX = 420; var PANEL_FONT_SIZE_PX = 13; var PANEL_BUTTON_HEIGHT_PX = 34; var PANEL_BLOCK_GAP_PX = 10; var PANEL_BUTTON_GAP_PX = 8; var PANEL_CARD_PADDING_PX = 12; var PANEL_STICKY_GAP_PX = 12; var PANEL_MEDIA_GAP_PX = 12; /** * Under the header kept at the top (25, boot/sticky-header.ts) and over the * page. At the bottom of a page the block the panel is in ends, and a tall * panel is pushed up: it has to go under the header then, not over it. It * was 100, and drew over the header and over the script's dialogs (40). */ var PANEL_Z_INDEX$1 = 20; var STAT_LABEL_WIDTH_PX = 62; var ORIGINAL_BUTTON_SIZE_PX = 34; var STICKY_TOP_VAR = "--rdw-post-panel-sticky-top"; var CLASS_PANEL = "rdw-post-actions"; var CLASS_MODE_WIDE = "rdw-post-actions--wide"; var CLASS_MODE_NARROW = "rdw-post-actions--narrow"; var WARN_NO_FLEXI = "post-actions: div.flexi missing; panel not mounted"; var BODY_SELECTOR$1 = `body.${featureBodyClass(FEATURE_ID$5)}`; var FEATURE_CSS$5 = ` ${BODY_SELECTOR$1} #fit-to-screen div.flexi, ${BODY_SELECTOR$1} div#right-col div.flexi, ${BODY_SELECTOR$1} div.flexi { flex-wrap: wrap; align-items: flex-start; /* Space between the media and the panel, beside it or under it. */ gap: ${String(PANEL_MEDIA_GAP_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID}.${CLASS_PANEL} { box-sizing: border-box; width: ${String(PANEL_WIDTH_PX$1)}px; min-width: ${String(PANEL_MIN_WIDTH_PX)}px; max-width: min(${String(PANEL_MAX_WIDTH_PX)}px, 100%); flex: 0 1 ${String(PANEL_WIDTH_PX$1)}px; z-index: ${String(PANEL_Z_INDEX$1)}; font: ${String(PANEL_FONT_SIZE_PX)}px/1.35 var(--rdw-font); color: var(--rdw-text); } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID}.${CLASS_MODE_WIDE} { position: sticky; top: var(${STICKY_TOP_VAR}, ${String(PANEL_STICKY_GAP_PX)}px); align-self: flex-start; max-height: calc(100vh - var(${STICKY_TOP_VAR}, ${String(PANEL_STICKY_GAP_PX)}px) - ${String(PANEL_STICKY_GAP_PX)}px); overflow-y: auto; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID}.${CLASS_MODE_NARROW} { position: static; width: 100%; min-width: 0; max-width: 100%; flex: 1 1 100%; margin: 0.75rem 0 0; max-height: none; overflow-y: visible; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel { display: grid; gap: ${String(PANEL_BLOCK_GAP_PX)}px; position: relative; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-card { padding: ${String(PANEL_CARD_PADDING_PX)}px; display: grid; gap: ${String(PANEL_BLOCK_GAP_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-btn { min-height: ${String(PANEL_BUTTON_HEIGHT_PX)}px; font-size: ${String(PANEL_FONT_SIZE_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-actions { display: grid; gap: ${String(PANEL_BUTTON_GAP_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-actions-row { display: flex; flex-wrap: wrap; align-items: stretch; gap: ${String(PANEL_BUTTON_GAP_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-actions-row > .rdw-btn, ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-actions-row > .rdw-post-panel-collections { flex: 1 1 0; min-width: 0; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-collections { position: relative; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-collections .rdw-btn { width: 100%; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-original { box-sizing: border-box; flex: 0 0 ${String(ORIGINAL_BUTTON_SIZE_PX)}px; width: ${String(ORIGINAL_BUTTON_SIZE_PX)}px; height: ${String(ORIGINAL_BUTTON_SIZE_PX)}px; min-width: ${String(ORIGINAL_BUTTON_SIZE_PX)}px; min-height: ${String(ORIGINAL_BUTTON_SIZE_PX)}px; display: inline-grid; place-items: center; padding: 0; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-m); background: var(--rdw-surface); color: var(--rdw-text); text-decoration: none; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} button.rdw-post-panel-download { font: inherit; cursor: pointer; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} button.rdw-post-panel-download:disabled { opacity: 0.55; cursor: progress; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} button.rdw-post-panel-download[data-phase="done"] { border-color: var(--rdw-accent); color: var(--rdw-accent); } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} button.rdw-post-panel-download[data-phase="failed"] { border-color: var(--rdw-danger); color: var(--rdw-danger); } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-stats { display: grid; grid-template-columns: ${String(STAT_LABEL_WIDTH_PX)}px 1fr; column-gap: ${String(PANEL_BUTTON_GAP_PX)}px; row-gap: ${String(PANEL_BUTTON_GAP_PX)}px; font-size: ${String(PANEL_FONT_SIZE_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-stat-label { color: var(--rdw-muted); } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-source { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--rdw-accent); } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-info { display: grid; gap: ${String(PANEL_BLOCK_GAP_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-post-actions { display: grid; gap: ${String(PANEL_BUTTON_GAP_PX)}px; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-post-action { width: 100%; justify-content: flex-start; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-tabpanel[hidden] { display: none; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID} .rdw-post-panel-comments-host { min-width: 0; } @media ${NARROW_MEDIA_QUERY} { ${BODY_SELECTOR$1} #${POST_ACTIONS_ID}.${CLASS_MODE_WIDE} { position: static; max-height: none; overflow-y: visible; } } @media ${WIDE_MEDIA_QUERY} { ${BODY_SELECTOR$1} div#post-view > div#right-col { flex-grow: 1; } ${BODY_SELECTOR$1} div.flexi > :has(+ #${POST_ACTIONS_ID}.${CLASS_MODE_WIDE}) { margin-left: auto; } ${BODY_SELECTOR$1} #${POST_ACTIONS_ID}.${CLASS_MODE_WIDE} { margin-left: ${String(12)}px; margin-right: auto; } } `.trim(); var layoutCleanup = null; var panelHost = null; function removeExistingPanel() { if (layoutCleanup !== null) { layoutCleanup(); layoutCleanup = null; } if (panelHost !== null) { Q$1(null, panelHost); panelHost.remove(); panelHost = null; } const existing = document.getElementById(POST_ACTIONS_ID); if (existing !== null) existing.remove(); document.body.classList.remove(POST_PANEL_MOUNTED_CLASS); } function isNarrowViewport() { if (typeof window.matchMedia === "function") return window.matchMedia(NARROW_MEDIA_QUERY).matches; return window.innerWidth < NARROW_BREAKPOINT_PX; } function applyStickyTop(panel) { const topPx = measureHeaderOffsetPx(PANEL_STICKY_GAP_PX); panel.style.setProperty(STICKY_TOP_VAR, `${String(topPx)}px`); } function placePanel(panel, flexi) { const narrow = isNarrowViewport(); panel.classList.toggle(CLASS_MODE_WIDE, !narrow); panel.classList.toggle(CLASS_MODE_NARROW, narrow); applyStickyTop(panel); const media = findMediaWrapper(flexi, POST_ACTIONS_ID); if (media !== null) { media.after(panel); return; } flexi.append(panel); } function bindLayout(panel, flexi) { const sync = () => { placePanel(panel, flexi); }; sync(); const onResize = () => { sync(); }; window.addEventListener("resize", onResize); let mediaCleanup = null; if (typeof window.matchMedia === "function") { const media = window.matchMedia(NARROW_MEDIA_QUERY); const onChange = () => { sync(); }; if (typeof media.addEventListener === "function") { media.addEventListener("change", onChange); mediaCleanup = () => { media.removeEventListener("change", onChange); }; } else if (typeof media.addListener === "function") { media.addListener(onChange); mediaCleanup = () => { media.removeListener(onChange); }; } } layoutCleanup = () => { window.removeEventListener("resize", onResize); if (mediaCleanup !== null) mediaCleanup(); }; } function mountPostActions(ctx) { removeExistingPanel(); const flexi = findFlexi(); if (flexi === null) { log.warn(WARN_NO_FLEXI); return; } const host = document.createElement("div"); host.id = POST_ACTIONS_ID; host.className = CLASS_PANEL; host.setAttribute("role", "complementary"); host.setAttribute("aria-label", FEATURE_LABEL$6); const postId = readPostIdFromSearch(ctx.search); panelHost = host; document.body.classList.add(POST_PANEL_MOUNTED_CLASS); placePanel(host, flexi); bindLayout(host, flexi); Q$1(k$1(PostPanel, { postId }), host); } var postActionsFeature = { id: FEATURE_ID$5, label: FEATURE_LABEL$6, settingsCaption: "One panel beside the picture: Favorite, vote, download, collections and the details of the post, in place of the site's scattered links.", pages: [...FEATURE_PAGES$4], defaultEnabled: true, css: FEATURE_CSS$5, mount: mountPostActions }; /** * The height of the search panel, kept between page loads so that its place * can be reserved before the first paint and nothing jumps when it mounts. * * Plain localStorage: it is read before the first paint and must cost * nothing. This module imports nothing, so both the boot code and the * search-tools feature can use it. */ /** Panel height reserved before the panel was ever measured in this browser. */ var DEFAULT_HEIGHT_PX = 168; var HEIGHT_LIMIT_PX = 2e3; var SEARCH_TOOLS_HEIGHT_KEY = "ruledesk-web.search-tools-height"; /** * Body class that hides the site's own "Filter AI" row, which the panel * replaces with its "AI posts" switch. It is set before the first paint: * otherwise the site's row shows for a moment under the panel on every load * and the page shifts when it goes away. */ var SEARCH_TOOLS_AI_ROW_BODY_CLASS$1 = "rdw-search-tools-ai-posts"; /** On the panel root once the panel is rendered: the reserve is dropped. */ var SEARCH_TOOLS_MOUNTED_CLASS = "rdw-search-tools--mounted"; /** The height the panel had the last time it was shown, or the default. */ function readSearchToolsReserveHeight() { let raw = null; try { raw = window.localStorage.getItem(SEARCH_TOOLS_HEIGHT_KEY); } catch {} const height = raw === null ? NaN : Number(raw); if (!Number.isFinite(height) || height <= 0 || height > HEIGHT_LIMIT_PX) return DEFAULT_HEIGHT_PX; return Math.round(height); } /** Remembers the panel height for the next page load. */ function rememberSearchToolsHeight(height) { if (!Number.isFinite(height) || height <= 0) return; try { window.localStorage.setItem(SEARCH_TOOLS_HEIGHT_KEY, String(Math.round(height))); } catch {} } /** * The buttons at the foot of the search panel that act on posts, on results * pages only. "Select posts" picks posts on the page; what was picked can be * added to a custom collection and, when the download manager is available * (see {@link downloadsAvailable}), downloaded. "Download results" takes the * whole search and needs the manager too. */ var LABEL_DOWNLOAD_RESULTS = "Download results"; var TITLE_DOWNLOAD_RESULTS = "Download every post of this search"; /** One word wherever posts are picked: Posts, Feed, Favorites, Following. */ var LABEL_SELECT = "Select"; var TITLE_SELECT = "Pick posts on this page to add to a collection"; var TITLE_SELECT_WITH_DOWNLOADS = "Pick posts on this page to add to a collection or to download"; var LABEL_ADD_SELECTED = "Add to collection"; var LABEL_SELECT_PAGE = "Select page"; var SELECT_NOTE_CLASS = "rdw-select-note"; var LABEL_DOWNLOAD_SELECTED = "Download selected"; var DIALOG_TITLE = "Download results"; var CONFIRM_LABEL = "Download"; /** Names the folder only; the panel says "N selected posts" (see SELECTION_SCOPE). */ var SELECTION_LABEL_SUFFIX = " (selected)"; var SELECTION_SCOPE = "selection"; var UNNAMED_SELECTION = "selected posts"; var CONFIRM_PREFIX = "Download every post of “"; var CONFIRM_SUFFIX = "”? The list is read through the API first, then the files are saved one by one. A large search takes a long time; it can be paused or cancelled in the panel."; function pageQuery(search) { return withoutSortRandom(new URLSearchParams(search).get("tags") ?? ""); } function isResultsPage(search) { return new URLSearchParams(search).get("s") === SEARCH_SECTION; } /** The collection's name when the page was opened from its card, else the query. */ function jobLabel(query) { const markedId = readDynamicCollectionMark(window.location.hash); if (markedId !== null) { const collection = load$1().collections.find((item) => item.id === markedId); if (collection !== void 0) return collection.name; } return query; } function DownloadControls(props = {}) { const [selecting, setSelecting] = d(false); const [count, setCount] = d(0); const [confirmOpen, setConfirmOpen] = d(false); const [collectionPosts, setCollectionPosts] = d(null); const [note, setNote] = d(""); A(() => () => { stopGridSelect(); }, []); const { onSelectingChange } = props; A(() => { onSelectingChange?.(selecting); }, [onSelectingChange, selecting]); useEscape(selecting, () => { stopGridSelect(); setSelecting(false); setCount(0); }); const search = window.location.search; if (!isResultsPage(search)) return null; const canDownload = downloadsAvailable(); const query = pageQuery(search); const label = jobLabel(query); const leaveSelect = () => { stopGridSelect(); setSelecting(false); setCount(0); }; if (selecting) { const bar = /* @__PURE__ */ a(SelectionBar, { layout: "stack", count, selectAllLabel: LABEL_SELECT_PAGE, onSelectAll: selectGridPage, onClear: clearGridSelection, onCancel: leaveSelect, children: [/* @__PURE__ */ a(Button, { variant: "secondary", disabled: count === 0, onClick: () => { setCollectionPosts(readSelectedPosts(readPreviewThumbUrl)); }, children: LABEL_ADD_SELECTED }), canDownload ? /* @__PURE__ */ a(Button, { variant: "secondary", disabled: count === 0, onClick: () => { const ids = readSelectedPostIds(); leaveSelect(); if (ids.length > 0 && !isDownloadBusy()) startDownload(label.length > 0 ? `${label}${SELECTION_LABEL_SUFFIX}` : UNNAMED_SELECTION, { kind: "ids", ids }, SELECTION_SCOPE); }, children: LABEL_DOWNLOAD_SELECTED }) : null] }); const host = props.barHost ?? null; return /* @__PURE__ */ a($$1, { children: [host === null ? bar : U(bar, host), /* @__PURE__ */ a(BulkCollectionDialog, { open: collectionPosts !== null, posts: collectionPosts ?? [], onClose: () => { setCollectionPosts(null); }, onDone: (result) => { leaveSelect(); refreshAddButtons(); setNote(bulkCollectionSummary(result)); } })] }); } return /* @__PURE__ */ a($$1, { children: [ !canDownload || isUnfilteredQuery(query) ? null : /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", title: TITLE_DOWNLOAD_RESULTS, onClick: () => { setConfirmOpen(true); }, children: LABEL_DOWNLOAD_RESULTS }), /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", title: canDownload ? TITLE_SELECT_WITH_DOWNLOADS : TITLE_SELECT, onClick: () => { setNote(""); startGridSelect(setCount); setSelecting(true); }, children: LABEL_SELECT }), note.length > 0 ? /* @__PURE__ */ a("span", { className: SELECT_NOTE_CLASS, role: "status", children: note }) : null, /* @__PURE__ */ a(Dialog, { variant: "confirm", open: confirmOpen, title: DIALOG_TITLE, message: `${CONFIRM_PREFIX}${label}${CONFIRM_SUFFIX}`, confirmLabel: CONFIRM_LABEL, cancelLabel: UI_TEXT.cancel, onConfirm: () => { setConfirmOpen(false); if (!isDownloadBusy()) startDownload(label, { kind: "query", tags: query }); }, onClose: () => { setConfirmOpen(false); } }) ] }); } var SAVE_SEARCH_LABEL = "Save as collection"; var SAVE_SEARCH_TITLE = "Save this search as a dynamic collection"; var SAVE_SEARCH_DIALOG_TITLE = "New dynamic collection"; var SAVE_SEARCH_CLASS = "rdw-search-tools-save"; var CLASS_FORM = "rdw-dialog__fields"; var CLASS_ACTIONS = "rdw-dialog__actions"; var CLASS_ERROR = "rdw-search-tools-save-error"; var CLASS_SAVED = "rdw-search-tools-saved"; var SAVED_NOTE = "Saved to Collections"; /** `sort:score:desc`, `score:>=10`: a filter, not a tag. */ var FILTER_MARK = ":"; var TOKEN_SPLIT = /\s+/; var NON_TAG_TOKENS = [ "(", ")", "~" ]; var QUERY_LABEL = "Query"; var EMPTY_NAME_MESSAGE = "Enter a name."; var DUPLICATE_NAME_MESSAGE = "A collection with this name already exists."; var REJECTED_QUERY_MESSAGE = "Enter a tag search that is not saved yet."; var SAVE_SEARCH_CSS = ` .${CLASS_ERROR} { margin: 0; color: var(--rdw-danger); font-size: 12px; } .${CLASS_SAVED} { flex: 1 1 auto; align-self: center; text-align: center; color: var(--rdw-muted); font-size: 12px; } `.trim(); function storedQuery(collection) { return collection.query ?? serialize(collection.tags); } /** * A search text (the tags field, not the page address) without `sort:random`, * when it can be saved as a dynamic collection. Null for a search without tags * (empty, the site's `all`, or filters such as `sort:score:desc` only), the * Feed query, a custom collection's id list, and a search that is already saved. */ function readSavableQuery(tags) { const query = withoutSortRandom(tags); if (isUnfilteredQuery(query)) return null; if (!query.split(TOKEN_SPLIT).some((token) => !NON_TAG_TOKENS.includes(token) && !token.includes(FILTER_MARK))) return null; if (parsePlaylistQuery(query) !== null) return null; const artistTags = listArtistTags(); if (isFullUpdatesQuery(query, artistTags) || isPartialUpdatesQuery(query, artistTags) || findFeedGroupIndex(query, artistTags, getUpdatesGroupSize()) >= 0) return null; for (const collection of load$1().collections) { if (isPlaylist(collection)) continue; if (queriesMatchIgnoringSortRandom(query, storedQuery(collection))) return null; } return query; } function nameError(name) { const folded = name.trim().toLowerCase(); if (folded.length === 0) return EMPTY_NAME_MESSAGE; for (const collection of load$1().collections) if (collection.name.trim().toLowerCase() === folded) return DUPLICATE_NAME_MESSAGE; return null; } /** True when the page is the results list of exactly this search. */ function pageShowsQuery(search, query) { const params = new URLSearchParams(search); if (params.get("s") !== "list") return false; return queriesMatchIgnoringSortRandom(params.get("tags") ?? "", query); } /** * "Save as collection" button for the search panel footer. Rendered only while * the search in the tags field can be saved. The dialog shows the name and the * query that will be stored. When the page already shows that search, saving * takes the collection's cover and post count from it and leaves a short note * in place of the button. When the field was edited but not submitted, the * saved search is opened as the Search button would, so the cover is known. * The collection's bar shows only when it is opened from Collections. */ function SaveSearchButton(props) { const [open, setOpen] = d(false); const [name, setName] = d(""); const [queryDraft, setQueryDraft] = d(""); const [error, setError] = d(""); const [saved, setSaved] = d(false); const savable = readSavableQuery(props.tags); if (savable === null && !open) { if (!saved) return null; return /* @__PURE__ */ a($$1, { children: [/* @__PURE__ */ a("style", { children: SAVE_SEARCH_CSS }), /* @__PURE__ */ a("span", { className: CLASS_SAVED, role: "status", children: SAVED_NOTE })] }); } const close = () => { setOpen(false); setName(""); setError(""); }; const submit = () => { const message = nameError(name); if (message !== null) { setError(message); return; } const query = readSavableQuery(queryDraft); if (query === null) { setError(REJECTED_QUERY_MESSAGE); return; } const created = createDynamicCollection(name.trim(), query); const search = window.location.search; if (pageShowsQuery(search, query)) { rememberDynamicCoverFromPage(created.id, search); setSaved(true); close(); return; } close(); window.location.assign(buildSearchUrl(parseTags(query))); }; return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("style", { children: SAVE_SEARCH_CSS }), /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", className: SAVE_SEARCH_CLASS, title: SAVE_SEARCH_TITLE, onClick: () => { setQueryDraft(savable ?? ""); setName(savable ?? ""); setOpen(true); }, children: SAVE_SEARCH_LABEL }), /* @__PURE__ */ a(Dialog, { open, onClose: close, title: SAVE_SEARCH_DIALOG_TITLE, children: /* @__PURE__ */ a("form", { className: CLASS_FORM, onSubmit: (event) => { event.preventDefault(); event.stopPropagation(); submit(); }, children: [ /* @__PURE__ */ a(TextField, { label: UI_TEXT.nameLabel, value: name, onChange: (value) => { setName(value); setError(""); } }), /* @__PURE__ */ a(QueryField, { label: QUERY_LABEL, value: queryDraft, onChange: (value) => { setQueryDraft(value); setError(""); } }), error.length > 0 ? /* @__PURE__ */ a("p", { className: CLASS_ERROR, role: "alert", children: error }) : null, /* @__PURE__ */ a("div", { className: CLASS_ACTIONS, children: [/* @__PURE__ */ a(Button, { type: "button", variant: "secondary", size: "s", onClick: close, children: UI_TEXT.cancel }), /* @__PURE__ */ a(Button, { type: "submit", variant: "primary", size: "s", children: UI_TEXT.save })] }) ] }) }) ] }); } /** * True in the script's own themes (Light, Dark, Custom), where the skin draws * the site. In Site default and Site dark the site looks the way it does * without the script, and the script does not dress the site's own controls * there: a field with the script's magnifier in it but the site's white box * around it is worse than either (Kaze, 17.11.2026). What the script adds of * its own (the search panel, the buttons, the menu) is there in every theme. */ function skinIsOn() { return document.documentElement.classList.contains(RDW_SKIN_CLASS); } /** * The site's own search field on Posts and Feed, dressed like the script's * search fields: a magnifier, a button that clears it, and a "?" that lists * what the site's search understands. * * Nothing of the site's is moved. The field sits in `div.awesomplete`, which * the site already positions for its suggestion list; the two buttons are * added to that box and laid over the right end of the field. */ var SITE_SEARCH_BOX_SELECTOR = "div.awesomplete"; var SITE_SEARCH_TOOLS_CLASS = "rdw-site-search-tools"; var SITE_SEARCH_TOOL_CLASS = "rdw-site-search-tool"; var SITE_SEARCH_BOX_CLASS = "rdw-site-search-box"; var CLEAR_LABEL = "Clear search"; var HELP_LABEL = "Search syntax"; var HELP_WIDTH_PX = 380; var ICON_PX$1 = 14; /** * The site's cheat sheet, less what the panel under the field already does * with a control: the order, the least score, pictures or videos, AI posts. */ var SITE_SEARCH_HELP = { label: HELP_LABEL, widthPx: HELP_WIDTH_PX, rows: [ ["cat dog", "posts with both tags"], ["( cat ~ dog )", "posts with either tag; keep the spaces"], ["-cat", "posts without the tag"], ["ca*t", "any tag that starts with ca and ends with t"], ["night~", "tags spelled like night"], ["user:bob", "posts uploaded by bob"], ["rating:safe", "by rating; -rating:safe for the rest"], ["parent:1234", "post 1234 and its child posts"], ["width:>=1000", "by size; height: works the same"], ["aspectratio:16:9", "by shape, within 3%"], ["sourcedomains:x.com", "by the site of the source"], ["md5:abc*", "by the file's hash"] ], note: "Sort, Min score, Media and AI posts are set with the controls below the field." }; function SiteSearchTools(props) { const { input } = props; const [filled, setFilled] = d(input.value.length > 0); const [helpOpen, setHelpOpen] = d(false); const helpRef = T(null); A(() => { const sync = () => { setFilled(input.value.length > 0); }; const timer = window.setInterval(sync, 400); input.addEventListener("input", sync); input.addEventListener("change", sync); return () => { window.clearInterval(timer); input.removeEventListener("input", sync); input.removeEventListener("change", sync); }; }, [input]); return /* @__PURE__ */ a($$1, { children: [ filled ? /* @__PURE__ */ a("button", { type: "button", className: `${SITE_SEARCH_TOOL_CLASS} rdw-kit-focusable`, "aria-label": CLEAR_LABEL, title: CLEAR_LABEL, onClick: () => { input.value = ""; input.dispatchEvent(new Event("input", { bubbles: true })); setFilled(false); input.focus(); }, children: /* @__PURE__ */ a(IconX, { size: ICON_PX$1 }) }) : null, /* @__PURE__ */ a("button", { type: "button", ref: helpRef, className: `${SITE_SEARCH_TOOL_CLASS} rdw-kit-focusable`, "aria-label": HELP_LABEL, title: HELP_LABEL, "aria-expanded": helpOpen, onClick: () => { setHelpOpen(!helpOpen); }, children: /* @__PURE__ */ a(IconHelp, { size: ICON_PX$1 }) }), /* @__PURE__ */ a(Popover, { open: helpOpen, onClose: () => { setHelpOpen(false); }, anchorRef: helpRef, widthPx: HELP_WIDTH_PX, "aria-label": HELP_LABEL, children: /* @__PURE__ */ a(SearchHelpList, { help: SITE_SEARCH_HELP }) }) ] }); } /** Adds the buttons to the box of the site's search field. Safe to call again. */ function mountSiteSearchTools(input) { if (!skinIsOn()) return; const box = input.closest(SITE_SEARCH_BOX_SELECTOR); if (!(box instanceof HTMLElement) || box.querySelector(`.rdw-site-search-tools`) !== null) return; box.classList.add(SITE_SEARCH_BOX_CLASS); const tools = document.createElement("span"); tools.className = SITE_SEARCH_TOOLS_CLASS; box.append(tools); Q$1(/* @__PURE__ */ a(SiteSearchTools, { input }), tools); } var FEATURE_ID$4 = "search-tools"; var FEATURE_LABEL$5 = "Search tools"; var FEATURE_PAGES$3 = ["list", "post"]; /** * Followed artists for the Feed chip (read-only). * Mirror first — GM snapshots on bfcache pages can omit recent follows. */ function resolveFollowedArtistTags() { const mirrored = readArtistsMirror(); if (mirrored !== null && mirrored.length > 0) return [...mirrored]; return listArtistTags(); } var TAGS_INPUT_SELECTOR$1 = "input[name=\"tags\"]"; var TAG_SIDEBAR_SELECTOR$2 = "ul#tag-sidebar"; var ROOT_ID = "rdw-search-tools"; var ROOT_CLASS = "rdw-search-tools"; var CARD_CLASS = "rdw-search-tools-card"; var CHIPS_CLASS = "rdw-search-tools-chips"; var CHIP_CLASS = "rdw-search-tools-chip"; var CHIP_ATTR_START = "data-chip-start"; var CHIP_ATTR_END = "data-chip-end"; var CHIP_ATTR_TOGGLE = "data-chip-toggle"; var CHIP_ATTR_REMOVE = "data-chip-remove"; var FIELD_CLASS = "rdw-search-tools-field"; var ROW_SORT_CLASS = "rdw-search-tools-row-sort"; var FOOT_CLASS$1 = "rdw-search-tools-foot"; /** Over the card: the bar of a selection is drawn into it. */ var BAR_HOST_CLASS = "rdw-search-tools-bar"; /** Around the card while posts are being selected: seen, dimmed, not to be pressed. */ var LOCKED_CLASS = "rdw-search-tools-locked"; var RESET_CLASS = "rdw-search-tools-reset"; var TOKEN_SPLIT_RE = /\s+/; var MULTI_SPACE_RE = /\s+/g; var POLL_INTERVAL_MS = 700; var NAV_DEBOUNCE_MS = 400; var META_SEP = ":"; var SCORE_TOKEN_PREFIX = "score:>="; var SCORE_TOKEN_RE = /^score:>=(\d+)$/; var SORT_TOKEN_PREFIX = "sort:"; var MEDIA_VIDEO = "video"; var MEDIA_IMAGES = `-${MEDIA_VIDEO}`; var TAG_TYPE_CLASS_PREFIX = "tag-type-"; var SORT_HINT = "Sorts within the current search"; var RESET_LABEL = "Reset"; var RESET_TITLE = "Clear the search and all filters"; var KEY_ENTER = "Enter"; var EVENT_INPUT = "input"; var EVENT_CHANGE = "change"; var EVENT_CLICK = "click"; var EVENT_AWESOMPLETE_SELECT = "awesomplete-selectcomplete"; var WARN_NO_FORM = "search-tools: search form not found; not mounted"; var BODY_CLASS$3 = featureBodyClass(FEATURE_ID$4); var FILTER_AI_WAIT_TIMEOUT_MS = 4e3; var FILTER_AI_OBSERVER_OPTIONS = { childList: true, subtree: true }; var TAG_TYPES = [ "artist", "character", "copyright", "general", "metadata" ]; function isTagType(value) { for (const entry of TAG_TYPES) if (entry === value) return true; return false; } var MEDIA_OPTIONS = [ { value: "all", label: "All" }, { value: "images", label: "Images" }, { value: "videos", label: "Videos" } ]; var AI_POSTS_OPTIONS = AI_MODE_OPTIONS; var AI_POSTS_SECTION_LABEL = AI_LABEL; /** After "AI posts" in the label, where the choice is not that of Posts: "AI posts in Feed". */ var AI_SCOPE_NAMES = { [AI_SCOPE_FEED]: "Feed", [AI_SCOPE_FOLLOWING]: "Following", [AI_SCOPE_COLLECTIONS]: "Collections" }; var SORT_OPTIONS = [ { value: "newest", label: "Newest", token: null }, { value: "oldest", label: "Oldest", token: "sort:id:asc" }, { value: "score", label: "Top score", token: "sort:score:desc" }, { value: "updated", label: "Recently updated", token: "sort:updated:desc" }, { value: "random", label: "Random", token: "sort:random" } ]; var SORT_TOKEN_TO_MODE = /* @__PURE__ */ new Map(); for (const option of SORT_OPTIONS) if (option.token !== null) SORT_TOKEN_TO_MODE.set(option.token, option.value); var SEARCH_ICON_MASK = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'/%3E%3Cpath d='m21 21-4.3-4.3'/%3E%3C/svg%3E\") center / contain no-repeat"; /** The width the skin gives the sidebar (site-skin.ts); the panel is drawn for it. */ var SIDEBAR_WIDTH_PX = 228; var FEATURE_CSS$4 = [ `body.${BODY_CLASS$3} .${ROOT_CLASS} {`, " margin-top: 8px;", " max-width: 100%;", " box-sizing: border-box;", "}", `body.${BODY_CLASS$3} div.sidebar {`, ` width: ${String(SIDEBAR_WIDTH_PX)}px;`, ` min-width: ${String(SIDEBAR_WIDTH_PX)}px;`, ` max-width: ${String(SIDEBAR_WIDTH_PX)}px;`, "}", `body.${BODY_CLASS$3} .${ROOT_CLASS} {`, " font-family: var(--rdw-font);", "}", `body.${BODY_CLASS$3} .${ROOT_CLASS} * {`, " font-family: var(--rdw-font);", "}", `body.${BODY_CLASS$3} .${CARD_CLASS} {`, " padding: 10px;", " display: grid;", " gap: 10px;", "}", `body.${BODY_CLASS$3} .${CHIPS_CLASS} {`, " display: flex;", " flex-wrap: wrap;", " gap: 5px;", "}", `body.${BODY_CLASS$3} .${CHIP_CLASS} {`, " cursor: default;", "}", `body.${BODY_CLASS$3} .${CHIP_CLASS}[${CHIP_ATTR_TOGGLE}="1"] {`, " cursor: pointer;", "}", `body.${BODY_CLASS$3} .${FIELD_CLASS} {`, " display: grid;", " gap: 0;", " min-width: 0;", "}", `body.${BODY_CLASS$3} .${ROW_SORT_CLASS} {`, " display: grid;", " grid-template-columns: 1fr 72px;", " gap: 8px;", " align-items: start;", "}", `body.${BODY_CLASS$3} .${FOOT_CLASS$1} {`, " display: flex;", " flex-direction: column;", " align-items: stretch;", " gap: 6px;", " border-top: 1px solid var(--rdw-border);", " padding-top: 10px;", "}", `body.${BODY_CLASS$3} .${FOOT_CLASS$1} > button {`, " width: 100%;", " white-space: nowrap;", "}", `body.${BODY_CLASS$3} .${SITE_SEARCH_BOX_CLASS} {`, " position: relative;", " display: block;", "}", `body.${BODY_CLASS$3} .${SITE_SEARCH_BOX_CLASS}::before {`, " content: \"\";", " position: absolute;", " left: 9px;", " top: 50%;", " z-index: 1;", " width: 14px;", " height: 14px;", " transform: translateY(-50%);", " background: var(--rdw-muted);", ` -webkit-mask: ${SEARCH_ICON_MASK};`, ` mask: ${SEARCH_ICON_MASK};`, " pointer-events: none;", "}", `body.${BODY_CLASS$3} .${SITE_SEARCH_BOX_CLASS} > input[name="tags"] {`, " padding-left: 30px !important;", " padding-right: 54px !important;", " box-sizing: border-box;", "}", `body.${BODY_CLASS$3} .${SITE_SEARCH_TOOLS_CLASS} {`, " position: absolute;", " right: 4px;", " top: 50%;", " z-index: 1;", " transform: translateY(-50%);", " display: flex;", " gap: 2px;", "}", `body.${BODY_CLASS$3} button.${SITE_SEARCH_TOOL_CLASS} {`, " display: inline-grid;", " place-items: center;", " width: 22px;", " height: 22px;", " min-height: 0;", " margin: 0;", " padding: 0;", " border: 0;", " border-radius: var(--rdw-radius-s);", " background: transparent;", " color: var(--rdw-muted);", " cursor: pointer;", "}", `body.${BODY_CLASS$3} button.${SITE_SEARCH_TOOL_CLASS}:hover {`, " color: var(--rdw-text);", "}", `body.${BODY_CLASS$3} .${BAR_HOST_CLASS}:not(:empty) {`, " margin-bottom: 8px;", "}", `body.${BODY_CLASS$3} .${LOCKED_CLASS} {`, " opacity: 0.45;", " pointer-events: none;", "}", `body.${BODY_CLASS$3} .${FOOT_CLASS$1} > .${SELECT_NOTE_CLASS} {`, " font: 12px/1.4 var(--rdw-font);", " color: var(--rdw-muted);", "}" ].join("\n"); function findTagsInput() { const input = document.querySelector(TAGS_INPUT_SELECTOR$1); return input instanceof HTMLInputElement ? input : null; } function findSearchForm(input) { const form = input.closest("form"); return form instanceof HTMLFormElement ? form : null; } function parseTokens(value) { const trimmed = value.trim(); if (trimmed.length === 0) return []; return trimmed.split(TOKEN_SPLIT_RE).filter((token) => token.length > 0); } function normalizeSpaces(value) { return value.replace(MULTI_SPACE_RE, " ").trim(); } function joinTokens(tokens) { return tokens.join(" "); } function bareTag(token) { if (token.startsWith("-") && token.length > 1) return token.slice(1); return token; } function normalizeTagKey(raw) { return raw.trim().toLowerCase().replaceAll(" ", "_"); } function isMediaToken(token) { return token === MEDIA_VIDEO || token === MEDIA_IMAGES; } function isSortToken(token) { return bareTag(token).startsWith(SORT_TOKEN_PREFIX); } function isScoreToken(token) { return SCORE_TOKEN_RE.test(bareTag(token)); } function isControlledToken(token) { return isMediaToken(token) || isSortToken(token) || isScoreToken(token); } function isMetaToken(token) { return bareTag(token).includes(META_SEP); } function readMediaMode(tokens) { let hasVideo = false; let hasImages = false; for (const token of tokens) if (token === MEDIA_VIDEO) hasVideo = true; else if (token === MEDIA_IMAGES) hasImages = true; if (hasVideo) return "videos"; if (hasImages) return "images"; return "all"; } function readSortMode(tokens) { for (const token of tokens) { const mode = SORT_TOKEN_TO_MODE.get(bareTag(token)); if (mode !== void 0) return mode; } return "newest"; } function readMinScore(tokens) { for (const token of tokens) { const match = SCORE_TOKEN_RE.exec(bareTag(token)); if (match === null) continue; const raw = match[1]; if (raw === void 0) continue; const value = Number(raw); if (Number.isFinite(value) && value > 0) return value; } return null; } function freeTokens(tokens) { return tokens.filter((token) => !isControlledToken(token)); } function sortTokenForMode(mode) { return SORT_OPTIONS.find((entry) => entry.value === mode)?.token ?? null; } function buildTokenSet(current, media, sort, minScore) { const next = freeTokens(current); if (media === "images") next.push(MEDIA_IMAGES); else if (media === "videos") next.push(MEDIA_VIDEO); const sortToken = sortTokenForMode(sort); if (sortToken !== null) next.push(sortToken); if (minScore !== null && minScore > 0) next.push(`${SCORE_TOKEN_PREFIX}${String(minScore)}`); return next; } function navigateTokens(tokens) { window.location.assign(buildSearchUrl(parseTags(joinTokens(tokens)))); } function toggleExclude(token) { if (token.startsWith("-") && token.length > 1) return token.slice(1); return `-${token}`; } function removeTokenRange(tokens, start, end) { if (start < 0 || end < start || start >= tokens.length) return [...tokens]; return tokens.filter((_, index) => index < start || index > end); } function replaceTokenAt(tokens, index, nextToken) { return tokens.map((token, tokenIndex) => tokenIndex === index ? nextToken : token); } function chipKindFromTagType(tagType) { if (tagType === "artist") return "artist"; if (tagType === "character") return "character"; if (tagType === "copyright") return "copyright"; if (tagType === "metadata") return "metadata"; return "default"; } function readTagTypeFromClassList(classList) { for (const className of classList) { if (!className.startsWith(TAG_TYPE_CLASS_PREFIX)) continue; const typeName = className.slice(9); if (isTagType(typeName)) return typeName; } return null; } function extractSidebarTag(li) { const links = li.querySelectorAll("a[href]"); for (const node of links) { if (!(node instanceof HTMLAnchorElement)) continue; const href = node.getAttribute("href"); if (href === null || href.length === 0) continue; let url; try { url = new URL(href, SITE_ORIGIN); } catch { continue; } const tags = url.searchParams.get(SEARCH_PARAM_TAGS); if (tags !== null && tags.trim().length > 0) { const first = parseTokens(tags)[0]; if (first !== void 0) return normalizeTagKey(bareTag(first)); } const text = node.textContent?.trim() ?? ""; if (text.length > 0) return normalizeTagKey(text); } return null; } function buildSidebarTagTypes() { const map = /* @__PURE__ */ new Map(); const sidebar = document.querySelector(TAG_SIDEBAR_SELECTOR$2); if (!(sidebar instanceof HTMLUListElement)) return map; for (const child of sidebar.children) { if (!(child instanceof HTMLLIElement)) continue; const tagType = readTagTypeFromClassList(child.classList); if (tagType === null) continue; const tag = extractSidebarTag(child); if (tag === null) continue; map.set(tag, tagType); } rememberTagKinds(map); return map; } function findFilterAiCheckbox() { const node = document.querySelector(SITE_SELECTORS.filterAiCheckbox); return node instanceof HTMLInputElement ? node : null; } function setAiRowBodyClass(active) { document.body.classList.toggle(SEARCH_TOOLS_AI_ROW_BODY_CLASS$1, active); } /** * Resolve #chkFilterAI now or when the site injects it. Disconnects on find * or timeout. Returns a cancel function for unmount. */ function waitForFilterAiCheckbox(onFound, onTimeout) { const existing = findFilterAiCheckbox(); if (existing !== null) { onFound(existing); return () => {}; } let settled = false; const finish = (action) => { if (settled) return; settled = true; observer.disconnect(); window.clearTimeout(timeoutId); action(); }; const observer = new MutationObserver(() => { const checkbox = findFilterAiCheckbox(); if (checkbox === null) return; finish(() => { onFound(checkbox); }); }); observer.observe(document.documentElement, FILTER_AI_OBSERVER_OPTIONS); const timeoutId = window.setTimeout(() => { finish(onTimeout); }, FILTER_AI_WAIT_TIMEOUT_MS); return () => { finish(() => {}); }; } /** The part of the site this list belongs to: each has its own choice for AI posts. */ function pageAiScope() { return currentListScope() ?? "posts"; } /** * The choice of this part of the site, not the state of the site's checkbox: * the checkbox is one for the whole site, and the script moves it. */ function readAiPostsMode(_checkbox) { return aiModeIn(pageAiScope()); } function tryParseParenGroup(tokens, start) { if (tokens[start] !== "(") return null; for (let index = start + 1; index < tokens.length; index += 1) { if (tokens[index] === "(") return null; if (tokens[index] === ")") { const inner = tokens.slice(start + 1, index); if (inner.length === 0) return null; return { end: index, inner }; } } return null; } function isOrJoinedMembers(inner) { if (inner.length === 0 || inner.length % 2 === 0) return null; const members = []; for (let index = 0; index < inner.length; index += 1) { const token = inner[index]; if (token === void 0) return null; if (index % 2 === 1) { if (token !== "~") return null; continue; } if (token === "(" || token === ")" || token === "~") return null; members.push(token); } return members.length > 0 ? members : null; } function orGroupLabel(members) { const title = members.join(" "); const query = joinTokens([ "(", ...members.flatMap((member, index) => index === 0 ? [member] : ["~", member]), ")" ]); const artists = resolveFollowedArtistTags(); const count = members.length; if (isFullUpdatesQuery(query, artists) || findFeedGroupIndex(query, artists, getUpdatesGroupSize()) >= 0) return { label: `Feed · ${String(artists.length)} artists`, title }; return { label: `Any of ${String(count)} tags`, title }; } function chipsSignature(chips) { return chips.map((chip) => { if (chip.kind === "tag") return `t:${String(chip.start)}:${chip.token}:${chip.chipKind}`; return `g:${chip.kind}:${String(chip.start)}:${String(chip.end)}:${chip.label}:${chip.title}`; }).join("|"); } function buildChipModels(tokens) { const tagTypes = buildSidebarTagTypes(); const chips = []; let index = 0; while (index < tokens.length) { const token = tokens[index]; if (token === void 0) break; if (isControlledToken(token)) { index += 1; continue; } const group = tryParseParenGroup(tokens, index); if (group !== null) { const groupTokens = tokens.slice(index, group.end + 1); const playlistIds = parsePlaylistQuery(joinTokens(groupTokens)); if (playlistIds !== null && playlistIds.length > 0) { chips.push({ kind: "id-group", start: index, end: group.end, label: `${String(playlistIds.length)} posts`, title: groupTokens.join(" ") }); index = group.end + 1; continue; } const members = isOrJoinedMembers(group.inner); if (members !== null) { const { label, title } = orGroupLabel(members); chips.push({ kind: "or-group", start: index, end: group.end, label, title }); index = group.end + 1; continue; } } const excluded = token.startsWith("-") && token.length > 1; const tagType = tagTypes.get(normalizeTagKey(bareTag(token))) ?? null; chips.push({ kind: "tag", start: index, end: index, token, label: token, excluded, chipKind: chipKindFromTagType(tagType), title: isMetaToken(token) ? token : null }); index += 1; } return chips; } function readPanelView(inputValue, search) { const tokens = parseTokens(inputValue); const chips = buildChipModels(tokens); return { chips, chipsSig: chipsSignature(chips), media: readMediaMode(tokens), sort: readSortMode(tokens), minScore: readMinScore(tokens) }; } function ensureRoot(form) { const existing = document.getElementById(ROOT_ID); if (existing instanceof HTMLDivElement) { if (existing.previousElementSibling !== form) form.after(existing); return existing; } const root = document.createElement("div"); root.id = ROOT_ID; root.className = ROOT_CLASS; form.after(root); return root; } function setInputValueOnly(input, tokens) { input.value = normalizeSpaces(joinTokens(tokens)); } function SearchToolsPanel(props) { const { input } = props; const [view, setView] = d(() => readPanelView(input.value)); const [scoreDraft, setScoreDraft] = d(view.minScore); const [aiPosts, setAiPosts] = d(() => { const checkbox = findFilterAiCheckbox(); return checkbox === null ? null : readAiPostsMode(); }); const scoreFocusedRef = T(false); const navTimerRef = T(null); const lastPolledValueRef = T(input.value); const clearNavTimer = () => { if (navTimerRef.current !== null) { window.clearTimeout(navTimerRef.current); navTimerRef.current = null; } }; const scheduleNavigate = (tokens) => { clearNavTimer(); navTimerRef.current = window.setTimeout(() => { navTimerRef.current = null; navigateTokens(tokens); }, NAV_DEBOUNCE_MS); }; const applyViewFromInput = (options) => { const next = readPanelView(input.value); lastPolledValueRef.current = input.value; setView((prev) => { const chipsUnchanged = next.chipsSig === prev.chipsSig; if (chipsUnchanged && next.media === prev.media && next.sort === prev.sort && next.minScore === prev.minScore) return prev; return { ...next, chips: chipsUnchanged ? prev.chips : next.chips }; }); if (!scoreFocusedRef.current) setScoreDraft(next.minScore); if (options.navigate) scheduleNavigate(parseTokens(input.value)); }; const writeTokens = (tokens, options) => { setInputValueOnly(input, tokens); lastPolledValueRef.current = input.value; const next = readPanelView(input.value); setView((prev) => { const chipsUnchanged = next.chipsSig === prev.chipsSig; return { ...next, chips: chipsUnchanged ? prev.chips : next.chips }; }); if (!scoreFocusedRef.current) setScoreDraft(next.minScore); if (options.navigate) scheduleNavigate(tokens); }; const applyViewRef = T(applyViewFromInput); applyViewRef.current = applyViewFromInput; A(() => { const onSiteInput = () => { applyViewRef.current({ navigate: false }); }; input.addEventListener(EVENT_INPUT, onSiteInput); input.addEventListener(EVENT_CHANGE, onSiteInput); input.addEventListener(EVENT_AWESOMPLETE_SELECT, onSiteInput); const sidebar = document.querySelector(TAG_SIDEBAR_SELECTOR$2); const onSidebarClick = () => { window.setTimeout(() => { applyViewRef.current({ navigate: false }); }, 0); }; if (sidebar !== null) sidebar.addEventListener(EVENT_CLICK, onSidebarClick); const pollId = window.setInterval(() => { if (document.hidden) return; if (input.value === lastPolledValueRef.current) return; applyViewRef.current({ navigate: false }); }, POLL_INTERVAL_MS); return () => { clearNavTimer(); input.removeEventListener(EVENT_INPUT, onSiteInput); input.removeEventListener(EVENT_CHANGE, onSiteInput); input.removeEventListener(EVENT_AWESOMPLETE_SELECT, onSiteInput); if (sidebar !== null) sidebar.removeEventListener(EVENT_CLICK, onSidebarClick); window.clearInterval(pollId); }; }, [input]); A(() => { let checkbox = null; const onCheckboxChange = () => { if (checkbox === null) return; setAiPosts(readAiPostsMode()); }; const cancelWait = waitForFilterAiCheckbox((found) => { checkbox = found; setAiPosts(readAiPostsMode()); setAiRowBodyClass(true); found.addEventListener(EVENT_CHANGE, onCheckboxChange); }, () => { setAiPosts(null); setAiRowBodyClass(false); }); return () => { cancelWait(); if (checkbox !== null) checkbox.removeEventListener(EVENT_CHANGE, onCheckboxChange); setAiRowBodyClass(false); }; }, []); const onChipsClick = (event) => { const target = event.target; if (!(target instanceof Element)) return; const chipEl = target.closest(`[${CHIP_ATTR_START}]`); if (!(chipEl instanceof HTMLElement)) return; const startRaw = chipEl.getAttribute(CHIP_ATTR_START); const endRaw = chipEl.getAttribute(CHIP_ATTR_END); if (startRaw === null || endRaw === null) return; const start = Number(startRaw); const end = Number(endRaw); if (!Number.isFinite(start) || !Number.isFinite(end)) return; if (target.closest(`[${CHIP_ATTR_REMOVE}]`) !== null) { event.preventDefault(); const current = parseTokens(input.value); writeTokens(removeTokenRange(current, start, end), { navigate: true }); return; } if (chipEl.getAttribute(CHIP_ATTR_TOGGLE) !== "1") return; event.preventDefault(); const current = parseTokens(input.value); const currentToken = current[start]; if (currentToken === void 0 || isMetaToken(currentToken)) return; writeTokens(replaceTokenAt(current, start, toggleExclude(currentToken)), { navigate: true }); }; const onMediaChange = (value) => { const media = MEDIA_OPTIONS.find((entry) => entry.value === value)?.value; if (media === void 0) return; const tokens = parseTokens(input.value); writeTokens(buildTokenSet(tokens, media, readSortMode(tokens), readMinScore(tokens)), { navigate: true }); }; const onSortChange = (value) => { const sort = SORT_OPTIONS.find((entry) => entry.value === value)?.value; if (sort === void 0) return; const tokens = parseTokens(input.value); writeTokens(buildTokenSet(tokens, readMediaMode(tokens), sort, readMinScore(tokens)), { navigate: true }); }; const commitScore = () => { const tokens = parseTokens(input.value); let minScore = null; if (scoreDraft !== null && Number.isFinite(scoreDraft) && scoreDraft > 0) minScore = Math.floor(scoreDraft); const current = readMinScore(tokens); if (current === minScore) { setScoreDraft(current); return; } writeTokens(buildTokenSet(tokens, readMediaMode(tokens), readSortMode(tokens), minScore), { navigate: true }); }; const onAiPostsChange = (value) => { const mode = AI_POSTS_OPTIONS.find((entry) => entry.value === value)?.value; if (mode === void 0) return; if (findFilterAiCheckbox() === null) { setAiPosts(null); return; } if (aiHiddenEverywhere() || mode === aiModeIn(pageAiScope())) return; const scope = pageAiScope(); setAiHiddenIn(scope, mode === AI_MODE_HIDE); alignSiteAiFilter(scope); setAiPosts(mode); const typed = parseTokens(input.value); const shown = parseTokens(new URLSearchParams(window.location.search).get("tags") ?? ""); if (joinTokens(typed) !== joinTokens(shown)) { clearNavTimer(); navigateTokens(typed); return; } window.location.reload(); }; const aiScopeName = AI_SCOPE_NAMES[pageAiScope()]; const aiLabel = aiScopeName === void 0 ? AI_POSTS_SECTION_LABEL : `${AI_POSTS_SECTION_LABEL} in ${aiScopeName}`; const [barHost, setBarHost] = d(null); const [selecting, setSelecting] = d(false); const onReset = () => { clearNavTimer(); setInputValueOnly(input, []); lastPolledValueRef.current = input.value; setView(readPanelView("")); setScoreDraft(null); window.location.assign(buildSearchUrl([])); }; return /* @__PURE__ */ a($$1, { children: [ /* @__PURE__ */ a("style", { children: CHIP_CSS }), /* @__PURE__ */ a("div", { className: BAR_HOST_CLASS, ref: setBarHost }), /* @__PURE__ */ a("div", { ...selecting ? { className: LOCKED_CLASS, inert: true } : {}, children: /* @__PURE__ */ a(Card, { className: CARD_CLASS, children: [ view.chips.length > 0 ? /* @__PURE__ */ a("div", { className: FIELD_CLASS, children: [/* @__PURE__ */ a(SectionLabel, { children: "Tags" }), /* @__PURE__ */ a("div", { className: CHIPS_CLASS, onClick: onChipsClick, role: "list", "aria-label": "Search tags", children: view.chips.map((chip) => { if (chip.kind === "tag") { const excluded = chip.excluded; const variantClass = excluded ? "rdw-chip--exclude" : "rdw-chip--dot"; const kindClass = !excluded && chip.chipKind !== "default" ? `rdw-chip--${chip.chipKind}` : ""; const toggleable = !isMetaToken(chip.token); return /* @__PURE__ */ a("span", { className: [ "rdw-chip", variantClass, kindClass, CHIP_CLASS ].filter((part) => part.length > 0).join(" "), role: "listitem", title: chip.title ?? void 0, "data-chip-start": String(chip.start), "data-chip-end": String(chip.end), "data-chip-toggle": toggleable ? "1" : "0", children: [ !excluded ? /* @__PURE__ */ a("i", { className: "rdw-chip__dot", "aria-hidden": "true" }) : null, /* @__PURE__ */ a("span", { children: chip.label }), /* @__PURE__ */ a("button", { type: "button", className: "rdw-chip__remove rdw-kit-focusable", "aria-label": `Remove ${chip.label}`, "data-chip-remove": "1", children: /* @__PURE__ */ a(IconX, { size: 12 }) }) ] }, `t-${String(chip.start)}-${chip.token}`); } return /* @__PURE__ */ a("span", { className: `rdw-chip rdw-chip--group ${CHIP_CLASS}`, role: "listitem", title: chip.title, "data-chip-start": String(chip.start), "data-chip-end": String(chip.end), "data-chip-toggle": "0", children: [/* @__PURE__ */ a("span", { children: chip.label }), /* @__PURE__ */ a("button", { type: "button", className: "rdw-chip__remove rdw-kit-focusable", "aria-label": `Remove ${chip.label}`, "data-chip-remove": "1", children: /* @__PURE__ */ a(IconX, { size: 12 }) })] }, `g-${String(chip.start)}-${String(chip.end)}-${chip.label}`); }) })] }) : null, /* @__PURE__ */ a("div", { className: FIELD_CLASS, children: [/* @__PURE__ */ a(SectionLabel, { children: "Media" }), /* @__PURE__ */ a(Segmented, { label: "Media", options: MEDIA_OPTIONS.map((entry) => ({ value: entry.value, label: entry.label })), value: view.media, onChange: onMediaChange })] }), /* @__PURE__ */ a("div", { className: ROW_SORT_CLASS, title: SORT_HINT, children: [/* @__PURE__ */ a(Select, { label: "Sort", options: SORT_OPTIONS.map((entry) => ({ value: entry.value, label: entry.label })), value: view.sort, onChange: onSortChange }), /* @__PURE__ */ a("div", { onFocusIn: () => { scoreFocusedRef.current = true; }, onFocusOut: (event) => { const next = event.relatedTarget; if (next instanceof Node && event.currentTarget.contains(next)) return; scoreFocusedRef.current = false; commitScore(); }, onKeyDown: (event) => { if (event.key !== KEY_ENTER) return; event.preventDefault(); commitScore(); }, children: /* @__PURE__ */ a(NumberField, { label: "Min score", placeholder: "Any", value: scoreDraft, min: 1, step: 1, onChange: setScoreDraft }) })] }), aiPosts !== null ? /* @__PURE__ */ a("div", { className: FIELD_CLASS, children: [ /* @__PURE__ */ a(SectionLabel, { children: aiLabel }), /* @__PURE__ */ a(Segmented, { label: aiLabel, options: AI_POSTS_OPTIONS.map((entry) => ({ value: entry.value, label: entry.label })), value: aiPosts, disabled: aiHiddenEverywhere(), onChange: onAiPostsChange }), aiHiddenEverywhere() ? /* @__PURE__ */ a(AiEverywhereNote, {}) : null ] }) : null, /* @__PURE__ */ a("div", { className: FOOT_CLASS$1, children: [ /* @__PURE__ */ a(Button, { variant: "secondary", size: "s", className: RESET_CLASS, title: RESET_TITLE, onClick: onReset, children: RESET_LABEL }), /* @__PURE__ */ a(SaveSearchButton, { tags: input.value }), /* @__PURE__ */ a(DownloadControls, { barHost, onSelectingChange: setSelecting }) ] }) ] }) }) ] }); } function mountSearchTools(_ctx) { const input = findTagsInput(); if (input === null) { log.warn(WARN_NO_FORM); return; } const form = findSearchForm(input); if (form === null) { log.warn(WARN_NO_FORM); return; } mountSiteSearchTools(input); const root = ensureRoot(form); Q$1(/* @__PURE__ */ a(SearchToolsPanel, { input }), root); root.classList.add(SEARCH_TOOLS_MOUNTED_CLASS); const remember = () => { if (isGridSelecting()) return; rememberSearchToolsHeight(root.getBoundingClientRect().height); }; if (typeof ResizeObserver === "function") new ResizeObserver(remember).observe(root); else window.requestAnimationFrame(remember); } var searchToolsFeature = { id: FEATURE_ID$4, label: FEATURE_LABEL$5, settingsCaption: "A panel under the search field: rating, type, order and score are picked there and written into the search as text.", pages: [...FEATURE_PAGES$3], defaultEnabled: true, css: FEATURE_CSS$4, mount: mountSearchTools }; var FEATURE_ID$3 = "tag-groups"; var FEATURE_LABEL$4 = "Collapse tags"; var TAG_SIDEBAR_SELECTOR$1 = "ul#tag-sidebar"; var TOGGLE_CLASS = "rdw-tag-group-toggle"; var COLLAPSED_CLASS = "rdw-tag-group-collapsed"; var BODY_FEATURE_CLASS = featureBodyClass(FEATURE_ID$3); var MISSING_SIDEBAR_WARN = "Tag sidebar not found"; var GROUP_HEADER_NAME_SET = /* @__PURE__ */ new Set([ "Copyright", "Character", "Artist", "General", "Meta" ]); var DEFAULT_COLLAPSED = ["General", "Meta"]; var FEATURE_PAGES$2 = ["list", "post"]; /** * Site-skin `html.rdw-skin ul#tag-sidebar > li { display: block }` includes an id, * so a body+class rule cannot hide the row. Match that chain, then add the * collapsed class. The second selector covers site themes (no html.rdw-skin). */ var COLLAPSED_ROW = `ul#tag-sidebar > li.${COLLAPSED_CLASS}`; var HIDE_COLLAPSED_WITH_SKIN = `html.${RDW_SKIN_CLASS} body.${BODY_FEATURE_CLASS} ${COLLAPSED_ROW}`; var HIDE_COLLAPSED_SITE_THEME = `body.${BODY_FEATURE_CLASS} ${COLLAPSED_ROW}`; var FEATURE_CSS$3 = [ `${HIDE_COLLAPSED_WITH_SKIN},`, `${HIDE_COLLAPSED_SITE_THEME} { display: none; }`, `body.${BODY_FEATURE_CLASS} button.${TOGGLE_CLASS} {`, " background: transparent;", " border: none;", " color: inherit;", " cursor: pointer;", " font: inherit;", " padding: 0;", "}", `body.${BODY_FEATURE_CLASS} button.${TOGGLE_CLASS}:focus-visible {`, " outline: 2px solid var(--rdw-accent);", " outline-offset: 2px;", "}" ].join("\n"); var TagGroupsStateSchema = object({ collapsed: array(string()) }); function defaultState() { return { collapsed: [...DEFAULT_COLLAPSED] }; } function parseTagGroupsState(raw) { const parsed = TagGroupsStateSchema.safeParse(raw); if (!parsed.success) return defaultState(); return parsed.data; } function isGroupHeaderName(text) { return GROUP_HEADER_NAME_SET.has(text); } function readHeaderName(li) { const h6 = li.querySelector(":scope > h6"); if (!(h6 instanceof HTMLHeadingElement)) return null; const text = h6.textContent?.trim() ?? ""; if (!isGroupHeaderName(text)) return null; return text; } function collectGroups(sidebar) { const groups = []; let current = null; for (const child of sidebar.children) { if (!(child instanceof HTMLLIElement)) continue; const headerName = readHeaderName(child); if (headerName !== null) { current = { name: headerName, headerLi: child, members: [] }; groups.push(current); continue; } if (current !== null) current.members.push(child); } return groups; } function formatToggleLabel(name, count) { return `${name} (${String(count)})`; } function applyGroupCollapsed(members, button, collapsed) { for (const member of members) member.classList.toggle(COLLAPSED_CLASS, collapsed); button.setAttribute("aria-expanded", collapsed ? "false" : "true"); } function writeCollapsedState(ctx, collapsedNames) { ctx.setState({ collapsed: [...collapsedNames] }); } function mountToggle(group, collapsedNames, ctx) { const h6 = group.headerLi.querySelector(":scope > h6"); if (!(h6 instanceof HTMLHeadingElement)) return; const button = document.createElement("button"); button.type = "button"; button.className = TOGGLE_CLASS; button.textContent = formatToggleLabel(group.name, group.members.length); const initiallyCollapsed = collapsedNames.has(group.name); applyGroupCollapsed(group.members, button, initiallyCollapsed); button.addEventListener("click", () => { const nextCollapsed = !collapsedNames.has(group.name); if (nextCollapsed) collapsedNames.add(group.name); else collapsedNames.delete(group.name); applyGroupCollapsed(group.members, button, nextCollapsed); writeCollapsedState(ctx, [...collapsedNames]); }); h6.replaceChildren(button); } function mountTagGroups(ctx) { const sidebar = document.querySelector(TAG_SIDEBAR_SELECTOR$1); if (!(sidebar instanceof HTMLUListElement)) { log.warn(MISSING_SIDEBAR_WARN); return; } const state = ctx.getState(parseTagGroupsState); const collapsedNames = new Set(state.collapsed); const groups = collectGroups(sidebar); for (const group of groups) mountToggle(group, collapsedNames, ctx); } var tagGroupsFeature = { id: FEATURE_ID$3, label: FEATURE_LABEL$4, settingsCaption: "The tags in the sidebar fold by type, and an artist, character or copyright tag gets a Follow button.", pages: [...FEATURE_PAGES$2], defaultEnabled: true, css: FEATURE_CSS$3, resetStateOnToggle: true, mount: mountTagGroups }; /** * A click on the "?" of a tag in the sidebar shows what the site's wiki says * about the tag, in a small panel beside it, instead of leaving the page. * * The "?" leads to a search of the wiki, not to the entry, so one click is two * requests: that search, then the entry it lists. Both only on the click, and * an answer is kept until the page is left. A click with a modifier key, or * the middle button, opens the wiki as before. */ var FEATURE_ID$2 = "tag-wiki"; var FEATURE_LABEL$3 = "Tag description on the ? in the sidebar"; var BODY_CLASS$2 = featureBodyClass(FEATURE_ID$2); var SIDEBAR_SELECTOR = "ul#tag-sidebar"; var HELP_LINK_TEXT = "?"; var WIKI_HREF_MARK = "page=wiki"; var ENTRY_LINK_SELECTOR = "table.highlightable a[href*=\"page=wiki\"][href*=\"s=view\"]"; /** The left half of an entry page: heading, tag type, the text, then the site's own notes. */ var ENTRY_BODY_SELECTOR = "div#content > div.flexi > div"; var TAG_LINK_SELECTOR = `a[href*="${SEARCH_PARAM_TAGS}="]`; var TITLE_PREFIX = "Now Viewing:"; var TYPE_PREFIX = "Tag type:"; var NOTES_HEADING = "Other Wiki Information"; var PANEL_ID = "rdw-tag-wiki"; var TITLE_CLASS = "rdw-tag-wiki-title"; var TYPE_CLASS = "rdw-tag-wiki-type"; var TEXT_CLASS = "rdw-tag-wiki-text"; var FOOT_CLASS = "rdw-tag-wiki-foot"; var PANEL_WIDTH_PX = 320; var PANEL_GAP_PX = 8; var PANEL_Z_INDEX = 2147483e3; var TEXT_LOADING = "Reading the wiki…"; var TEXT_NO_ENTRY = "The wiki has no entry for this tag."; var TEXT_EMPTY_ENTRY = "The wiki entry has no description."; var TEXT_FAILED = "Could not read the wiki. Try again later."; var TEXT_OPEN = "Open in the wiki"; var PANEL_LABEL = "Tag description"; var FEATURE_CSS$2 = ` #${PANEL_ID} { position: fixed; z-index: ${String(PANEL_Z_INDEX)}; box-sizing: border-box; width: ${String(PANEL_WIDTH_PX)}px; max-width: calc(100vw - ${String(16)}px); padding: 10px 12px; border: 1px solid var(--rdw-border); border-radius: var(--rdw-radius-l); background: var(--rdw-surface); box-shadow: var(--rdw-shadow-2); color: var(--rdw-text); font: 12px/1.45 var(--rdw-font); } #${PANEL_ID} .${TITLE_CLASS} { margin: 0; font: 700 13px var(--rdw-font); overflow-wrap: anywhere; } #${PANEL_ID} .${TYPE_CLASS} { margin: 2px 0 0; color: var(--rdw-muted); } #${PANEL_ID} .${TEXT_CLASS} { margin: 8px 0 0; max-height: 240px; overflow-y: auto; white-space: pre-wrap; overflow-wrap: anywhere; } #${PANEL_ID} .${FOOT_CLASS} { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rdw-border); } #${PANEL_ID} .${FOOT_CLASS} a { color: var(--rdw-accent); } `.trim(); /** A tag as the wiki and the sidebar may spell it: case and underscores aside. */ function foldTag(tag) { return tag.trim().toLowerCase().replaceAll(" ", "_"); } /** The address of the entry for `tag` among the results of a wiki search, or null. */ function findWikiEntryHref(results, tag) { const wanted = foldTag(tag); for (const link of results.querySelectorAll(ENTRY_LINK_SELECTOR)) if (foldTag(link.textContent ?? "") === wanted) return link.getAttribute("href"); return null; } function nodeText(node) { if (node instanceof HTMLBRElement) return "\n"; return node.textContent ?? ""; } /** What an entry page says: the heading, the tag type and the text between them and the site's notes. */ function readWikiEntry(page) { const body = page.querySelector(ENTRY_BODY_SELECTOR); const heading = body?.querySelector("h2") ?? null; if (body === null || body === void 0 || heading === null) return null; const title = (heading.textContent ?? "").replace(TITLE_PREFIX, "").trim(); let type = ""; let text = ""; let started = false; for (const node of body.childNodes) { const content = (node.textContent ?? "").trim(); if (node === heading) { started = true; continue; } if (!started) continue; if (node instanceof HTMLElement && content.startsWith(TYPE_PREFIX)) { type = content.slice(9).trim(); continue; } if (node instanceof HTMLElement && content === NOTES_HEADING) break; text += nodeText(node); } const clean = text.split("\n").map((line) => line.replace(/\s+/g, " ").trim()).join("\n").replace(/\n{3,}/g, "\n\n").trim(); return { title, type, text: clean }; } var answers = /* @__PURE__ */ new Map(); async function fetchDocument(url) { const absolute = new URL(url, window.location.href); if (absolute.origin !== window.location.origin) throw new Error("cross-origin wiki address"); const response = await fetch(absolute.href, { method: "GET", credentials: FETCH_CREDENTIALS }); if (!response.ok) throw new Error(`HTTP ${String(response.status)}`); return new DOMParser().parseFromString(await response.text(), "text/html"); } async function readAnswer(tag, searchHref) { const known = answers.get(tag); if (known !== void 0 && known.kind !== "failed") return known; let answer; try { const entryHref = findWikiEntryHref(await fetchDocument(searchHref), tag); if (entryHref === null) answer = { kind: "none", href: searchHref }; else { const entry = readWikiEntry(await fetchDocument(entryHref)); answer = entry === null ? { kind: "none", href: entryHref } : { kind: "entry", entry, href: entryHref }; } } catch (error) { log.warn("tag-wiki: request failed", tag, error); answer = { kind: "failed", href: searchHref }; } answers.set(tag, answer); return answer; } var openFor = null; function closeTagWiki() { document.getElementById(PANEL_ID)?.remove(); document.removeEventListener("keydown", onKeyDown, true); document.removeEventListener("pointerdown", onPointerDown, true); const opener = openFor; openFor = null; opener?.focus(); } function onKeyDown(event) { if (event.key === "Escape") { event.preventDefault(); closeTagWiki(); } } function onPointerDown(event) { const panel = document.getElementById(PANEL_ID); const target = event.target; if (panel === null || !(target instanceof Node)) return; if (!panel.contains(target) && !(openFor?.contains(target) ?? false)) closeTagWiki(); } function line(className, text) { const element = document.createElement("p"); element.className = className; element.textContent = text; return element; } function fill(panel, tag, answer) { const parts = [line(TITLE_CLASS, answer?.kind === "entry" ? answer.entry.title : tag)]; if (answer === null) parts.push(line(TEXT_CLASS, TEXT_LOADING)); else if (answer.kind === "entry") { if (answer.entry.type.length > 0) parts.push(line(TYPE_CLASS, answer.entry.type)); parts.push(line(TEXT_CLASS, answer.entry.text.length > 0 ? answer.entry.text : TEXT_EMPTY_ENTRY)); } else parts.push(line(TEXT_CLASS, answer.kind === "none" ? TEXT_NO_ENTRY : TEXT_FAILED)); if (answer !== null) { const foot = document.createElement("p"); foot.className = FOOT_CLASS; const link = document.createElement("a"); link.href = answer.href; link.textContent = TEXT_OPEN; foot.append(link); parts.push(foot); } panel.replaceChildren(...parts); } function place(panel, anchor) { const rect = anchor.getBoundingClientRect(); const width = Math.min(PANEL_WIDTH_PX, window.innerWidth - 16); let left = rect.right + PANEL_GAP_PX; if (left + width > window.innerWidth - PANEL_GAP_PX) left = Math.max(PANEL_GAP_PX, rect.left - width - PANEL_GAP_PX); const height = panel.offsetHeight; const top = Math.max(PANEL_GAP_PX, Math.min(rect.top, window.innerHeight - height - PANEL_GAP_PX)); panel.style.left = `${String(left)}px`; panel.style.top = `${String(top)}px`; } /** The tag a row of the sidebar is about, from its search link. */ function sidebarRowTag(row) { const links = row.querySelectorAll(TAG_LINK_SELECTOR); const href = links[links.length - 1]?.getAttribute("href") ?? null; if (href === null) return null; try { const tag = new URL(href, window.location.href).searchParams.get(SEARCH_PARAM_TAGS); return tag === null || tag.trim().length === 0 ? null : tag.trim(); } catch { return null; } } function showFor(link, tag) { if (openFor === link) { closeTagWiki(); return; } closeTagWiki(); const panel = document.createElement("div"); panel.id = PANEL_ID; panel.setAttribute("role", "dialog"); panel.setAttribute("aria-label", PANEL_LABEL); fill(panel, tag, null); document.body.append(panel); place(panel, link); openFor = link; document.addEventListener("keydown", onKeyDown, true); document.addEventListener("pointerdown", onPointerDown, true); readAnswer(tag, link.href).then((answer) => { if (openFor === link && panel.isConnected) { fill(panel, tag, answer); place(panel, link); } }); } function onSidebarClick(event) { if (!document.body.classList.contains(BODY_CLASS$2)) return; if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return; const target = event.target; const link = target instanceof Element ? target.closest("a") : null; if (!(link instanceof HTMLAnchorElement) || (link.textContent ?? "").trim() !== HELP_LINK_TEXT || !(link.getAttribute("href") ?? "").includes(WIKI_HREF_MARK)) return; const row = link.closest("li"); const tag = row === null ? null : sidebarRowTag(row); if (tag === null) return; event.preventDefault(); event.stopPropagation(); showFor(link, tag); } var boundSidebar = null; function mountTagWiki(_ctx) { const sidebar = document.querySelector(SIDEBAR_SELECTOR); if (sidebar === null || sidebar === boundSidebar) return; boundSidebar = sidebar; sidebar.addEventListener("click", (event) => { if (event instanceof MouseEvent) onSidebarClick(event); }); } var tagWikiFeature = { id: FEATURE_ID$2, label: FEATURE_LABEL$3, pages: ["list", "post"], defaultEnabled: true, cssOnly: true, settingsCaption: "Shows the wiki text beside the tag instead of opening the wiki. Two requests on a click: the wiki search and the entry.", css: FEATURE_CSS$2, mount: mountTagWiki }; /** * Hides the browser tooltip with the full tag list that shows when the pointer * rests on a thumbnail. * * The tooltip is the `title` of the preview image (`img.preview`; on the * favorites page the image has no class). The attribute stays: the site's * scripts and this script read tags from it, and nothing inside `a#p{ID}` is * changed. Instead the image stops taking the pointer, so the hovered element * is the link around it, which has no title. A click lands on the link as * before. */ var FEATURE_ID$1 = "thumb-tooltip"; var FEATURE_LABEL$2 = "Hide tag tooltip on thumbnails"; /** "other" is for the Comments page; elsewhere the rules match nothing. */ var FEATURE_PAGES$1 = [ "list", "favorites", "other" ]; var BODY_CLASS$1 = featureBodyClass(FEATURE_ID$1); /** Added when the site lays the thumb link out inline (see mount). */ var THUMB_TOOLTIP_INLINE_CLASS = `${BODY_CLASS$1}-inline`; var DISPLAY_INLINE = "inline"; var THUMB_LINK_SELECTOR = `:is(${SITE_SELECTORS.thumb}, ${SITE_SELECTORS.commentThumb}) > a:not([onclick])`; var FEATURE_CSS$1 = ` body.${BODY_CLASS$1} ${SITE_SELECTORS.thumb} > a > img, body.${BODY_CLASS$1} ${SITE_SELECTORS.commentThumb} > a > img { pointer-events: none; } body.${BODY_CLASS$1}.${THUMB_TOOLTIP_INLINE_CLASS} ${THUMB_LINK_SELECTOR} { display: inline-block; } `.trim(); /** * An inline link does not cover its image for hit-testing, so with the image * out of the way a click would miss the link. Such a link becomes an * inline-block, which wraps the image. */ function mountThumbTooltip(_ctx) { const link = document.querySelector(THUMB_LINK_SELECTOR); if (link === null) return; if (window.getComputedStyle(link).display === DISPLAY_INLINE) document.body.classList.add(THUMB_TOOLTIP_INLINE_CLASS); } var thumbTooltipFeature = { id: FEATURE_ID$1, label: FEATURE_LABEL$2, pages: [...FEATURE_PAGES$1], defaultEnabled: true, css: FEATURE_CSS$1, cssOnly: true, mount: mountThumbTooltip }; /** * How a video is told from a picture in a grid: a play sign in a small plate * on the thumbnail, the same plate "GIF" has, in place of the frame around * it. A frame is told by its colour alone and reads as a focus ring or as a * selection (the designer, 17.11.2026). Kaze asked for it as a choice: with * the switch off the frame is back. * * Styles only, and in the script's own themes only: in Site default and Site * dark the thumbnails keep the site's own frame whatever the switch says. * Which thumbs are videos is marked by site/video-thumbs.ts. */ var VIDEO_MARK_FEATURE_ID = "video-mark"; var FEATURE_LABEL$1 = "Play icon on video thumbnails"; var FEATURE_CAPTION = "Off: a frame around the thumbnail instead. In the site's own themes the site's frame stays."; var BODY_CLASS = featureBodyClass(VIDEO_MARK_FEATURE_ID); var SCOPE = `html.${RDW_SKIN_CLASS} body.${BODY_CLASS}`; var videoMarkFeature = { id: VIDEO_MARK_FEATURE_ID, label: FEATURE_LABEL$1, pages: [ "list", "favorites", "other" ], defaultEnabled: true, cssOnly: true, settingsCaption: FEATURE_CAPTION, css: ` ${SCOPE} .${VIDEO_THUMB_CLASS} > a > img, ${SCOPE} .webm-thumb { border: 0; } ${SCOPE} .${VIDEO_THUMB_CLASS}::after { content: "\\25B6\\FE0E";${THUMB_LABEL_RULES} } @supports (anchor-name: --a) { ${SCOPE} .${VIDEO_THUMB_CLASS}::after { position-anchor: ${THUMB_ANCHOR_NAME}; left: calc(anchor(left) + ${String(6)}px); bottom: calc(anchor(bottom) + ${String(6)}px); } html.${FAVORITES_PAGE_CLASS}.${RDW_SKIN_CLASS} body.${BODY_CLASS} .${VIDEO_THUMB_CLASS}::after { position-anchor: ${FAVORITE_IMAGE_ANCHOR_NAME}; } } `.trim(), mount: () => void 0 }; /** * The site's Comments page: a list of posts, each with its preview, its whole * tag list and its latest comments. * * - Video posts get the mark the outline and the hover preview go by. * - A long tag list is folded to a few lines, with a button that opens it. * * The page is recognised by its markup, not by its address. */ var TAGS_COLLAPSED_CLASS = "rdw-tags-collapsed"; var TAGS_TOGGLE_CLASS = "rdw-tags-toggle"; var STYLE_ID$1 = "rdw-comments-page-style"; /** How many lines of tags stay visible while the list is folded. */ var COLLAPSED_LINES = 3; /** Rounding slack when comparing the full height with the folded one. */ var OVERFLOW_SLACK_PX = 1; var TAG_SELECTOR = ":scope > span"; var ARIA_EXPANDED = "aria-expanded"; var COMMENTS_PAGE_CSS = ` ${SITE_SELECTORS.commentTags}.${TAGS_COLLAPSED_CLASS} { max-height: ${String(COLLAPSED_LINES)}lh !important; overflow: hidden !important; } .${TAGS_TOGGLE_CLASS} { display: block; margin: 4px 0 0; padding: 0; border: 0; background: none; color: var(--rdw-accent); font: inherit; font-size: 12px; cursor: pointer; } .${TAGS_TOGGLE_CLASS}:hover { color: var(--rdw-text); } .${TAGS_TOGGLE_CLASS}:focus-visible { outline: 2px solid var(--rdw-accent); outline-offset: 2px; } `.trim(); function isCommentsPage(root = document) { return root.querySelector(SITE_SELECTORS.commentList) !== null; } function showAllLabel(count) { return `Show all ${String(count)} tags`; } var SHOW_FEWER_LABEL = "Show fewer tags"; function ensureStyle$1() { if (document.getElementById(STYLE_ID$1) !== null) return; const style = document.createElement("style"); style.id = STYLE_ID$1; style.textContent = COMMENTS_PAGE_CSS; document.head.append(style); } /** * Folds one tag list when it is taller than the folded height and puts the * button under it. A list that fits is left as it is. */ function foldTags(tags) { tags.classList.add(TAGS_COLLAPSED_CLASS); if (tags.scrollHeight <= tags.clientHeight + OVERFLOW_SLACK_PX) { tags.classList.remove(TAGS_COLLAPSED_CLASS); return false; } const collapsedLabel = showAllLabel(tags.querySelectorAll(TAG_SELECTOR).length); const button = document.createElement("button"); button.type = "button"; button.className = TAGS_TOGGLE_CLASS; button.textContent = collapsedLabel; button.setAttribute(ARIA_EXPANDED, "false"); button.addEventListener("click", () => { const collapsed = tags.classList.toggle(TAGS_COLLAPSED_CLASS); button.textContent = collapsed ? collapsedLabel : SHOW_FEWER_LABEL; button.setAttribute(ARIA_EXPANDED, collapsed ? "false" : "true"); }); tags.after(button); return true; } /** Folds the long tag lists under `root`; returns how many it folded. */ function foldLongTagLists(root = document) { let folded = 0; for (const tags of root.querySelectorAll(SITE_SELECTORS.commentTags)) if (tags instanceof HTMLElement && foldTags(tags)) folded += 1; return folded; } /** Does nothing on a page that is not the Comments list. */ function mountCommentsPage() { if (!isCommentsPage()) return; ensureStyle$1(); markVideoThumbs(document, SITE_SELECTORS.commentThumb); mountGifMarks(SITE_SELECTORS.commentThumb); foldLongTagLists(); } var FEATURE_ID = "video-preview"; var FEATURE_LABEL = "Video preview on hover"; /** Settings caption for Phase 2 F/H (Switch hint under the toggle). */ var VIDEO_PREVIEW_SETTING_CAPTION = "Each preview loads the video file itself."; /** "other" is for the Comments page, which is recognised by its markup. */ var FEATURE_PAGES = [ "list", "favorites", "other" ]; var VIDEO_CLASS = "rdw-video-preview"; var WEBM_PREVIEW_SELECTOR = "img.preview.webm-thumb"; var THUMBS_SELECTOR = `${SITE_SELECTORS.thumb}, ${SITE_SELECTORS.commentThumb}`; var VIDEO_Z_INDEX = 3; var PRELOAD_NONE = "none"; var BODY_SELECTOR = `body.${featureBodyClass(FEATURE_ID)}`; var FEATURE_CSS = ` ${BASE_GRID_CSS.trim()} ${BODY_SELECTOR} .${VIDEO_CLASS} { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: ${String(VIDEO_Z_INDEX)}; margin: 0; padding: 0; border: 0; object-fit: contain; pointer-events: none; } @supports (anchor-name: --a) { ${BODY_SELECTOR} .${VIDEO_CLASS} { position-anchor: ${THUMB_ANCHOR_NAME}; top: anchor(top); left: anchor(left); width: anchor-size(width); height: anchor-size(height); } } `.trim(); /** Post id → when its preview last failed to load, ms since epoch. */ var failedPostIds = /* @__PURE__ */ new Map(); /** * A post whose preview failed is left alone for a while and then tried * again: a file just uploaded may not be served yet, and one stray error * should not switch the preview of that post off until the page is reloaded. */ function failedRecently(postId) { const failedAt = failedPostIds.get(postId); if (failedAt === void 0) return false; if (Date.now() - failedAt < 3e4) return true; failedPostIds.delete(postId); return false; } var boundThumbGeneration = /* @__PURE__ */ new WeakMap(); var bindGeneration = 0; var activePreview = null; var hoverTimerId = null; var hoverThumb = null; var started = false; function clearHoverTimer() { if (hoverTimerId === null) return; window.clearTimeout(hoverTimerId); hoverTimerId = null; } function tearDownActive() { const current = activePreview; if (current === null) return; activePreview = null; current.video.removeEventListener("error", current.onError); current.video.pause(); current.video.src = ""; current.video.load(); current.video.remove(); } function findThumbLink(thumb, postId) { const byId = thumb.querySelector(`#p${postId}`); if (byId instanceof HTMLAnchorElement) return byId; const byHref = thumb.querySelector(SITE_SELECTORS.thumbLink); if (byHref instanceof HTMLAnchorElement) return byHref; const around = thumb.querySelector(THUMB_IMAGE_SELECTOR)?.parentElement; return around instanceof HTMLAnchorElement ? around : null; } function readPostId(thumb) { return extractPostIdFromThumb(thumb) ?? extractPostIdFromThumbLink(thumb) ?? extractPostIdFromCommentThumb(thumb); } function findWebmThumbImage(thumb) { const img = thumb.querySelector(WEBM_PREVIEW_SELECTOR); if (img instanceof HTMLImageElement) return img; if (!thumb.classList.contains("rdw-video-thumb")) return null; const favorite = thumb.querySelector(THUMB_IMAGE_SELECTOR); return favorite instanceof HTMLImageElement ? favorite : null; } /** * Puts the video exactly over the image by measuring both. The stylesheet * does the same by anchor positioning, but the browser does not always find * the anchor for a thumb that got its anchor scope only now, on hover (seen * on the favorites page: the video took the size of the whole cell). Measured * numbers do not depend on that. Nothing is set when there is no layout. */ function placeOverImage(video, thumb, img) { const image = img.getBoundingClientRect(); if (image.width <= 0 || image.height <= 0) return; const cell = thumb.getBoundingClientRect(); video.style.top = `${String(image.top - cell.top - thumb.clientTop)}px`; video.style.left = `${String(image.left - cell.left - thumb.clientLeft)}px`; video.style.width = `${String(image.width)}px`; video.style.height = `${String(image.height)}px`; } function startPreview(thumb) { const postId = readPostId(thumb); if (postId === null || failedRecently(postId)) return; const img = findWebmThumbImage(thumb); if (img === null) return; const videoUrl = buildVideoUrlFromThumbUrl(img.currentSrc || img.src); if (videoUrl === null) return; const link = findThumbLink(thumb, postId); if (link === null) return; tearDownActive(); ensureThumbAnchor(thumb); const video = document.createElement("video"); video.className = VIDEO_CLASS; video.muted = true; video.defaultMuted = true; video.loop = true; video.playsInline = true; video.setAttribute("playsinline", ""); video.preload = PRELOAD_NONE; video.setAttribute("aria-hidden", "true"); const onError = () => { failedPostIds.set(postId, Date.now()); if (activePreview?.video === video) tearDownActive(); else { video.removeEventListener("error", onError); video.pause(); video.src = ""; video.load(); video.remove(); } }; video.addEventListener("error", onError); video.src = videoUrl; link.after(video); placeOverImage(video, thumb, img); activePreview = { thumb, video, postId, onError }; const playResult = video.play(); if (playResult !== void 0) playResult.catch(() => {}); } function onThumbPointerEnter(event) { const thumb = event.currentTarget; if (!(thumb instanceof HTMLElement)) return; const postId = readPostId(thumb); if (postId === null || failedRecently(postId)) return; if (findWebmThumbImage(thumb) === null) return; clearHoverTimer(); hoverThumb = thumb; hoverTimerId = window.setTimeout(() => { hoverTimerId = null; if (hoverThumb !== thumb) return; startPreview(thumb); }, 200); } function onThumbPointerLeave(event) { const thumb = event.currentTarget; if (!(thumb instanceof HTMLElement)) return; if (hoverThumb === thumb) hoverThumb = null; clearHoverTimer(); if (activePreview?.thumb === thumb) tearDownActive(); } function bindThumb(thumb) { if (boundThumbGeneration.get(thumb) === bindGeneration) return; if (findWebmThumbImage(thumb) === null) return; boundThumbGeneration.set(thumb, bindGeneration); thumb.addEventListener("pointerenter", onThumbPointerEnter); thumb.addEventListener("pointerleave", onThumbPointerLeave); } function bindThumbsInRoot(root) { const thumbs = root.querySelectorAll(THUMBS_SELECTOR); for (const thumb of thumbs) if (thumb instanceof HTMLElement) bindThumb(thumb); } function startBindings() { if (started) return; started = true; bindThumbsInRoot(document); onThumbsAdded((root) => { bindThumbsInRoot(root); }); } function mountVideoPreview(ctx) { if (ctx.pageKind === "other" && !isCommentsPage()) return; scheduleAfterFirstPaint(() => { startBindings(); }); } var videoPreviewFeature = { id: FEATURE_ID, label: FEATURE_LABEL, pages: [...FEATURE_PAGES], defaultEnabled: false, settingsCaption: VIDEO_PREVIEW_SETTING_CAPTION, css: FEATURE_CSS, mount: mountVideoPreview }; var FEATURES = exports("a$",[ feedFeature, menuCleanupFeature, tagGroupsFeature, searchToolsFeature, seenDimFeature, playlistMenuFeature, playlistBarFeature, blacklistHideFeature, infiniteScrollFeature, postActionsFeature, gridDensityFeature, thumbTooltipFeature, favoritesBulkFeature, videoPlayerFeature, videoPreviewFeature, cdnFallbackFeature, downloadsFeature, imageZoomFeature, gifPostFeature, fullImageFeature, sidebarRightFeature, motionFeature, feedCounterFeature, tagWikiFeature, videoMarkFeature ]); /** * The groups the settings page shows the page tweaks in, by the part of the * site a tweak changes. Kept here, beside the list of the features, so that a * new feature is given its group where it is added to the list. */ var SETTINGS_GROUP = exports("b1",{ header: "header", grid: "grid", post: "post", video: "video", feed: "feed", ai: "ai", search: "search", collections: "collections", favorites: "favorites", downloads: "downloads", appearance: "appearance", other: "other" }); /** The groups in the order they are shown; "Other" is last. */ var SETTINGS_GROUPS = exports("aM",[ { id: SETTINGS_GROUP.header, title: "Header" }, { id: SETTINGS_GROUP.grid, title: "Grid and thumbnails" }, { id: SETTINGS_GROUP.post, title: "Post page" }, { id: SETTINGS_GROUP.video, title: "Video" }, { id: SETTINGS_GROUP.feed, title: "Feed" }, { id: SETTINGS_GROUP.ai, title: "AI posts" }, { id: SETTINGS_GROUP.search, title: "Search and sidebar" }, { id: SETTINGS_GROUP.collections, title: "Collections" }, { id: SETTINGS_GROUP.other, title: "Other" } ]); /** * Made when first asked for, not when this module is loaded: some features * import the runtime, which imports this list, so at load time a feature * named here may not be there yet. */ function buildFeatureSettingsGroups() { return /* @__PURE__ */ new Map([ [menuCleanupFeature.id, SETTINGS_GROUP.header], [seenDimFeature.id, SETTINGS_GROUP.grid], [blacklistHideFeature.id, SETTINGS_GROUP.grid], [infiniteScrollFeature.id, SETTINGS_GROUP.grid], [thumbTooltipFeature.id, SETTINGS_GROUP.grid], [gridDensityFeature.id, SETTINGS_GROUP.grid], [postActionsFeature.id, SETTINGS_GROUP.post], [imageZoomFeature.id, SETTINGS_GROUP.post], [fullImageFeature.id, SETTINGS_GROUP.post], [gifPostFeature.id, SETTINGS_GROUP.post], [cdnFallbackFeature.id, SETTINGS_GROUP.post], [videoPlayerFeature.id, SETTINGS_GROUP.video], [videoPreviewFeature.id, SETTINGS_GROUP.video], [videoMarkFeature.id, SETTINGS_GROUP.video], [feedFeature.id, SETTINGS_GROUP.feed], [feedCounterFeature.id, SETTINGS_GROUP.feed], [searchToolsFeature.id, SETTINGS_GROUP.search], [tagGroupsFeature.id, SETTINGS_GROUP.search], [tagWikiFeature.id, SETTINGS_GROUP.search], [sidebarRightFeature.id, SETTINGS_GROUP.search], [playlistMenuFeature.id, SETTINGS_GROUP.collections], [playlistBarFeature.id, SETTINGS_GROUP.collections], [favoritesBulkFeature.id, SETTINGS_GROUP.favorites], [downloadsFeature.id, SETTINGS_GROUP.downloads], [motionFeature.id, SETTINGS_GROUP.appearance] ]); } var featureSettingsGroups = null; /** The group of a feature; one that was given none is shown under "Other". */ function featureSettingsGroup(featureId) { featureSettingsGroups ??= buildFeatureSettingsGroups(); return featureSettingsGroups.get(featureId) ?? SETTINGS_GROUP.other; } var mountedIds = /* @__PURE__ */ new Set(); var activePageKind = null; var activeSearch = ""; var thumbsAddedListeners = /* @__PURE__ */ new Set(); /** Subscribe to thumbs inserted after the initial page load (e.g. infinite scroll). */ function onThumbsAdded(cb) { thumbsAddedListeners.add(cb); return () => { thumbsAddedListeners.delete(cb); }; } /** Notify subscribers that new thumb nodes exist under `root`. */ function notifyThumbsAdded(root) { for (const listener of thumbsAddedListeners) listener(root); } function findFeature(id) { return FEATURES.find((feature) => feature.id === id); } function isFeatureEnabled(id) { const feature = findFeature(id); if (feature === void 0) return false; return getFeatureEnabled(id, feature.defaultEnabled); } function getFeatureChoice(id) { const feature = findFeature(id); if (feature?.choice === void 0) return ""; const stored = getFeatureChoiceValue(id); if (stored !== void 0 && feature.choice.options.some((option) => option.value === stored)) return stored; return feature.choice.defaultValue; } function ensureFeatureCss(feature) { const styleId = `${FEATURE_STYLE_ID_PREFIX}${feature.id}`; if (document.getElementById(styleId) !== null) return; const style = document.createElement("style"); style.id = styleId; style.textContent = feature.css; document.head.append(style); } function createContext(feature, pageKind, search) { return { pageKind, search, getState: (parse) => { return parse(getFeatureState(feature.id)); }, setState: (value) => { setFeatureState(feature.id, value); } }; } function resolvePageContext() { if (activePageKind !== null) return { pageKind: activePageKind, search: activeSearch }; return { pageKind: detectPageKind(window.location.search), search: window.location.search }; } function clearChoiceBodyClasses(feature) { if (feature.choice === void 0) return; for (const option of feature.choice.options) document.body.classList.remove(featureChoiceBodyClass(feature.id, option.value)); } function mountFeatureOnce(feature) { if (mountedIds.has(feature.id)) return; const { pageKind, search } = resolvePageContext(); if (!feature.pages.includes(pageKind)) return; mountedIds.add(feature.id); try { feature.mount(createContext(feature, pageKind, search)); } catch (error) { log.error(`Feature mount failed: ${feature.id}`, error); } } /** * Body class + feature CSS + mount once. Used by layout-before-paint and runtime. * Records the id in mountedIds so deferred runFeatures will not remount. */ function applyFeatureChrome(feature, pageKind, search, options = {}) { if (mountedIds.has(feature.id)) return; if (!feature.pages.includes(pageKind)) return; activePageKind = pageKind; activeSearch = search; document.body.classList.add(featureBodyClass(feature.id)); if (feature.choice !== void 0) { const choiceValue = options.choiceValue ?? (() => { const stored = getFeatureChoiceValue(feature.id); if (stored !== void 0 && feature.choice.options.some((option) => option.value === stored)) return stored; return feature.choice.defaultValue; })(); clearChoiceBodyClasses(feature); document.body.classList.add(featureChoiceBodyClass(feature.id, choiceValue)); } ensureFeatureCss(feature); mountedIds.add(feature.id); try { feature.mount(createContext(feature, pageKind, search)); } catch (error) { log.error(`Feature mount failed: ${feature.id}`, error); } } /** * Live-apply a cssOnly feature enable/disable: body classes + CSS injection. * Mounts once if not yet mounted when enabling. Does not remount on re-enable. */ function applyCssOnlyFeatureEnabled(id, enabled) { const feature = findFeature(id); if (feature?.cssOnly !== true) return; if (!getTweaksEnabled()) return; if (!enabled) { document.body.classList.remove(featureBodyClass(feature.id)); clearChoiceBodyClasses(feature); return; } ensureFeatureCss(feature); document.body.classList.add(featureBodyClass(feature.id)); if (feature.choice !== void 0) { clearChoiceBodyClasses(feature); document.body.classList.add(featureChoiceBodyClass(feature.id, getFeatureChoice(feature.id))); } mountFeatureOnce(feature); } /** * Live-apply a cssOnly feature choice: swap body.rdw-f-- classes. */ function applyCssOnlyFeatureChoice(id, value) { const feature = findFeature(id); if (feature?.cssOnly !== true || feature.choice === void 0) return; if (!getTweaksEnabled()) return; if (!getFeatureEnabled(id, feature.defaultEnabled)) return; ensureFeatureCss(feature); clearChoiceBodyClasses(feature); document.body.classList.add(featureChoiceBodyClass(feature.id, value)); } /** Zero-delay yield so the browser can paint / handle input between mounts. */ function yieldToMain() { return new Promise((resolve) => { setTimeout(resolve, 0); }); } /** * Mount remaining features one-by-one, yielding to the main thread between each. * Skips ids already mounted during layout-before-paint. */ async function runFeaturesYielding(pageKind, search, features = FEATURES) { activePageKind = pageKind; activeSearch = search; if (!getTweaksEnabled()) return; for (const feature of features) { if (mountedIds.has(feature.id)) continue; if (!feature.pages.includes(pageKind)) continue; if (!getFeatureEnabled(feature.id, feature.defaultEnabled)) continue; applyFeatureChrome(feature, pageKind, search); await yieldToMain(); } } /** The preview image of a thumb, whatever classes the page gave it. */ var THUMB_IMAGE_SELECTOR = ":scope > a > img"; /** The class the site itself puts on the preview image of a video on a search page. */ var SITE_VIDEO_IMAGE_CLASS = "webm-thumb"; var VIDEO_TAG = "video"; /** `video` as the last tag of a title, after the site cut its last character. */ var VIDEO_TAG_CUT = "vide"; var TAG_SEPARATOR = /\s+/; /** True when the tag list in a thumb `title` names the post a video. */ function titleSaysVideo(title) { const tags = title.trim().split(TAG_SEPARATOR); if (tags.includes(VIDEO_TAG)) return true; return tags[tags.length - 1] === VIDEO_TAG_CUT; } /** * Marks the video thumbs among the `thumbSelector` elements under `root`; * returns how many it marked. */ function markVideoThumbs(root, thumbSelector) { let marked = 0; for (const thumb of root.querySelectorAll(thumbSelector)) { const img = thumb.querySelector(THUMB_IMAGE_SELECTOR); if (!(img instanceof HTMLImageElement) || !(img.classList.contains(SITE_VIDEO_IMAGE_CLASS) || titleSaysVideo(img.title))) continue; thumb.classList.add(THUMB_CLASS, VIDEO_THUMB_CLASS); marked += 1; } return marked; } /** * Marks the video thumbs on the page and those added to it later. On a * search page the site's own class on the image says which are videos; on * the favorites page only the tag list does. */ function mountVideoMarks(thumbSelector = SITE_SELECTORS.thumb) { markVideoThumbs(document, thumbSelector); onThumbsAdded((root) => { markVideoThumbs(root, thumbSelector); }); } /** Favorites page: marks the thumbs on the page and those added to it later. */ function mountFavoriteVideoMarks() { mountVideoMarks(SITE_SELECTORS.thumb); } /** * Animated GIFs get a small "GIF" label on the preview: the site marks them * only with the `animated_gif` tag, and nothing on a thumbnail tells them from * a still picture. The label is a pseudo-element of the thumb, outside the * link, placed against the picture by its anchor. */ var GIF_THUMB_CLASS = "rdw-gif-thumb"; var GIF_TAG = "animated_gif"; /** The tag as the first or the last one of a favorites title, cut by the site. */ var GIF_TAG_CUT_START = "nimated_gif"; var GIF_TAG_CUT_END = "animated_gi"; var GIF_STYLE_ID = "rdw-gif-thumb-style"; var GIF_LABEL = "GIF"; var GIF_INSET_PX = 6; var GIF_THUMB_CSS = ` ${BASE_GRID_CSS.trim()} .${GIF_THUMB_CLASS}::after { content: "${GIF_LABEL}";${THUMB_LABEL_RULES} } @supports (anchor-name: --a) { .${GIF_THUMB_CLASS}::after { position-anchor: ${THUMB_ANCHOR_NAME}; left: calc(anchor(left) + ${String(GIF_INSET_PX)}px); bottom: calc(anchor(bottom) + ${String(GIF_INSET_PX)}px); } html.${FAVORITES_PAGE_CLASS} .${GIF_THUMB_CLASS}::after { position-anchor: ${FAVORITE_IMAGE_ANCHOR_NAME}; } } `.trim(); /** True when the tag list in a thumb `title` names the post an animated GIF. */ function titleSaysGif(title) { const tags = title.trim().split(TAG_SEPARATOR); return tags.includes(GIF_TAG) || tags[0] === GIF_TAG_CUT_START || tags[tags.length - 1] === GIF_TAG_CUT_END; } /** Marks the GIF thumbs among the `thumbSelector` elements under `root`. */ function markGifThumbs(root, thumbSelector) { let marked = 0; for (const thumb of root.querySelectorAll(thumbSelector)) { const img = thumb.querySelector(THUMB_IMAGE_SELECTOR); if (!(img instanceof HTMLImageElement) || !titleSaysGif(img.title)) continue; thumb.classList.add(THUMB_CLASS, GIF_THUMB_CLASS); marked += 1; } return marked; } /** Marks the GIF thumbs on the page and those added to it later. */ function mountGifMarks(thumbSelector) { if (document.getElementById(GIF_STYLE_ID) === null) { const style = document.createElement("style"); style.id = GIF_STYLE_ID; style.textContent = GIF_THUMB_CSS; document.head.append(style); } markGifThumbs(document, thumbSelector); onThumbsAdded((root) => { markGifThumbs(root, thumbSelector); }); } /** * Site chrome CSS for html.rdw-skin (light / dark / custom themes). * Colors only via --rdw-* tokens. Does not change .thumb 200×200 cell size. * Injected via applyAppearanceTheme → injectSiteSkinHook(getSiteSkinCss()). */ var ROOT = `html.${RDW_SKIN_CLASS}`; /** The site's Favorites page only (see FAVORITES_PAGE_CLASS). */ var ROOT_FAVORITES = `${ROOT}.${FAVORITES_PAGE_CLASS}`; var ROOT_DARK = `${ROOT}[${RDW_THEME_ATTR}="${APPEARANCE_THEME_DARK}"]`; var ROOT_SITE = `html[${RDW_THEME_ATTR}="${APPEARANCE_THEME_SITE}"]`; var ROOT_SITE_DARK = `html[${RDW_THEME_ATTR}="${APPEARANCE_THEME_SITE_DARK}"]`; var ROOT_THEME_DARK = `html[${RDW_THEME_ATTR}="${APPEARANCE_THEME_DARK}"]`; /** search-tools mount root (id + class in src/features/search-tools.tsx). */ var SEARCH_TOOLS_ROOT_ID$1 = "rdw-search-tools"; /** Reset control class (src/features/search-tools.tsx). */ /** Exclude our light-DOM controls from site button/input chrome. */ /** Height of the site's own text fields and selects, next to its buttons. */ var SITE_CONTROL_MIN_HEIGHT_PX = 30; /** Widest a comment or forum post grows before the line gets too long to read. */ var COMMENT_MAX_WIDTH_PX = 1100; /** The least width a preview on Comments is drawn at; a narrower one is cropped to it. */ var COMMENT_THUMB_MIN_WIDTH_PX = 96; /** Anchor of a favorites preview, visible to the Remove link beside its thumb. */ var FAV_REMOVE_ANCHOR_NAME = FAVORITE_IMAGE_ANCHOR_NAME; var FAV_REMOVE_INSET_PX = 6; /** The same square as the buttons on a Posts thumb. */ var FAV_REMOVE_SIZE_PX = 28; var FAV_REMOVE_ICON_PX = 16; /** A bin, drawn as a mask so that it takes the colour of the rule. */ var FAV_REMOVE_ICON_MASK = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M3 6h18'/%3E%3Cpath d='M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6'/%3E%3Cpath d='M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2'/%3E%3Cpath d='M10 11v6'/%3E%3Cpath d='M14 11v6'/%3E%3C/svg%3E") center / contain no-repeat`; /** Above the hover video preview. */ var FAV_REMOVE_Z_INDEX = 4; var ACCOUNT_CARD_MAX_WIDTH_PX = 640; var HELP_CARD_MIN_WIDTH_PX = 220; /** * Same exclusions as :not…:not…, but :where() zeros their specificity so an * ID-bearing :not cannot outrank accent rules like div.tag-search submit. */ var WHERE_NOT_OUR_CONTROL = `:where(:not([class*="rdw-"])${`:not(#${SEARCH_TOOLS_ROOT_ID$1} *)`})`; /** * Body class Package E sets only while the post panel host is mounted * (`POST_PANEL_MOUNTED_CLASS` in post-actions.ts). */ var RDW_POST_PANEL_MOUNTED_CLASS = "rdw-post-panel-mounted"; /** Native "I came" counter row — hide with panel chrome (E HANDOFF). */ var POST_PANEL_ICAME_ROW = "li:has(a[onclick^=\"iCame(\"])"; /** Post panel host id — keep in sync with POST_ACTIONS_ID in features/types.ts. */ var POST_ACTIONS_HOST_ID = "rdw-post-actions"; /** Kit select list — keep in sync with src/ui/kit/select.tsx. */ var KIT_SELECT_LIST_CLASS = "rdw-select__list"; /** Kit autocomplete list — keep in sync with src/ui/kit/autocomplete-field.tsx. */ var KIT_AC_LIST_CLASS = "rdw-ac__list"; /** Kit dialog panel — keep in sync with src/ui/kit/dialog.tsx. */ var KIT_DIALOG_CLASS = "rdw-dialog"; /** Playlist add-to menu — keep in sync with src/features/playlist-menu.ts. */ var PLAYLIST_MENU_CLASS = "rdw-playlist-menu"; /** Firefox / modern Chromium thin scrollbar (E HANDOFF). */ var SCROLLBAR_WIDTH = "thin"; /** Post panel Original control — keep in sync with post-actions ORIGINAL_BUTTON_SIZE_PX. */ var POST_PANEL_ORIGINAL_SIZE_PX = 34; /** Active tab underline — keep in sync with kit/tabs.tsx. */ var POST_PANEL_TAB_UNDERLINE_PX = 2; /** Post panel classes — keep in sync with src/features/post-panel/post-panel.tsx. */ var POST_PANEL_ACTIONS_CLASS = "rdw-post-panel-actions"; var POST_PANEL_ACTIONS_ROW_CLASS = "rdw-post-panel-actions-row"; var POST_PANEL_FAV_CLASS = "rdw-post-panel-fav"; var POST_PANEL_ORIGINAL_CLASS = "rdw-post-panel-original"; var POST_PANEL_TABPANEL_CLASS = "rdw-post-panel-tabpanel"; var POST_PANEL_POST_ACTION_CLASS = "rdw-post-panel-post-action"; /** Kit tabs — keep in sync with src/ui/kit/tabs.tsx. */ var KIT_TABS_CLASS = "rdw-tabs"; var KIT_TAB_CLASS = "rdw-tabs__tab"; var KIT_BTN_PRIMARY_CLASS = "rdw-btn--primary"; /** * Body class while search-tools «AI posts» row is rendered * (`SEARCH_TOOLS_AI_ROW_BODY_CLASS` in search-tools.tsx — F HANDOFF). */ var SEARCH_TOOLS_AI_ROW_BODY_CLASS = "rdw-search-tools-ai-posts"; /** F bulk-select chrome — keep in sync with src/features/favorites-bulk.tsx. */ var FAV_BULK_SELECTED_CLASS = "rdw-fav-bulk-selected"; var FAV_BULK_CHECK_CLASS = "rdw-fav-bulk-check"; var FAV_BULK_ROOT_ID = "rdw-favorites-bulk"; var FAV_BULK_BAR_CLASS = "rdw-favorites-bulk-bar"; var FAV_BULK_STATUS_CLASS = "rdw-favorites-bulk-status"; /** Body class while selection mode is active (featureBodyClass + "-selecting"). */ var FAV_BULK_SELECTING_BODY_CLASS = "rdw-f-favorites-bulk-selecting"; var FAV_BULK_OUTLINE_WIDTH = "2px"; var FAV_BULK_OUTLINE_OFFSET = "2px"; var FAV_BULK_CHECK_SIZE = "1.25rem"; var FAV_BULK_CHECK_INSET = "0.25rem"; var FAV_BULK_CHECK_Z_INDEX = 2; var FAV_BULK_CHECK_FONT_SIZE = "0.75rem"; /** * The image upload form: found by the fields it holds, so that another form * in the same box is not laid out by these rules. Classes the script adds * are in upload-page.ts. */ var UPLOAD = `${ROOT} div#upload-form:has(#fileUpload):has(#tags)`; var UPLOAD_DRAG_CLASS = "rdw-upload-drag"; var UPLOAD_HAS_FILE_CLASS = "rdw-upload-has-file"; var UPLOAD_FILE_NAME_CLASS = "rdw-upload-file-name"; var UPLOAD_PREVIEW_CLASS = "rdw-upload-preview"; var UPLOAD_HINT_CLASS = "rdw-upload-hint"; var UPLOAD_NOTE_CLASS = "rdw-upload-note"; var NOTICE_GONE_CLASS = "rdw-notice-gone"; var UPLOAD_REMOVE_CLASS = "rdw-upload-remove"; var UPLOAD_PREVIEW_BOX_CLASS = "rdw-upload-preview-box"; var UPLOAD_CROSS_MASK = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M18 6 6 18'/%3E%3Cpath d='m6 6 12 12'/%3E%3C/svg%3E\") center / contain no-repeat"; var UPLOAD_TAG_COUNT_CLASS = "rdw-upload-tag-count"; var UPLOAD_TAG_COUNT_SHORT_CLASS = "rdw-upload-tag-count--short"; var UPLOAD_GUIDE_TOGGLE_CLASS = "rdw-upload-guide-toggle"; var UPLOAD_GUIDE_FOLDED_CLASS = "rdw-upload-guide-folded"; var UPLOAD_ICON_MASK = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4'/%3E%3Cpolyline points='17 8 12 3 7 8'/%3E%3Cline x1='12' x2='12' y1='3' y2='15'/%3E%3C/svg%3E\") center / contain no-repeat"; /** The forum: the list of topics, and one topic. Classes the script adds are in list-pages.ts. */ var FORUM_LIST = `${ROOT} div#forum:not(.response-list)`; var FORUM_TOPIC = `${ROOT} div#forum.response-list`; var FORUM_MARKED_ROW_CLASS = "rdw-forum-row-marked"; var FORUM_ONLY_NEW_CLASS = "rdw-forum-only-new"; var FORUM_TOOLBAR_CLASS = "rdw-forum-toolbar"; var FORUM_PIN_CLASS = "rdw-forum-pin"; var FORUM_NO_VALUE_CLASS = "rdw-forum-no-value"; var FORUM_UNIT_ATTRIBUTE = "data-rdw-unit"; var FORUM_SEARCH_FORM_CLASS = "rdw-forum-search"; var FORUM_SEARCH_CLEAR_CLASS = "rdw-forum-search-clear"; var FORUM_SEARCH_MASK = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Ccircle cx='11' cy='11' r='8'/%3E%3Cpath d='m21 21-4.3-4.3'/%3E%3C/svg%3E\") center / contain no-repeat"; var FORUM_CLEAR_MASK = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M18 6 6 18'/%3E%3Cpath d='m6 6 12 12'/%3E%3C/svg%3E\") center / 14px no-repeat"; var FORUM_PIN_MASK = "url(\"data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M12 17v5'/%3E%3Cpath d='M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z'/%3E%3C/svg%3E\") center / contain no-repeat"; var v = { bg: `var(${TOKEN_VAR.bg})`, surface: `var(${TOKEN_VAR.surface})`, surface2: `var(${TOKEN_VAR.surface2})`, border: `var(${TOKEN_VAR.border})`, text: `var(${TOKEN_VAR.text})`, muted: `var(${TOKEN_VAR.muted})`, accent: `var(${TOKEN_VAR.accent})`, accentSoft: `var(${TOKEN_VAR.accentSoft})`, danger: `var(${TOKEN_VAR.danger})`, dangerSoft: `var(${TOKEN_VAR.dangerSoft})`, tagArtist: `var(${TOKEN_VAR.tagArtist})`, tagCharacter: `var(${TOKEN_VAR.tagCharacter})`, tagCopyright: `var(${TOKEN_VAR.tagCopyright})`, tagMetadata: `var(${TOKEN_VAR.tagMetadata})`, radiusS: `var(${TOKEN_VAR.radiusS})`, radiusM: `var(${TOKEN_VAR.radiusM})`, radiusL: `var(${TOKEN_VAR.radiusL})`, shadow1: `var(${TOKEN_VAR.shadow1})`, shadow2: `var(${TOKEN_VAR.shadow2})`, font: `var(${TOKEN_VAR.font})` }; /** Full site-skin stylesheet (empty until injected by boot). */ var SITE_SKIN_CSS = ` /* —— base —— */ ${ROOT} body { font-family: ${v.font}; font-size: 13px; line-height: 1.4; background: ${v.bg}; color: ${v.text}; } ${ROOT} body, ${ROOT} body div, ${ROOT} body h1, ${ROOT} body h2, ${ROOT} body h3, ${ROOT} body h4, ${ROOT} body h5, ${ROOT} body h6, ${ROOT} body p, ${ROOT} body ul, ${ROOT} body li, ${ROOT} body dd, ${ROOT} body dt, ${ROOT} body input, ${ROOT} body select, ${ROOT} body button, ${ROOT} body textarea { font-family: ${v.font}; } /* A visited link looks like any other link: one colour for links on a page. */ ${ROOT} a:link, ${ROOT} a:visited { color: ${v.accent}; text-decoration: none; } ${ROOT} a:hover, ${ROOT} a:active { color: ${v.text}; text-decoration: none; } /* * My Account: "Logout" is not a link but a form button dressed as a heading, *