// ==UserScript==
// @name Cotrans Manga/Image Translator (Regular Edition)
// @name:zh-CN Cotrans 漫画/图片翻译器 (常规版)
// @namespace https://cotrans.touhou.ai/userscript/#regular
// @version 0.8.0-bata.9
// @description (WIP) Translate texts in images on Pixiv, Twitter
// @description:zh-CN (WIP) 一键翻译图片内文字,支持 Pixiv、Twitter
// @author QiroNT
// @license GPL-3.0
// @contributionURL https://ko-fi.com/voilelabs
// @supportURL https://discord.gg/975FRV8ca6
// @source https://cotrans.touhou.ai/
// @include http*://www.pixiv.net/*
// @match http://www.pixiv.net/
// @include http*://twitter.com/*
// @match http://twitter.com/
// @connect pixiv.net
// @connect pximg.net
// @connect twitter.com
// @connect twimg.com
// @connect api.cotrans.touhou.ai
// @connect cotrans-r2.moe.ci
// @connect *
// @grant GM.xmlHttpRequest
// @grant GM_xmlhttpRequest
// @grant GM.setValue
// @grant GM_setValue
// @grant GM.getValue
// @grant GM_getValue
// @grant GM.deleteValue
// @grant GM_deleteValue
// @grant GM.addValueChangeListener
// @grant GM_addValueChangeListener
// @grant GM.removeValueChangeListener
// @grant GM_removeValueChangeListener
// @grant window.onurlchange
// @run-at document-idle
// ==/UserScript==
/* eslint-disable no-undef, unused-imports/no-unused-vars */
const VERSION = '0.8.0-bata.9'
const EDITION = 'regular'
let GMP
{
// polyfill functions
const GMPFunctionMap = {
xmlHttpRequest: typeof GM_xmlhttpRequest !== 'undefined' ? GM_xmlhttpRequest : undefined,
setValue: typeof GM_setValue !== 'undefined' ? GM_setValue : undefined,
getValue: typeof GM_getValue !== 'undefined' ? GM_getValue : undefined,
deleteValue: typeof GM_deleteValue !== 'undefined' ? GM_deleteValue : undefined,
addValueChangeListener: typeof GM_addValueChangeListener !== 'undefined' ? GM_addValueChangeListener : undefined,
removeValueChangeListener: typeof GM_removeValueChangeListener !== 'undefined' ? GM_removeValueChangeListener : undefined,
}
const xmlHttpRequest = GM.xmlHttpRequest.bind(GM) || GMPFunctionMap.xmlHttpRequest
GMP = new Proxy(GM, {
get(target, prop) {
if (prop === 'xmlHttpRequest') {
return (context) => {
return new Promise((resolve, reject) => {
xmlHttpRequest({
...context,
onload(event) {
context.onload?.()
resolve(event)
},
onerror(event) {
context.onerror?.()
reject(event)
},
})
})
}
}
if (prop in target) {
const v = target[prop]
return typeof v === 'function' ? v.bind(target) : v
}
if (prop in GMPFunctionMap && typeof GMPFunctionMap[prop] === 'function')
return GMPFunctionMap[prop]
console.error(`[Cotrans Manga Translator] GM.${prop} isn't supported in your userscript engine and it's required by this script. This may lead to unexpected behavior.`)
},
})
}
(function () {
'use strict';
var i=new Map([["align-self","-ms-grid-row-align"],["color-adjust","-webkit-print-color-adjust"],["column-gap","grid-column-gap"],["forced-color-adjust","-ms-high-contrast-adjust"],["gap","grid-gap"],["grid-template-columns","-ms-grid-columns"],["grid-template-rows","-ms-grid-rows"],["justify-self","-ms-grid-column-align"],["margin-inline-end","-webkit-margin-end"],["margin-inline-start","-webkit-margin-start"],["mask-border","-webkit-mask-box-image"],["mask-border-outset","-webkit-mask-box-image-outset"],["mask-border-slice","-webkit-mask-box-image-slice"],["mask-border-source","-webkit-mask-box-image-source"],["mask-border-repeat","-webkit-mask-box-image-repeat"],["mask-border-width","-webkit-mask-box-image-width"],["overflow-wrap","word-wrap"],["padding-inline-end","-webkit-padding-end"],["padding-inline-start","-webkit-padding-start"],["print-color-adjust","color-adjust"],["row-gap","grid-row-gap"],["scroll-margin-bottom","scroll-snap-margin-bottom"],["scroll-margin-left","scroll-snap-margin-left"],["scroll-margin-right","scroll-snap-margin-right"],["scroll-margin-top","scroll-snap-margin-top"],["scroll-margin","scroll-snap-margin"],["text-combine-upright","-ms-text-combine-horizontal"]]);function r(r){return i.get(r)}function a(i){var r=/^(?:(text-(?:decoration$|e|or|si)|back(?:ground-cl|d|f)|box-d|mask(?:$|-[ispro]|-cl)|pr|hyphena|flex-d)|(tab-|column(?!-s)|text-align-l)|(ap)|u|hy)/i.exec(i);return r?r[1]?1:r[2]?2:r[3]?3:5:0}function t$1(i,r){var a=/^(?:(pos)|(cli)|(background-i)|(flex(?:$|-b)|(?:max-|min-)?(?:block-s|inl|he|widt))|dis)/i.exec(i);return a?a[1]?/^sti/i.test(r)?1:0:a[2]?/^pat/i.test(r)?1:0:a[3]?/^image-/i.test(r)?1:0:a[4]?"-"===r[3]?2:0:/^(?:inline-)?grid$/i.test(r)?4:0:0}
// src/internal/util.ts
var includes = (value, search) => !!~value.indexOf(search);
var join = (parts, separator = "-") => parts.join(separator);
var joinTruthy = (parts, separator) => join(parts.filter(Boolean), separator);
var tail = (array, startIndex = 1) => array.slice(startIndex);
var identity = value => value;
var noop = () => {};
var capitalize = value => value[0].toUpperCase() + tail(value);
var hyphenate = value => value.replace(/[A-Z]/g, "-$&").toLowerCase();
var evalThunk = (value, context) => {
while (typeof value == "function") {
value = value(context);
}
return value;
};
var ensureMaxSize = (map, max) => {
if (map.size > max) {
map.delete(map.keys().next().value);
}
};
var isCSSProperty = (key, value) => !includes("@:&", key[0]) && (includes("rg", (typeof value)[5]) || Array.isArray(value));
var merge = (target, source, context) => source ? Object.keys(source).reduce((target2, key) => {
const value = evalThunk(source[key], context);
if (isCSSProperty(key, value)) {
target2[hyphenate(key)] = value;
} else {
target2[key] = key[0] == "@" && includes("figa", key[1]) ? (target2[key] || []).concat(value) : merge(target2[key] || {}, value, context);
}
return target2;
}, target) : target;
var escape = typeof CSS !== "undefined" && CSS.escape || (className => className.replace(/[!"'`*+.,;:\\/<=>?@#$%&^|~()[\]{}]/g, "\\$&").replace(/^\d/, "\\3$& "));
var buildMediaQuery = screen => {
if (!Array.isArray(screen)) {
screen = [screen];
}
return "@media " + join(screen.map(screen2 => {
if (typeof screen2 == "string") {
screen2 = {
min: screen2
};
}
return screen2.raw || join(Object.keys(screen2).map(feature => `(${feature}-width:${screen2[feature]})`), " and ");
}), ",");
};
var cyrb32 = value => {
for (var h = 9, index = value.length; index--;) {
h = Math.imul(h ^ value.charCodeAt(index), 1597334677);
}
return "tw-" + ((h ^ h >>> 9) >>> 0).toString(36);
};
var sortedInsertionIndex = (array, element) => {
for (var low = 0, high = array.length; low < high;) {
const pivot = high + low >> 1;
if (array[pivot] <= element) {
low = pivot + 1;
} else {
high = pivot;
}
}
return high;
};
// src/twind/parse.ts
var groupings;
var rules;
var startGrouping = (value = "") => {
groupings.push(value);
return "";
};
var endGrouping = isWhitespace => {
groupings.length = Math.max(groupings.lastIndexOf("") + ~~isWhitespace, 0);
};
var onlyPrefixes = s => s && !includes("!:", s[0]);
var onlyVariants = s => s[0] == ":";
var addRule = (directive2, negate) => {
rules.push({
v: groupings.filter(onlyVariants),
d: directive2,
n: negate,
i: includes(groupings, "!"),
$: ""
});
};
var saveRule = buffer => {
const negate = buffer[0] == "-";
if (negate) {
buffer = tail(buffer);
}
const prefix = join(groupings.filter(onlyPrefixes));
addRule(buffer == "&" ? prefix : (prefix && prefix + "-") + buffer, negate);
return "";
};
var parseString = (token, isVariant) => {
let buffer = "";
for (let char, dynamic = false, position2 = 0; char = token[position2++];) {
if (dynamic || char == "[") {
buffer += char;
dynamic = char != "]";
continue;
}
switch (char) {
case ":":
buffer = buffer && startGrouping(":" + (token[position2] == char ? token[position2++] : "") + buffer);
break;
case "(":
buffer = buffer && startGrouping(buffer);
startGrouping();
break;
case "!":
startGrouping(char);
break;
case ")":
case " ":
case " ":
case "\n":
case "\r":
buffer = buffer && saveRule(buffer);
endGrouping(char !== ")");
break;
default:
buffer += char;
}
}
if (buffer) {
if (isVariant) {
startGrouping(":" + buffer);
} else if (buffer.slice(-1) == "-") {
startGrouping(buffer.slice(0, -1));
} else {
saveRule(buffer);
}
}
};
var parseGroupedToken = token => {
startGrouping();
parseToken(token);
endGrouping();
};
var parseGroup = (key, token) => {
if (token) {
startGrouping();
const isVariant = includes("tbu", (typeof token)[1]);
parseString(key, isVariant);
if (isVariant) {
parseGroupedToken(token);
}
endGrouping();
}
};
var parseToken = token => {
switch (typeof token) {
case "string":
parseString(token);
break;
case "function":
addRule(token);
break;
case "object":
if (Array.isArray(token)) {
token.forEach(parseGroupedToken);
} else if (token) {
Object.keys(token).forEach(key => {
parseGroup(key, token[key]);
});
}
}
};
var staticsCaches = new WeakMap();
var buildStatics = strings => {
let statics = staticsCaches.get(strings);
if (!statics) {
let slowModeIndex = NaN;
let buffer = "";
statics = strings.map((token, index) => {
if (slowModeIndex !== slowModeIndex && (token.slice(-1) == "[" || includes(":-(", (strings[index + 1] || "")[0]))) {
slowModeIndex = index;
}
if (index >= slowModeIndex) {
return interpolation => {
if (index == slowModeIndex) {
buffer = "";
}
buffer += token;
if (includes("rg", (typeof interpolation)[5])) {
buffer += interpolation;
} else if (interpolation) {
parseString(buffer);
buffer = "";
parseToken(interpolation);
}
if (index == strings.length - 1) {
parseString(buffer);
}
};
}
const staticRules = rules = [];
parseString(token);
const activeGroupings = [...groupings];
rules = [];
return interpolation => {
rules.push(...staticRules);
groupings = [...activeGroupings];
if (interpolation) {
parseToken(interpolation);
}
};
});
staticsCaches.set(strings, statics);
}
return statics;
};
var parse = tokens => {
groupings = [];
rules = [];
if (Array.isArray(tokens[0]) && Array.isArray(tokens[0].raw)) {
buildStatics(tokens[0]).forEach((apply2, index) => apply2(tokens[index + 1]));
} else {
parseToken(tokens);
}
return rules;
};
// src/twind/directive.ts
var isFunctionFree;
var detectFunction = (key, value) => {
if (typeof value == "function") {
isFunctionFree = false;
}
return value;
};
var stringify = data => {
isFunctionFree = true;
const key = JSON.stringify(data, detectFunction);
return isFunctionFree && key;
};
var cacheByFactory = new WeakMap();
var directive = (factory, data) => {
const key = stringify(data);
let directive2;
if (key) {
var cache = cacheByFactory.get(factory);
if (!cache) {
cacheByFactory.set(factory, cache = new Map());
}
directive2 = cache.get(key);
}
if (!directive2) {
directive2 = Object.defineProperty((params, context) => {
context = Array.isArray(params) ? context : params;
return evalThunk(factory(data, context), context);
}, "toJSON", {
value: () => key || data
});
if (cache) {
cache.set(key, directive2);
ensureMaxSize(cache, 1e4);
}
}
return directive2;
};
// src/twind/apply.ts
var applyFactory = (tokens, {
css
}) => css(parse(tokens));
var apply = (...tokens) => directive(applyFactory, tokens);
// src/twind/helpers.ts
var positions = resolve => (value, position2, prefix, suffix) => {
if (value) {
const properties = position2 && resolve(position2);
if (properties && properties.length > 0) {
return properties.reduce((declarations, property2) => {
declarations[joinTruthy([prefix, property2, suffix])] = value;
return declarations;
}, {});
}
}
};
var corners = /* @__PURE__ */positions(key => ({
t: ["top-left", "top-right"],
r: ["top-right", "bottom-right"],
b: ["bottom-left", "bottom-right"],
l: ["bottom-left", "top-left"],
tl: ["top-left"],
tr: ["top-right"],
bl: ["bottom-left"],
br: ["bottom-right"]
})[key]);
var expandEdges = key => {
const parts = ({
x: "lr",
y: "tb"
}[key] || key || "").split("").sort();
for (let index = parts.length; index--;) {
if (!(parts[index] = {
t: "top",
r: "right",
b: "bottom",
l: "left"
}[parts[index]])) return;
}
if (parts.length) return parts;
};
var edges = /* @__PURE__ */positions(expandEdges);
var stringifyVariant = (selector, variant) => selector + (variant[1] == ":" ? tail(variant, 2) + ":" : tail(variant)) + ":";
var stringifyRule = (rule, directive2 = rule.d) => typeof directive2 == "function" ? "" : rule.v.reduce(stringifyVariant, "") + (rule.i ? "!" : "") + (rule.n ? "-" : "") + directive2;
// src/twind/plugins.ts
var _;
var __;
var $;
var toColumnsOrRows = x => x == "cols" ? "columns" : "rows";
var property = property2 => (params, context, id) => ({
[property2]: id + ((_ = join(params)) && "-" + _)
});
var propertyValue = (property2, separator) => (params, context, id) => (_ = join(params, separator)) && {
[property2 || id]: _
};
var themeProperty = section => (params, {
theme: theme2
}, id) => (_ = theme2(section || id, params)) && {
[section || id]: _
};
var themePropertyFallback = (section, separator) => (params, {
theme: theme2
}, id) => (_ = theme2(section || id, params, join(params, separator))) && {
[section || id]: _
};
var alias = (handler, name) => (params, context) => handler(params, context, name);
var display = property("display");
var position = property("position");
var textTransform = property("textTransform");
var textDecoration = property("textDecoration");
var fontStyle = property("fontStyle");
var fontVariantNumeric = key => (params, context, id) => ({
["--tw-" + key]: id,
fontVariantNumeric: "var(--tw-ordinal,/*!*/ /*!*/) var(--tw-slashed-zero,/*!*/ /*!*/) var(--tw-numeric-figure,/*!*/ /*!*/) var(--tw-numeric-spacing,/*!*/ /*!*/) var(--tw-numeric-fraction,/*!*/ /*!*/)"
});
var inset = (params, {
theme: theme2
}, id) => (_ = theme2("inset", params)) && {
[id]: _
};
var opacityProperty = (params, theme2, id, section = id) => (_ = theme2(section + "Opacity", tail(params))) && {
[`--tw-${id}-opacity`]: _
};
var parseColorComponent = (chars, factor) => Math.round(parseInt(chars, 16) * factor);
var asRGBA = (color, opacityProperty2, opacityDefault) => {
if (color && color[0] == "#" && (_ = (color.length - 1) / 3) && ($ = [17, 1, 0.062272][_ - 1])) {
return `rgba(${parseColorComponent(color.substr(1, _), $)},${parseColorComponent(color.substr(1 + _, _), $)},${parseColorComponent(color.substr(1 + 2 * _, _), $)},${opacityProperty2 ? `var(--tw-${opacityProperty2}${opacityDefault ? "," + opacityDefault : ""})` : opacityDefault || 1})`;
}
return color;
};
var withOpacityFallback = (property2, kind, color) => color && typeof color == "string" ? (_ = asRGBA(color, kind + "-opacity")) && _ !== color ? {
[`--tw-${kind}-opacity`]: "1",
[property2]: [color, _]
} : {
[property2]: color
} : void 0;
var transparentTo = color => ($ = asRGBA(color, "", "0")) == _ ? "transparent" : $;
var reversableEdge = (params, {
theme: theme2
}, id, section, prefix, suffix) => (_ = {
x: ["right", "left"],
y: ["bottom", "top"]
}[params[0]]) && ($ = `--tw-${id}-${params[0]}-reverse`) ? params[1] == "reverse" ? {
[$]: "1"
} : {
[$]: "0",
[joinTruthy([prefix, _[0], suffix])]: (__ = theme2(section, tail(params))) && `calc(${__} * var(${$}))`,
[joinTruthy([prefix, _[1], suffix])]: __ && [__, `calc(${__} * calc(1 - var(${$})))`]
} : void 0;
var placeHelper = (property2, params) => params[0] && {
[property2]: (includes("wun", (params[0] || "")[3]) ? "space-" : "") + params[0]
};
var contentPluginFor = property2 => params => includes(["start", "end"], params[0]) ? {
[property2]: "flex-" + params[0]
} : placeHelper(property2, params);
var gridPlugin = kind => (params, {
theme: theme2
}) => {
if (_ = theme2("grid" + capitalize(kind), params, "")) {
return {
["grid-" + kind]: _
};
}
switch (params[0]) {
case "span":
return params[1] && {
["grid-" + kind]: `span ${params[1]} / span ${params[1]}`
};
case "start":
case "end":
return (_ = theme2("grid" + capitalize(kind) + capitalize(params[0]), tail(params), join(tail(params)))) && {
[`grid-${kind}-${params[0]}`]: _
};
}
};
var border = (params, {
theme: theme2
}, id) => {
switch (params[0]) {
case "solid":
case "dashed":
case "dotted":
case "double":
case "none":
return propertyValue("borderStyle")(params);
case "collapse":
case "separate":
return propertyValue("borderCollapse")(params);
case "opacity":
return opacityProperty(params, theme2, id);
}
return (_ = theme2(id + "Width", params, "")) ? {
borderWidth: _
} : withOpacityFallback("borderColor", id, theme2(id + "Color", params));
};
var borderEdges = (params, context, id) => {
var _a;
const edges2 = (_a = expandEdges(params[0])) == null ? void 0 : _a.map(capitalize);
if (edges2) {
params = tail(params);
}
let rules2 = border(params, context, id);
if (edges2 && rules2 && typeof rules2 === "object") {
rules2 = Object.entries(rules2).reduce((newRules, [key, value]) => {
if (key.startsWith("border")) {
for (const edge of edges2) {
newRules[key.slice(0, 6) + edge + key.slice(6)] = value;
}
} else {
newRules[key] = value;
}
return newRules;
}, {});
}
return rules2;
};
var transform = gpu => (gpu ? "translate3d(var(--tw-translate-x,0),var(--tw-translate-y,0),0)" : "translateX(var(--tw-translate-x,0)) translateY(var(--tw-translate-y,0))") + " rotate(var(--tw-rotate,0)) skewX(var(--tw-skew-x,0)) skewY(var(--tw-skew-y,0)) scaleX(var(--tw-scale-x,1)) scaleY(var(--tw-scale-y,1))";
var transformXYFunction = (params, context, id) => params[0] && (_ = context.theme(id, params[1] || params[0])) && {
[`--tw-${id}-x`]: params[0] !== "y" && _,
[`--tw-${id}-y`]: params[0] !== "x" && _,
transform: [`${id}${params[1] ? params[0].toUpperCase() : ""}(${_})`, transform()]
};
var edgesPluginFor = key => (params, context, id) => id[1] ? edges(context.theme(key, params), id[1], key) : themeProperty(key)(params, context, id);
var padding = edgesPluginFor("padding");
var margin = edgesPluginFor("margin");
var minMax = (params, {
theme: theme2
}, id) => (_ = {
w: "width",
h: "height"
}[params[0]]) && {
[_ = `${id}${capitalize(_)}`]: theme2(_, tail(params))
};
var filter = (params, {
theme: theme2
}, id) => {
const parts = id.split("-");
const prefix = parts[0] == "backdrop" ? parts[0] + "-" : "";
if (!prefix) {
params.unshift(...parts);
}
if (params[0] == "filter") {
const filters = ["blur", "brightness", "contrast", "grayscale", "hue-rotate", "invert", prefix && "opacity", "saturate", "sepia", !prefix && "drop-shadow"].filter(Boolean);
return params[1] == "none" ? {
[prefix + "filter"]: "none"
} : filters.reduce((css, key) => {
css["--tw-" + prefix + key] = "var(--tw-empty,/*!*/ /*!*/)";
return css;
}, {
[prefix + "filter"]: filters.map(key => `var(--tw-${prefix}${key})`).join(" ")
});
}
$ = params.shift();
if (includes(["hue", "drop"], $)) $ += capitalize(params.shift());
return (_ = theme2(prefix ? "backdrop" + capitalize($) : $, params)) && {
["--tw-" + prefix + $]: (Array.isArray(_) ? _ : [_]).map(_4 => `${hyphenate($)}(${_4})`).join(" ")
};
};
var corePlugins = {
group: (params, {
tag
}, id) => tag(join([id, ...params])),
hidden: alias(display, "none"),
inline: display,
block: display,
contents: display,
flow: display,
table: (params, context, id) => includes(["auto", "fixed"], params[0]) ? {
tableLayout: params[0]
} : display(params, context, id),
flex(params, context, id) {
switch (params[0]) {
case "row":
case "col":
return {
flexDirection: join(params[0] == "col" ? ["column", ...tail(params)] : params)
};
case "nowrap":
case "wrap":
return {
flexWrap: join(params)
};
case "grow":
case "shrink":
_ = context.theme("flex" + capitalize(params[0]), tail(params), params[1] || 1);
return _ != null && {
["flex-" + params[0]]: "" + _
};
}
return (_ = context.theme("flex", params, "")) ? {
flex: _
} : display(params, context, id);
},
grid(params, context, id) {
switch (params[0]) {
case "cols":
case "rows":
return (_ = context.theme("gridTemplate" + capitalize(toColumnsOrRows(params[0])), tail(params), params.length == 2 && Number(params[1]) ? `repeat(${params[1]},minmax(0,1fr))` : join(tail(params)))) && {
["gridTemplate-" + toColumnsOrRows(params[0])]: _
};
case "flow":
return params.length > 1 && {
gridAutoFlow: join(params[1] == "col" ? ["column", ...tail(params, 2)] : tail(params), " ")
};
}
return display(params, context, id);
},
auto: (params, {
theme: theme2
}) => includes(["cols", "rows"], params[0]) && (_ = theme2("gridAuto" + capitalize(toColumnsOrRows(params[0])), tail(params), join(tail(params)))) && {
["gridAuto-" + toColumnsOrRows(params[0])]: _
},
static: position,
fixed: position,
absolute: position,
relative: position,
sticky: position,
visible: {
visibility: "visible"
},
invisible: {
visibility: "hidden"
},
antialiased: {
WebkitFontSmoothing: "antialiased",
MozOsxFontSmoothing: "grayscale"
},
"subpixel-antialiased": {
WebkitFontSmoothing: "auto",
MozOsxFontSmoothing: "auto"
},
truncate: {
overflow: "hidden",
whiteSpace: "nowrap",
textOverflow: "ellipsis"
},
"sr-only": {
position: "absolute",
width: "1px",
height: "1px",
padding: "0",
margin: "-1px",
overflow: "hidden",
whiteSpace: "nowrap",
clip: "rect(0,0,0,0)",
borderWidth: "0"
},
"not-sr-only": {
position: "static",
width: "auto",
height: "auto",
padding: "0",
margin: "0",
overflow: "visible",
whiteSpace: "normal",
clip: "auto"
},
resize: params => ({
resize: {
x: "horizontal",
y: "vertical"
}[params[0]] || params[0] || "both"
}),
box: params => params[0] && {
boxSizing: params[0] + "-box"
},
appearance: propertyValue(),
cursor: themePropertyFallback(),
float: propertyValue(),
clear: propertyValue(),
decoration: propertyValue("boxDecorationBreak"),
isolate: {
isolation: "isolate"
},
isolation: propertyValue(),
"mix-blend": propertyValue("mixBlendMode"),
top: inset,
right: inset,
bottom: inset,
left: inset,
inset: (params, {
theme: theme2
}) => (_ = expandEdges(params[0])) ? edges(theme2("inset", tail(params)), params[0]) : (_ = theme2("inset", params)) && {
top: _,
right: _,
bottom: _,
left: _
},
underline: textDecoration,
"line-through": textDecoration,
"no-underline": alias(textDecoration, "none"),
"text-underline": alias(textDecoration, "underline"),
"text-no-underline": alias(textDecoration, "none"),
"text-line-through": alias(textDecoration, "line-through"),
uppercase: textTransform,
lowercase: textTransform,
capitalize: textTransform,
"normal-case": alias(textTransform, "none"),
"text-normal-case": alias(textTransform, "none"),
italic: fontStyle,
"not-italic": alias(fontStyle, "normal"),
"font-italic": alias(fontStyle, "italic"),
"font-not-italic": alias(fontStyle, "normal"),
font: (params, context, id) => (_ = context.theme("fontFamily", params, "")) ? {
fontFamily: _
} : themeProperty("fontWeight")(params, context, id),
items: params => params[0] && {
alignItems: includes(["start", "end"], params[0]) ? "flex-" + params[0] : join(params)
},
"justify-self": propertyValue(),
"justify-items": propertyValue(),
justify: contentPluginFor("justifyContent"),
content: contentPluginFor("alignContent"),
self: contentPluginFor("alignSelf"),
place: params => params[0] && placeHelper("place-" + params[0], tail(params)),
overscroll: params => params[0] && {
["overscrollBehavior" + (params[1] ? "-" + params[0] : "")]: params[1] || params[0]
},
col: gridPlugin("column"),
row: gridPlugin("row"),
duration: themeProperty("transitionDuration"),
delay: themeProperty("transitionDelay"),
tracking: themeProperty("letterSpacing"),
leading: themeProperty("lineHeight"),
z: themeProperty("zIndex"),
opacity: themeProperty(),
ease: themeProperty("transitionTimingFunction"),
p: padding,
py: padding,
px: padding,
pt: padding,
pr: padding,
pb: padding,
pl: padding,
m: margin,
my: margin,
mx: margin,
mt: margin,
mr: margin,
mb: margin,
ml: margin,
w: themeProperty("width"),
h: themeProperty("height"),
min: minMax,
max: minMax,
fill: themeProperty(),
order: themeProperty(),
origin: themePropertyFallback("transformOrigin", " "),
select: propertyValue("userSelect"),
"pointer-events": propertyValue(),
align: propertyValue("verticalAlign"),
whitespace: propertyValue("whiteSpace"),
"normal-nums": {
fontVariantNumeric: "normal"
},
ordinal: fontVariantNumeric("ordinal"),
"slashed-zero": fontVariantNumeric("slashed-zero"),
"lining-nums": fontVariantNumeric("numeric-figure"),
"oldstyle-nums": fontVariantNumeric("numeric-figure"),
"proportional-nums": fontVariantNumeric("numeric-spacing"),
"tabular-nums": fontVariantNumeric("numeric-spacing"),
"diagonal-fractions": fontVariantNumeric("numeric-fraction"),
"stacked-fractions": fontVariantNumeric("numeric-fraction"),
overflow: (params, context, id) => includes(["ellipsis", "clip"], params[0]) ? propertyValue("textOverflow")(params) : params[1] ? {
["overflow-" + params[0]]: params[1]
} : propertyValue()(params, context, id),
transform: params => params[0] == "none" ? {
transform: "none"
} : {
"--tw-translate-x": "0",
"--tw-translate-y": "0",
"--tw-rotate": "0",
"--tw-skew-x": "0",
"--tw-skew-y": "0",
"--tw-scale-x": "1",
"--tw-scale-y": "1",
transform: transform(params[0] == "gpu")
},
rotate: (params, {
theme: theme2
}) => (_ = theme2("rotate", params)) && {
"--tw-rotate": _,
transform: [`rotate(${_})`, transform()]
},
scale: transformXYFunction,
translate: transformXYFunction,
skew: transformXYFunction,
gap: (params, context, id) => (_ = {
x: "column",
y: "row"
}[params[0]]) ? {
[_ + "Gap"]: context.theme("gap", tail(params))
} : themeProperty("gap")(params, context, id),
stroke: (params, context, id) => (_ = context.theme("stroke", params, "")) ? {
stroke: _
} : themeProperty("strokeWidth")(params, context, id),
outline: (params, {
theme: theme2
}) => (_ = theme2("outline", params)) && {
outline: _[0],
outlineOffset: _[1]
},
"break-normal": {
wordBreak: "normal",
overflowWrap: "normal"
},
"break-words": {
overflowWrap: "break-word"
},
"break-all": {
wordBreak: "break-all"
},
text(params, {
theme: theme2
}, id) {
switch (params[0]) {
case "left":
case "center":
case "right":
case "justify":
return {
textAlign: params[0]
};
case "uppercase":
case "lowercase":
case "capitalize":
return textTransform([], _, params[0]);
case "opacity":
return opacityProperty(params, theme2, id);
}
const fontSize = theme2("fontSize", params, "");
if (fontSize) {
return typeof fontSize == "string" ? {
fontSize
} : {
fontSize: fontSize[0],
...(typeof fontSize[1] == "string" ? {
lineHeight: fontSize[1]
} : fontSize[1])
};
}
return withOpacityFallback("color", "text", theme2("textColor", params));
},
bg(params, {
theme: theme2
}, id) {
switch (params[0]) {
case "fixed":
case "local":
case "scroll":
return propertyValue("backgroundAttachment", ",")(params);
case "bottom":
case "center":
case "left":
case "right":
case "top":
return propertyValue("backgroundPosition", " ")(params);
case "no":
return params[1] == "repeat" && propertyValue("backgroundRepeat")(params);
case "repeat":
return includes("xy", params[1]) ? propertyValue("backgroundRepeat")(params) : {
backgroundRepeat: params[1] || params[0]
};
case "opacity":
return opacityProperty(params, theme2, id, "background");
case "clip":
case "origin":
return params[1] && {
["background-" + params[0]]: params[1] + (params[1] == "text" ? "" : "-box")
};
case "blend":
return propertyValue("background-blend-mode")(tail(params));
case "gradient":
if (params[1] == "to" && (_ = expandEdges(params[2]))) {
return {
backgroundImage: `linear-gradient(to ${join(_, " ")},var(--tw-gradient-stops))`
};
}
}
return (_ = theme2("backgroundPosition", params, "")) ? {
backgroundPosition: _
} : (_ = theme2("backgroundSize", params, "")) ? {
backgroundSize: _
} : (_ = theme2("backgroundImage", params, "")) ? {
backgroundImage: _
} : withOpacityFallback("backgroundColor", "bg", theme2("backgroundColor", params));
},
from: (params, {
theme: theme2
}) => (_ = theme2("gradientColorStops", params)) && {
"--tw-gradient-from": _,
"--tw-gradient-stops": `var(--tw-gradient-from),var(--tw-gradient-to,${transparentTo(_)})`
},
via: (params, {
theme: theme2
}) => (_ = theme2("gradientColorStops", params)) && {
"--tw-gradient-stops": `var(--tw-gradient-from),${_},var(--tw-gradient-to,${transparentTo(_)})`
},
to: (params, {
theme: theme2
}) => (_ = theme2("gradientColorStops", params)) && {
"--tw-gradient-to": _
},
border: borderEdges,
divide: (params, context, id) => (_ = reversableEdge(params, context, id, "divideWidth", "border", "width") || border(params, context, id)) && {
"&>:not([hidden])~:not([hidden])": _
},
space: (params, context, id) => (_ = reversableEdge(params, context, id, "space", "margin")) && {
"&>:not([hidden])~:not([hidden])": _
},
placeholder: (params, {
theme: theme2
}, id) => (_ = params[0] == "opacity" ? opacityProperty(params, theme2, id) : withOpacityFallback("color", "placeholder", theme2("placeholderColor", params))) && {
"&::placeholder": _
},
shadow: (params, {
theme: theme2
}) => (_ = theme2("boxShadow", params)) && {
":global": {
"*": {
"--tw-shadow": "0 0 transparent"
}
},
"--tw-shadow": _ == "none" ? "0 0 transparent" : _,
boxShadow: [_, `var(--tw-ring-offset-shadow,0 0 transparent),var(--tw-ring-shadow,0 0 transparent),var(--tw-shadow)`]
},
animate: (params, {
theme: theme2,
tag
}) => {
if ($ = theme2("animation", params)) {
const parts = $.split(" ");
if ((_ = theme2("keyframes", parts[0], __ = {})) !== __) {
return ($ = tag(parts[0])) && {
animation: $ + " " + join(tail(parts), " "),
["@keyframes " + $]: _
};
}
return {
animation: $
};
}
},
ring(params, {
theme: theme2
}, id) {
switch (params[0]) {
case "inset":
return {
"--tw-ring-inset": "inset"
};
case "opacity":
return opacityProperty(params, theme2, id);
case "offset":
return (_ = theme2("ringOffsetWidth", tail(params), "")) ? {
"--tw-ring-offset-width": _
} : {
"--tw-ring-offset-color": theme2("ringOffsetColor", tail(params))
};
}
return (_ = theme2("ringWidth", params, "")) ? {
"--tw-ring-offset-shadow": `var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)`,
"--tw-ring-shadow": `var(--tw-ring-inset) 0 0 0 calc(${_} + var(--tw-ring-offset-width)) var(--tw-ring-color)`,
boxShadow: `var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow,0 0 transparent)`,
":global": {
"*": {
"--tw-ring-inset": "var(--tw-empty,/*!*/ /*!*/)",
"--tw-ring-offset-width": theme2("ringOffsetWidth", "", "0px"),
"--tw-ring-offset-color": theme2("ringOffsetColor", "", "#fff"),
"--tw-ring-color": asRGBA(theme2("ringColor", "", "#93c5fd"), "ring-opacity", theme2("ringOpacity", "", "0.5")),
"--tw-ring-offset-shadow": "0 0 transparent",
"--tw-ring-shadow": "0 0 transparent"
}
}
} : {
"--tw-ring-opacity": "1",
"--tw-ring-color": asRGBA(theme2("ringColor", params), "ring-opacity")
};
},
object: (params, context, id) => includes(["contain", "cover", "fill", "none", "scale-down"], join(params)) ? {
objectFit: join(params)
} : themePropertyFallback("objectPosition", " ")(params, context, id),
list: (params, context, id) => join(params) == "item" ? display(params, context, id) : includes(["inside", "outside"], join(params)) ? {
listStylePosition: params[0]
} : themePropertyFallback("listStyleType")(params, context, id),
rounded: (params, context, id) => corners(context.theme("borderRadius", tail(params), ""), params[0], "border", "radius") || themeProperty("borderRadius")(params, context, id),
"transition-none": {
transitionProperty: "none"
},
transition: (params, {
theme: theme2
}) => ({
transitionProperty: theme2("transitionProperty", params),
transitionTimingFunction: theme2("transitionTimingFunction", ""),
transitionDuration: theme2("transitionDuration", "")
}),
container: (params, {
theme: theme2
}) => {
const {
screens = theme2("screens"),
center,
padding: padding2
} = theme2("container");
const paddingFor = screen => (_ = padding2 && (typeof padding2 == "string" ? padding2 : padding2[screen] || padding2.DEFAULT)) ? {
paddingRight: _,
paddingLeft: _
} : {};
return Object.keys(screens).reduce((rules2, screen) => {
if (($ = screens[screen]) && typeof $ == "string") {
rules2[buildMediaQuery($)] = {
"&": {
"max-width": $,
...paddingFor(screen)
}
};
}
return rules2;
}, {
width: "100%",
...(center ? {
marginRight: "auto",
marginLeft: "auto"
} : {}),
...paddingFor("xs")
});
},
filter,
blur: filter,
brightness: filter,
contrast: filter,
grayscale: filter,
"hue-rotate": filter,
invert: filter,
saturate: filter,
sepia: filter,
"drop-shadow": filter,
backdrop: filter
};
// src/twind/preflight.ts
var createPreflight = theme2 => ({
":root": {
tabSize: 4
},
"body,blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre,fieldset,ol,ul": {
margin: "0"
},
button: {
backgroundColor: "transparent",
backgroundImage: "none"
},
'button,[type="button"],[type="reset"],[type="submit"]': {
WebkitAppearance: "button"
},
"button:focus": {
outline: ["1px dotted", "5px auto -webkit-focus-ring-color"]
},
"fieldset,ol,ul,legend": {
padding: "0"
},
"ol,ul": {
listStyle: "none"
},
html: {
lineHeight: "1.5",
WebkitTextSizeAdjust: "100%",
fontFamily: theme2("fontFamily.sans", "ui-sans-serif,system-ui,sans-serif")
},
body: {
fontFamily: "inherit",
lineHeight: "inherit"
},
"*,::before,::after": {
boxSizing: "border-box",
border: `0 solid ${theme2("borderColor.DEFAULT", "currentColor")}`
},
hr: {
height: "0",
color: "inherit",
borderTopWidth: "1px"
},
img: {
borderStyle: "solid"
},
textarea: {
resize: "vertical"
},
"input::placeholder,textarea::placeholder": {
opacity: "1",
color: theme2("placeholderColor.DEFAULT", theme2("colors.gray.400", "#a1a1aa"))
},
'button,[role="button"]': {
cursor: "pointer"
},
table: {
textIndent: "0",
borderColor: "inherit",
borderCollapse: "collapse"
},
"h1,h2,h3,h4,h5,h6": {
fontSize: "inherit",
fontWeight: "inherit"
},
a: {
color: "inherit",
textDecoration: "inherit"
},
"button,input,optgroup,select,textarea": {
fontFamily: "inherit",
fontSize: "100%",
margin: "0",
padding: "0",
lineHeight: "inherit",
color: "inherit"
},
"button,select": {
textTransform: "none"
},
"::-moz-focus-inner": {
borderStyle: "none",
padding: "0"
},
":-moz-focusring": {
outline: "1px dotted ButtonText"
},
":-moz-ui-invalid": {
boxShadow: "none"
},
progress: {
verticalAlign: "baseline"
},
"::-webkit-inner-spin-button,::-webkit-outer-spin-button": {
height: "auto"
},
'[type="search"]': {
WebkitAppearance: "textfield",
outlineOffset: "-2px"
},
"::-webkit-search-decoration": {
WebkitAppearance: "none"
},
"::-webkit-file-upload-button": {
WebkitAppearance: "button",
font: "inherit"
},
summary: {
display: "list-item"
},
"abbr[title]": {
textDecoration: "underline dotted"
},
"b,strong": {
fontWeight: "bolder"
},
"pre,code,kbd,samp": {
fontFamily: theme2("fontFamily", "mono", "ui-monospace,monospace"),
fontSize: "1em"
},
"sub,sup": {
fontSize: "75%",
lineHeight: "0",
position: "relative",
verticalAlign: "baseline"
},
sub: {
bottom: "-0.25em"
},
sup: {
top: "-0.5em"
},
"img,svg,video,canvas,audio,iframe,embed,object": {
display: "block",
verticalAlign: "middle"
},
"img,video": {
maxWidth: "100%",
height: "auto"
}
});
// src/twind/variants.ts
var coreVariants = {
dark: "@media (prefers-color-scheme:dark)",
sticky: "@supports ((position: -webkit-sticky) or (position:sticky))",
"motion-reduce": "@media (prefers-reduced-motion:reduce)",
"motion-safe": "@media (prefers-reduced-motion:no-preference)",
first: "&:first-child",
last: "&:last-child",
even: "&:nth-child(2n)",
odd: "&:nth-child(odd)",
children: "&>*",
siblings: "&~*",
sibling: "&+*",
override: "&&"
};
// src/internal/dom.ts
var STYLE_ELEMENT_ID = "__twind";
var getStyleElement = nonce => {
let element = self[STYLE_ELEMENT_ID];
if (!element) {
element = document.head.appendChild(document.createElement("style"));
element.id = STYLE_ELEMENT_ID;
nonce && (element.nonce = nonce);
element.appendChild(document.createTextNode(""));
}
return element;
};
// src/twind/sheets.ts
var cssomSheet = ({
nonce,
target = getStyleElement(nonce).sheet
} = {}) => {
const offset = target.cssRules.length;
return {
target,
insert: (rule, index) => target.insertRule(rule, offset + index)
};
};
var voidSheet = () => ({
target: null,
insert: noop
});
// src/twind/modes.ts
var mode = report => ({
unknown(section, key = [], optional, context) {
if (!optional) {
this.report({
id: "UNKNOWN_THEME_VALUE",
key: section + "." + join(key)
}, context);
}
},
report({
id,
...info
}) {
return report(`[${id}] ${JSON.stringify(info)}`);
}
});
var warn = /* @__PURE__ */mode(message => console.warn(message));
var strict = /* @__PURE__ */mode(message => {
throw new Error(message);
});
var silent = /* @__PURE__ */mode(noop);
var noprefix = (property2, value, important) => `${property2}:${value}${important ? " !important" : ""}`;
var autoprefix = (property2, value, important) => {
let cssText = "";
const propertyAlias = r(property2);
if (propertyAlias) cssText += `${noprefix(propertyAlias, value, important)};`;
let flags = a(property2);
if (flags & 1) cssText += `-webkit-${noprefix(property2, value, important)};`;
if (flags & 2) cssText += `-moz-${noprefix(property2, value, important)};`;
if (flags & 4) cssText += `-ms-${noprefix(property2, value, important)};`;
flags = t$1(property2, value);
if (flags & 1) cssText += `${noprefix(property2, `-webkit-${value}`, important)};`;
if (flags & 2) cssText += `${noprefix(property2, `-moz-${value}`, important)};`;
if (flags & 4) cssText += `${noprefix(property2, `-ms-${value}`, important)};`;
cssText += noprefix(property2, value, important);
return cssText;
};
// src/twind/theme.ts
var ratios = (start, end) => {
const result = {};
do {
for (let dividend = 1; dividend < start; dividend++) {
result[`${dividend}/${start}`] = Number((dividend / start * 100).toFixed(6)) + "%";
}
} while (++start <= end);
return result;
};
var exponential = (stop, unit, start = 0) => {
const result = {};
for (; start <= stop; start = start * 2 || 1) {
result[start] = start + unit;
}
return result;
};
var linear = (stop, unit = "", divideBy = 1, start = 0, step = 1, result = {}) => {
for (; start <= stop; start += step) {
result[start] = start / divideBy + unit;
}
return result;
};
var alias2 = section => theme2 => theme2(section);
var defaultTheme = {
screens: {
sm: "640px",
md: "768px",
lg: "1024px",
xl: "1280px",
"2xl": "1536px"
},
colors: {
transparent: "transparent",
current: "currentColor",
black: "#000",
white: "#fff",
gray: {
50: "#f9fafb",
100: "#f3f4f6",
200: "#e5e7eb",
300: "#d1d5db",
400: "#9ca3af",
500: "#6b7280",
600: "#4b5563",
700: "#374151",
800: "#1f2937",
900: "#111827"
},
red: {
50: "#fef2f2",
100: "#fee2e2",
200: "#fecaca",
300: "#fca5a5",
400: "#f87171",
500: "#ef4444",
600: "#dc2626",
700: "#b91c1c",
800: "#991b1b",
900: "#7f1d1d"
},
yellow: {
50: "#fffbeb",
100: "#fef3c7",
200: "#fde68a",
300: "#fcd34d",
400: "#fbbf24",
500: "#f59e0b",
600: "#d97706",
700: "#b45309",
800: "#92400e",
900: "#78350f"
},
green: {
50: "#ecfdf5",
100: "#d1fae5",
200: "#a7f3d0",
300: "#6ee7b7",
400: "#34d399",
500: "#10b981",
600: "#059669",
700: "#047857",
800: "#065f46",
900: "#064e3b"
},
blue: {
50: "#eff6ff",
100: "#dbeafe",
200: "#bfdbfe",
300: "#93c5fd",
400: "#60a5fa",
500: "#3b82f6",
600: "#2563eb",
700: "#1d4ed8",
800: "#1e40af",
900: "#1e3a8a"
},
indigo: {
50: "#eef2ff",
100: "#e0e7ff",
200: "#c7d2fe",
300: "#a5b4fc",
400: "#818cf8",
500: "#6366f1",
600: "#4f46e5",
700: "#4338ca",
800: "#3730a3",
900: "#312e81"
},
purple: {
50: "#f5f3ff",
100: "#ede9fe",
200: "#ddd6fe",
300: "#c4b5fd",
400: "#a78bfa",
500: "#8b5cf6",
600: "#7c3aed",
700: "#6d28d9",
800: "#5b21b6",
900: "#4c1d95"
},
pink: {
50: "#fdf2f8",
100: "#fce7f3",
200: "#fbcfe8",
300: "#f9a8d4",
400: "#f472b6",
500: "#ec4899",
600: "#db2777",
700: "#be185d",
800: "#9d174d",
900: "#831843"
}
},
spacing: {
px: "1px",
0: "0px",
... /* @__PURE__ */linear(4, "rem", 4, 0.5, 0.5),
... /* @__PURE__ */linear(12, "rem", 4, 5),
14: "3.5rem",
... /* @__PURE__ */linear(64, "rem", 4, 16, 4),
72: "18rem",
80: "20rem",
96: "24rem"
},
durations: {
75: "75ms",
100: "100ms",
150: "150ms",
200: "200ms",
300: "300ms",
500: "500ms",
700: "700ms",
1e3: "1000ms"
},
animation: {
none: "none",
spin: "spin 1s linear infinite",
ping: "ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",
pulse: "pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",
bounce: "bounce 1s infinite"
},
backdropBlur: /* @__PURE__ */alias2("blur"),
backdropBrightness: /* @__PURE__ */alias2("brightness"),
backdropContrast: /* @__PURE__ */alias2("contrast"),
backdropGrayscale: /* @__PURE__ */alias2("grayscale"),
backdropHueRotate: /* @__PURE__ */alias2("hueRotate"),
backdropInvert: /* @__PURE__ */alias2("invert"),
backdropOpacity: /* @__PURE__ */alias2("opacity"),
backdropSaturate: /* @__PURE__ */alias2("saturate"),
backdropSepia: /* @__PURE__ */alias2("sepia"),
backgroundColor: /* @__PURE__ */alias2("colors"),
backgroundImage: {
none: "none"
},
backgroundOpacity: /* @__PURE__ */alias2("opacity"),
backgroundSize: {
auto: "auto",
cover: "cover",
contain: "contain"
},
blur: {
0: "0",
sm: "4px",
DEFAULT: "8px",
md: "12px",
lg: "16px",
xl: "24px",
"2xl": "40px",
"3xl": "64px"
},
brightness: {
... /* @__PURE__ */linear(200, "", 100, 0, 50),
... /* @__PURE__ */linear(110, "", 100, 90, 5),
75: "0.75",
125: "1.25"
},
borderColor: theme2 => ({
...theme2("colors"),
DEFAULT: theme2("colors.gray.200", "currentColor")
}),
borderOpacity: /* @__PURE__ */alias2("opacity"),
borderRadius: {
none: "0px",
sm: "0.125rem",
DEFAULT: "0.25rem",
md: "0.375rem",
lg: "0.5rem",
xl: "0.75rem",
"2xl": "1rem",
"3xl": "1.5rem",
"1/2": "50%",
full: "9999px"
},
borderWidth: {
DEFAULT: "1px",
... /* @__PURE__ */exponential(8, "px")
},
boxShadow: {
sm: "0 1px 2px 0 rgba(0,0,0,0.05)",
DEFAULT: "0 1px 3px 0 rgba(0,0,0,0.1), 0 1px 2px 0 rgba(0,0,0,0.06)",
md: "0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06)",
lg: "0 10px 15px -3px rgba(0,0,0,0.1), 0 4px 6px -2px rgba(0,0,0,0.05)",
xl: "0 20px 25px -5px rgba(0,0,0,0.1), 0 10px 10px -5px rgba(0,0,0,0.04)",
"2xl": "0 25px 50px -12px rgba(0,0,0,0.25)",
inner: "inset 0 2px 4px 0 rgba(0,0,0,0.06)",
none: "none"
},
contrast: {
... /* @__PURE__ */linear(200, "", 100, 0, 50),
75: "0.75",
125: "1.25"
},
divideColor: /* @__PURE__ */alias2("borderColor"),
divideOpacity: /* @__PURE__ */alias2("borderOpacity"),
divideWidth: /* @__PURE__ */alias2("borderWidth"),
dropShadow: {
sm: "0 1px 1px rgba(0,0,0,0.05)",
DEFAULT: ["0 1px 2px rgba(0,0,0,0.1)", "0 1px 1px rgba(0,0,0,0.06)"],
md: ["0 4px 3px rgba(0,0,0,0.07)", "0 2px 2px rgba(0,0,0,0.06)"],
lg: ["0 10px 8px rgba(0,0,0,0.04)", "0 4px 3px rgba(0,0,0,0.1)"],
xl: ["0 20px 13px rgba(0,0,0,0.03)", "0 8px 5px rgba(0,0,0,0.08)"],
"2xl": "0 25px 25px rgba(0,0,0,0.15)",
none: "0 0 #0000"
},
fill: {
current: "currentColor"
},
grayscale: {
0: "0",
DEFAULT: "100%"
},
hueRotate: {
0: "0deg",
15: "15deg",
30: "30deg",
60: "60deg",
90: "90deg",
180: "180deg"
},
invert: {
0: "0",
DEFAULT: "100%"
},
flex: {
1: "1 1 0%",
auto: "1 1 auto",
initial: "0 1 auto",
none: "none"
},
fontFamily: {
sans: 'ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji"'.split(","),
serif: 'ui-serif,Georgia,Cambria,"Times New Roman",Times,serif'.split(","),
mono: 'ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace'.split(",")
},
fontSize: {
xs: ["0.75rem", "1rem"],
sm: ["0.875rem", "1.25rem"],
base: ["1rem", "1.5rem"],
lg: ["1.125rem", "1.75rem"],
xl: ["1.25rem", "1.75rem"],
"2xl": ["1.5rem", "2rem"],
"3xl": ["1.875rem", "2.25rem"],
"4xl": ["2.25rem", "2.5rem"],
"5xl": ["3rem", "1"],
"6xl": ["3.75rem", "1"],
"7xl": ["4.5rem", "1"],
"8xl": ["6rem", "1"],
"9xl": ["8rem", "1"]
},
fontWeight: {
thin: "100",
extralight: "200",
light: "300",
normal: "400",
medium: "500",
semibold: "600",
bold: "700",
extrabold: "800",
black: "900"
},
gridTemplateColumns: {},
gridTemplateRows: {},
gridAutoColumns: {
min: "min-content",
max: "max-content",
fr: "minmax(0,1fr)"
},
gridAutoRows: {
min: "min-content",
max: "max-content",
fr: "minmax(0,1fr)"
},
gridColumn: {
auto: "auto",
"span-full": "1 / -1"
},
gridRow: {
auto: "auto",
"span-full": "1 / -1"
},
gap: /* @__PURE__ */alias2("spacing"),
gradientColorStops: /* @__PURE__ */alias2("colors"),
height: theme2 => ({
auto: "auto",
...theme2("spacing"),
...ratios(2, 6),
full: "100%",
screen: "100vh"
}),
inset: theme2 => ({
auto: "auto",
...theme2("spacing"),
...ratios(2, 4),
full: "100%"
}),
keyframes: {
spin: {
from: {
transform: "rotate(0deg)"
},
to: {
transform: "rotate(360deg)"
}
},
ping: {
"0%": {
transform: "scale(1)",
opacity: "1"
},
"75%,100%": {
transform: "scale(2)",
opacity: "0"
}
},
pulse: {
"0%,100%": {
opacity: "1"
},
"50%": {
opacity: ".5"
}
},
bounce: {
"0%, 100%": {
transform: "translateY(-25%)",
animationTimingFunction: "cubic-bezier(0.8,0,1,1)"
},
"50%": {
transform: "none",
animationTimingFunction: "cubic-bezier(0,0,0.2,1)"
}
}
},
letterSpacing: {
tighter: "-0.05em",
tight: "-0.025em",
normal: "0em",
wide: "0.025em",
wider: "0.05em",
widest: "0.1em"
},
lineHeight: {
none: "1",
tight: "1.25",
snug: "1.375",
normal: "1.5",
relaxed: "1.625",
loose: "2",
... /* @__PURE__ */linear(10, "rem", 4, 3)
},
margin: theme2 => ({
auto: "auto",
...theme2("spacing")
}),
maxHeight: theme2 => ({
...theme2("spacing"),
full: "100%",
screen: "100vh"
}),
maxWidth: (theme2, {
breakpoints
}) => ({
none: "none",
0: "0rem",
xs: "20rem",
sm: "24rem",
md: "28rem",
lg: "32rem",
xl: "36rem",
"2xl": "42rem",
"3xl": "48rem",
"4xl": "56rem",
"5xl": "64rem",
"6xl": "72rem",
"7xl": "80rem",
full: "100%",
min: "min-content",
max: "max-content",
prose: "65ch",
...breakpoints(theme2("screens"))
}),
minHeight: {
0: "0px",
full: "100%",
screen: "100vh"
},
minWidth: {
0: "0px",
full: "100%",
min: "min-content",
max: "max-content"
},
opacity: {
... /* @__PURE__ */linear(100, "", 100, 0, 10),
5: "0.05",
25: "0.25",
75: "0.75",
95: "0.95"
},
order: {
first: "-9999",
last: "9999",
none: "0",
... /* @__PURE__ */linear(12, "", 1, 1)
},
outline: {
none: ["2px solid transparent", "2px"],
white: ["2px dotted white", "2px"],
black: ["2px dotted black", "2px"]
},
padding: /* @__PURE__ */alias2("spacing"),
placeholderColor: /* @__PURE__ */alias2("colors"),
placeholderOpacity: /* @__PURE__ */alias2("opacity"),
ringColor: theme2 => ({
DEFAULT: theme2("colors.blue.500", "#3b82f6"),
...theme2("colors")
}),
ringOffsetColor: /* @__PURE__ */alias2("colors"),
ringOffsetWidth: /* @__PURE__ */exponential(8, "px"),
ringOpacity: theme2 => ({
DEFAULT: "0.5",
...theme2("opacity")
}),
ringWidth: {
DEFAULT: "3px",
... /* @__PURE__ */exponential(8, "px")
},
rotate: {
... /* @__PURE__ */exponential(2, "deg"),
... /* @__PURE__ */exponential(12, "deg", 3),
... /* @__PURE__ */exponential(180, "deg", 45)
},
saturate: /* @__PURE__ */linear(200, "", 100, 0, 50),
scale: {
... /* @__PURE__ */linear(150, "", 100, 0, 50),
... /* @__PURE__ */linear(110, "", 100, 90, 5),
75: "0.75",
125: "1.25"
},
sepia: {
0: "0",
DEFAULT: "100%"
},
skew: {
... /* @__PURE__ */exponential(2, "deg"),
... /* @__PURE__ */exponential(12, "deg", 3)
},
space: /* @__PURE__ */alias2("spacing"),
stroke: {
current: "currentColor"
},
strokeWidth: /* @__PURE__ */linear(2),
textColor: /* @__PURE__ */alias2("colors"),
textOpacity: /* @__PURE__ */alias2("opacity"),
transitionDuration: theme2 => ({
DEFAULT: "150ms",
...theme2("durations")
}),
transitionDelay: /* @__PURE__ */alias2("durations"),
transitionProperty: {
none: "none",
all: "all",
DEFAULT: "background-color,border-color,color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter",
colors: "background-color,border-color,color,fill,stroke",
opacity: "opacity",
shadow: "box-shadow",
transform: "transform"
},
transitionTimingFunction: {
DEFAULT: "cubic-bezier(0.4,0,0.2,1)",
linear: "linear",
in: "cubic-bezier(0.4,0,1,1)",
out: "cubic-bezier(0,0,0.2,1)",
"in-out": "cubic-bezier(0.4,0,0.2,1)"
},
translate: theme2 => ({
...theme2("spacing"),
...ratios(2, 4),
full: "100%"
}),
width: theme2 => ({
auto: "auto",
...theme2("spacing"),
...ratios(2, 6),
...ratios(12, 12),
screen: "100vw",
full: "100%",
min: "min-content",
max: "max-content"
}),
zIndex: {
auto: "auto",
... /* @__PURE__ */linear(50, "", 1, 0, 10)
}
};
var flattenColorPalette = (colors, target = {}, prefix = []) => {
Object.keys(colors).forEach(property2 => {
const value = colors[property2];
if (property2 == "DEFAULT") {
target[join(prefix)] = value;
target[join(prefix, ".")] = value;
}
const key = [...prefix, property2];
target[join(key)] = value;
target[join(key, ".")] = value;
if (value && typeof value == "object") {
flattenColorPalette(value, target, key);
}
}, target);
return target;
};
var resolveContext = {
negative: () => ({}),
breakpoints: screens => Object.keys(screens).filter(key => typeof screens[key] == "string").reduce((target, key) => {
target["screen-" + key] = screens[key];
return target;
}, {})
};
var handleArbitraryValues = (section, key) => (key = key[0] == "[" && key.slice(-1) == "]" && key.slice(1, -1)) && includes(section, "olor") == /^(#|(hsl|rgb)a?\(|[a-z]+$)/.test(key) && (includes(key, "calc(") ? key.replace(/(-?\d*\.?\d(?!\b-.+[,)](?![^+\-/*])\D)(?:%|[a-z]+)?|\))([+\-/*])/g, "$1 $2 ") : key);
var makeThemeResolver = config => {
const cache = new Map();
const theme2 = {
...defaultTheme,
...config
};
const deref = (theme3, section) => {
const base = theme3 && theme3[section];
const value = typeof base == "function" ? base(resolve, resolveContext) : base;
return value && section == "colors" ? flattenColorPalette(value) : value;
};
const resolve = (section, key, defaultValue) => {
const keypath = section.split(".");
section = keypath[0];
if (keypath.length > 1) {
defaultValue = key;
key = join(tail(keypath), ".");
}
let base = cache.get(section);
if (!base) {
cache.set(section, base = {
...deref(theme2, section)
});
Object.assign(base, deref(theme2.extend, section));
}
if (key != null) {
key = (Array.isArray(key) ? join(key) : key) || "DEFAULT";
const value = handleArbitraryValues(section, key) || base[key];
return value == null ? defaultValue : Array.isArray(value) && !includes(["fontSize", "outline", "dropShadow"], section) ? join(value, ",") : value;
}
return base;
};
return resolve;
};
// src/twind/translate.ts
var translate = (plugins, context) => (rule, isTranslating) => {
if (typeof rule.d == "function") {
return rule.d(context);
}
const parameters = rule.d.split(/-(?![^[]*])/g);
if (!isTranslating && parameters[0] == "tw" && rule.$ == rule.d) {
return rule.$;
}
for (let index = parameters.length; index; index--) {
const id = join(parameters.slice(0, index));
if (Object.prototype.hasOwnProperty.call(plugins, id)) {
const plugin = plugins[id];
return typeof plugin == "function" ? plugin(tail(parameters, index), context, id) : typeof plugin == "string" ? context[isTranslating ? "css" : "tw"](plugin) : plugin;
}
}
};
// src/twind/decorate.ts
var _2;
var GROUP_RE = /^:(group(?:(?!-focus).+?)*)-(.+)$/;
var NOT_PREFIX_RE = /^(:not)-(.+)/;
var prepareVariantSelector = variant => variant[1] == "[" ? tail(variant) : variant;
var decorate = (darkMode, variants, {
theme: theme2,
tag
}) => {
const applyVariant = (translation, variant) => {
if (_2 = theme2("screens", tail(variant), "")) {
return {
[buildMediaQuery(_2)]: translation
};
}
if (variant == ":dark" && darkMode == "class") {
return {
".dark &": translation
};
}
if (_2 = GROUP_RE.exec(variant)) {
return {
[`.${escape(tag(_2[1]))}:${_2[2]} &`]: translation
};
}
return {
[variants[tail(variant)] || "&" + variant.replace(NOT_PREFIX_RE, (_4, not, variant2) => not + "(" + prepareVariantSelector(":" + variant2) + ")")]: translation
};
};
return (translation, rule) => rule.v.reduceRight(applyVariant, translation);
};
// src/twind/presedence.ts
var _3;
var responsivePrecedence = css => (((_3 = /(?:^|min-width: *)(\d+(?:.\d+)?)(p)?/.exec(css)) ? +_3[1] / (_3[2] ? 15 : 1) / 10 : 0) & 31) << 22;
var seperatorPrecedence = string => {
_3 = 0;
for (let index = string.length; index--;) {
_3 += includes("-:,", string[index]);
}
return _3;
};
var atRulePresedence = css => (seperatorPrecedence(css) & 15) << 18;
var PRECEDENCES_BY_PSEUDO_CLASS = ["rst", "st", "en", "d", "nk", "sited", "pty", "ecked", "cus-w", "ver", "cus", "cus-v", "tive", "sable", "ad-on", "tiona", "quire"];
var pseudoPrecedence = pseudoClass => 1 << (~(_3 = PRECEDENCES_BY_PSEUDO_CLASS.indexOf(pseudoClass.replace(GROUP_RE, ":$2").slice(3, 8))) ? _3 : 17);
var makeVariantPresedenceCalculator = (theme2, variants) => (presedence, variant) => presedence | ((_3 = theme2("screens", tail(variant), "")) ? 1 << 27 | responsivePrecedence(buildMediaQuery(_3)) : variant == ":dark" ? 1 << 30 : (_3 = variants[variant] || variant.replace(NOT_PREFIX_RE, ":$2"))[0] == "@" ? atRulePresedence(_3) : pseudoPrecedence(variant));
var declarationPropertyPrecedence = property2 => property2[0] == "-" ? 0 : seperatorPrecedence(property2) + ((_3 = /^(?:(border-(?!w|c|sty)|[tlbr].{2,4}m?$|c.{7}$)|([fl].{5}l|g.{8}$|pl))/.exec(property2)) ? +!!_3[1] || -!!_3[2] : 0) + 1;
// src/twind/serialize.ts
var stringifyBlock = (body, selector) => selector + "{" + body + "}";
var serialize = (prefix, variants, context) => {
const {
theme: theme2,
tag
} = context;
const tagVar = (_4, property2) => "--" + tag(property2);
const tagVars = value => `${value}`.replace(/--(tw-[\w-]+)\b/g, tagVar);
const stringifyDeclaration = (property2, value, important) => {
property2 = tagVars(property2);
return Array.isArray(value) ? join(value.filter(Boolean).map(value2 => prefix(property2, tagVars(value2), important)), ";") : prefix(property2, tagVars(value), important);
};
let rules2;
const stringify2 = (atRules, selector, presedence, css, important) => {
if (Array.isArray(css)) {
css.forEach(css2 => css2 && stringify2(atRules, selector, presedence, css2, important));
return;
}
let declarations = "";
let maxPropertyPresedence = 0;
let numberOfDeclarations = 0;
if (css["@apply"]) {
css = merge(evalThunk(apply(css["@apply"]), context), {
...css,
"@apply": void 0
}, context);
}
Object.keys(css).forEach(key => {
const value = evalThunk(css[key], context);
if (isCSSProperty(key, value)) {
if (value !== "" && key.length > 1) {
const property2 = hyphenate(key);
numberOfDeclarations += 1;
maxPropertyPresedence = Math.max(maxPropertyPresedence, declarationPropertyPrecedence(property2));
declarations = (declarations && declarations + ";") + stringifyDeclaration(property2, value, important);
}
} else if (value) {
if (key == ":global") {
key = "@global";
}
if (key[0] == "@") {
if (key[1] == "g") {
stringify2([], "", 0, value, important);
} else if (key[1] == "f") {
stringify2([], key, 0, value, important);
} else if (key[1] == "k") {
const currentSize = rules2.length;
stringify2([], "", 0, value, important);
const waypoints = rules2.splice(currentSize, rules2.length - currentSize);
rules2.push({
r: stringifyBlock(join(waypoints.map(p => p.r), ""), key),
p: waypoints.reduce((sum, p) => sum + p.p, 0)
});
} else if (key[1] == "i") {
(Array.isArray(value) ? value : [value]).forEach(value2 => value2 && rules2.push({
p: 0,
r: `${key} ${value2};`
}));
} else {
if (key[2] == "c") {
key = buildMediaQuery(context.theme("screens", tail(key, 8).trim()));
}
stringify2([...atRules, key], selector, presedence | responsivePrecedence(key) | atRulePresedence(key), value, important);
}
} else {
stringify2(atRules, selector ? selector.replace(/ *((?:\(.+?\)|\[.+?\]|[^,])+) *(,|$)/g, (_4, selectorPart, comma) => key.replace(/ *((?:\(.+?\)|\[.+?\]|[^,])+) *(,|$)/g, (_5, keyPart, comma2) => (includes(keyPart, "&") ? keyPart.replace(/&/g, selectorPart) : (selectorPart && selectorPart + " ") + keyPart) + comma2) + comma) : key, presedence, value, important);
}
}
});
if (numberOfDeclarations) {
rules2.push({
r: atRules.reduceRight(stringifyBlock, stringifyBlock(declarations, selector)),
p: presedence * (1 << 8) + ((Math.max(0, 15 - numberOfDeclarations) & 15) << 4 | (maxPropertyPresedence || 15) & 15)
});
}
};
const variantPresedence = makeVariantPresedenceCalculator(theme2, variants);
return (css, className, rule, layer = 0) => {
layer <<= 28;
rules2 = [];
stringify2([], className ? "." + escape(className) : "", rule ? rule.v.reduceRight(variantPresedence, layer) : layer, css, rule && rule.i);
return rules2;
};
};
// src/twind/inject.ts
var inject = (sheet, mode2, init, context) => {
let sortedPrecedences;
init((value = []) => sortedPrecedences = value);
let insertedRules;
init((value = new Set()) => insertedRules = value);
return ({
r: css,
p: presedence
}) => {
if (!insertedRules.has(css)) {
insertedRules.add(css);
const index = sortedInsertionIndex(sortedPrecedences, presedence);
try {
sheet.insert(css, index);
sortedPrecedences.splice(index, 0, presedence);
} catch (error) {
if (!/:-[mwo]/.test(css)) {
mode2.report({
id: "INJECT_CSS_ERROR",
css,
error
}, context);
}
}
}
};
};
// src/twind/configure.ts
var sanitize = (value, defaultValue, disabled, enabled = defaultValue) => value === false ? disabled : value === true ? enabled : value || defaultValue;
var loadMode = mode2 => (typeof mode2 == "string" ? {
t: strict,
a: warn,
i: silent
}[mode2[1]] : mode2) || warn;
var COMPONENT_PROPS = {
_: {
value: "",
writable: true
}
};
var configure = (config = {}) => {
const theme2 = makeThemeResolver(config.theme);
const mode2 = loadMode(config.mode);
const hash = sanitize(config.hash, false, false, cyrb32);
const important = config.important;
let activeRule = {
v: []
};
let translateDepth = 0;
const lastTranslations = [];
const context = {
tw: (...tokens) => process(tokens),
theme: (section, key, defaultValue) => {
var _a;
const value = (_a = theme2(section, key, defaultValue)) != null ? _a : mode2.unknown(section, key == null || Array.isArray(key) ? key : key.split("."), defaultValue != null, context);
return activeRule.n && value && includes("rg", (typeof value)[5]) ? `calc(${value} * -1)` : value;
},
tag: value => hash ? hash(value) : value,
css: rules2 => {
translateDepth++;
const lastTranslationsIndex = lastTranslations.length;
try {
;
(typeof rules2 == "string" ? parse([rules2]) : rules2).forEach(convert);
const css = Object.create(null, COMPONENT_PROPS);
for (let index = lastTranslationsIndex; index < lastTranslations.length; index++) {
const translation = lastTranslations[index];
if (translation) {
switch (typeof translation) {
case "object":
merge(css, translation, context);
break;
case "string":
css._ += (css._ && " ") + translation;
}
}
}
return css;
} finally {
lastTranslations.length = lastTranslationsIndex;
translateDepth--;
}
}
};
const translate2 = translate({
...corePlugins,
...config.plugins
}, context);
const doTranslate = rule => {
const parentRule = activeRule;
activeRule = rule;
try {
return evalThunk(translate2(rule), context);
} finally {
activeRule = parentRule;
}
};
const variants = {
...coreVariants,
...config.variants
};
const decorate2 = decorate(config.darkMode || "media", variants, context);
const serialize2 = serialize(sanitize(config.prefix, autoprefix, noprefix), variants, context);
const sheet = config.sheet || (typeof window == "undefined" ? voidSheet() : cssomSheet(config));
const {
init = callback => callback()
} = sheet;
const inject2 = inject(sheet, mode2, init, context);
let idToClassName;
init((value = new Map()) => idToClassName = value);
const inlineDirectiveName = new WeakMap();
const evaluateFunctions = (key, value) => key == "_" ? void 0 : typeof value == "function" ? JSON.stringify(evalThunk(value, context), evaluateFunctions) : value;
const convert = rule => {
if (!translateDepth && activeRule.v.length) {
rule = {
...rule,
v: [...activeRule.v, ...rule.v],
$: ""
};
}
if (!rule.$) {
rule.$ = stringifyRule(rule, inlineDirectiveName.get(rule.d));
}
let className = translateDepth ? null : idToClassName.get(rule.$);
if (className == null) {
let translation = doTranslate(rule);
if (!rule.$) {
rule.$ = cyrb32(JSON.stringify(translation, evaluateFunctions));
inlineDirectiveName.set(rule.d, rule.$);
rule.$ = stringifyRule(rule, rule.$);
}
if (translation && typeof translation == "object") {
rule.v = rule.v.map(prepareVariantSelector);
if (important) rule.i = important;
translation = decorate2(translation, rule);
if (translateDepth) {
lastTranslations.push(translation);
} else {
const layer = typeof rule.d == "function" ? typeof translation._ == "string" ? 1 : 3 : 2;
className = hash || typeof rule.d == "function" ? (hash || cyrb32)(layer + rule.$) : rule.$;
serialize2(translation, className, rule, layer).forEach(inject2);
if (translation._) {
className += " " + translation._;
}
}
} else {
if (typeof translation == "string") {
className = translation;
} else {
className = rule.$;
mode2.report({
id: "UNKNOWN_DIRECTIVE",
rule: className
}, context);
}
if (translateDepth && typeof rule.d !== "function") {
lastTranslations.push(className);
}
}
if (!translateDepth) {
idToClassName.set(rule.$, className);
ensureMaxSize(idToClassName, 3e4);
}
}
return className;
};
const process = tokens => join(parse(tokens).map(convert).filter(Boolean), " ");
const preflight = sanitize(config.preflight, identity, false);
if (preflight) {
const css = createPreflight(theme2);
const styles = serialize2(typeof preflight == "function" ? evalThunk(preflight(css, context), context) || css : {
...css,
...preflight
});
init((injected = (styles.forEach(inject2), true)) => injected);
}
return {
init: () => mode2.report({
id: "LATE_SETUP_CALL"
}, context),
process
};
};
// src/twind/instance.ts
var create = config => {
let process = tokens => {
init();
return process(tokens);
};
let init = config2 => {
({
process,
init
} = configure(config2));
};
if (config) init(config);
let context;
const fromContext = key => () => {
if (!context) {
process([_4 => {
context = _4;
return "";
}]);
}
return context[key];
};
return {
tw: Object.defineProperties((...tokens) => process(tokens), {
theme: {
get: fromContext("theme")
}
}),
setup: config2 => init(config2)
};
};
// src/twind/default.ts
var {
tw,
setup
} = /* @__PURE__ */create();
setup({
preflight: false,
hash: true
});
const equalFn = (a, b) => a === b;
const $PROXY = Symbol("solid-proxy");
const $TRACK = Symbol("solid-track");
const $DEVCOMP = Symbol("solid-dev-component");
const signalOptions = {
equals: equalFn
};
let runEffects = runQueue;
const STALE = 1;
const PENDING = 2;
const UNOWNED = {
owned: null,
cleanups: null,
context: null,
owner: null
};
var Owner = null;
let Transition = null;
let Listener = null;
let Updates = null;
let Effects = null;
let ExecCount = 0;
function createRoot(fn, detachedOwner) {
const listener = Listener,
owner = Owner,
unowned = fn.length === 0,
root = unowned ? UNOWNED : {
owned: null,
cleanups: null,
context: null,
owner: detachedOwner === undefined ? owner : detachedOwner
},
updateFn = unowned ? fn : () => fn(() => untrack(() => cleanNode(root)));
Owner = root;
Listener = null;
try {
return runUpdates(updateFn, true);
} finally {
Listener = listener;
Owner = owner;
}
}
function createSignal(value, options) {
options = options ? Object.assign({}, signalOptions, options) : signalOptions;
const s = {
value,
observers: null,
observerSlots: null,
comparator: options.equals || undefined
};
const setter = value => {
if (typeof value === "function") {
value = value(s.value);
}
return writeSignal(s, value);
};
return [readSignal.bind(s), setter];
}
function createRenderEffect(fn, value, options) {
const c = createComputation(fn, value, false, STALE);
updateComputation(c);
}
function createEffect(fn, value, options) {
runEffects = runUserEffects;
const c = createComputation(fn, value, false, STALE);
if (!options || !options.render) c.user = true;
Effects ? Effects.push(c) : updateComputation(c);
}
function createMemo(fn, value, options) {
options = options ? Object.assign({}, signalOptions, options) : signalOptions;
const c = createComputation(fn, value, true, 0);
c.observers = null;
c.observerSlots = null;
c.comparator = options.equals || undefined;
updateComputation(c);
return readSignal.bind(c);
}
function batch(fn) {
return runUpdates(fn, false);
}
function untrack(fn) {
if (Listener === null) return fn();
const listener = Listener;
Listener = null;
try {
return fn();
} finally {
Listener = listener;
}
}
function on(deps, fn, options) {
const isArray = Array.isArray(deps);
let prevInput;
let defer = options && options.defer;
return prevValue => {
let input;
if (isArray) {
input = Array(deps.length);
for (let i = 0; i < deps.length; i++) input[i] = deps[i]();
} else input = deps();
if (defer) {
defer = false;
return undefined;
}
const result = untrack(() => fn(input, prevInput, prevValue));
prevInput = input;
return result;
};
}
function onMount(fn) {
createEffect(() => untrack(fn));
}
function onCleanup(fn) {
if (Owner === null) ;else if (Owner.cleanups === null) Owner.cleanups = [fn];else Owner.cleanups.push(fn);
return fn;
}
function getListener() {
return Listener;
}
function getOwner() {
return Owner;
}
function children(fn) {
const children = createMemo(fn);
const memo = createMemo(() => resolveChildren(children()));
memo.toArray = () => {
const c = memo();
return Array.isArray(c) ? c : c != null ? [c] : [];
};
return memo;
}
function readSignal() {
if (this.sources && (this.state)) {
if ((this.state) === STALE) updateComputation(this);else {
const updates = Updates;
Updates = null;
runUpdates(() => lookUpstream(this), false);
Updates = updates;
}
}
if (Listener) {
const sSlot = this.observers ? this.observers.length : 0;
if (!Listener.sources) {
Listener.sources = [this];
Listener.sourceSlots = [sSlot];
} else {
Listener.sources.push(this);
Listener.sourceSlots.push(sSlot);
}
if (!this.observers) {
this.observers = [Listener];
this.observerSlots = [Listener.sources.length - 1];
} else {
this.observers.push(Listener);
this.observerSlots.push(Listener.sources.length - 1);
}
}
return this.value;
}
function writeSignal(node, value, isComp) {
let current = node.value;
if (!node.comparator || !node.comparator(current, value)) {
node.value = value;
if (node.observers && node.observers.length) {
runUpdates(() => {
for (let i = 0; i < node.observers.length; i += 1) {
const o = node.observers[i];
const TransitionRunning = Transition && Transition.running;
if (TransitionRunning && Transition.disposed.has(o)) ;
if (TransitionRunning ? !o.tState : !o.state) {
if (o.pure) Updates.push(o);else Effects.push(o);
if (o.observers) markDownstream(o);
}
if (!TransitionRunning) o.state = STALE;
}
if (Updates.length > 10e5) {
Updates = [];
if (false) ;
throw new Error();
}
}, false);
}
}
return value;
}
function updateComputation(node) {
if (!node.fn) return;
cleanNode(node);
const owner = Owner,
listener = Listener,
time = ExecCount;
Listener = Owner = node;
runComputation(node, node.value, time);
Listener = listener;
Owner = owner;
}
function runComputation(node, value, time) {
let nextValue;
try {
nextValue = node.fn(value);
} catch (err) {
if (node.pure) {
{
node.state = STALE;
node.owned && node.owned.forEach(cleanNode);
node.owned = null;
}
}
node.updatedAt = time + 1;
return handleError(err);
}
if (!node.updatedAt || node.updatedAt <= time) {
if (node.updatedAt != null && "observers" in node) {
writeSignal(node, nextValue);
} else node.value = nextValue;
node.updatedAt = time;
}
}
function createComputation(fn, init, pure, state = STALE, options) {
const c = {
fn,
state: state,
updatedAt: null,
owned: null,
sources: null,
sourceSlots: null,
cleanups: null,
value: init,
owner: Owner,
context: null,
pure
};
if (Owner === null) ;else if (Owner !== UNOWNED) {
{
if (!Owner.owned) Owner.owned = [c];else Owner.owned.push(c);
}
}
return c;
}
function runTop(node) {
if ((node.state) === 0) return;
if ((node.state) === PENDING) return lookUpstream(node);
if (node.suspense && untrack(node.suspense.inFallback)) return node.suspense.effects.push(node);
const ancestors = [node];
while ((node = node.owner) && (!node.updatedAt || node.updatedAt < ExecCount)) {
if (node.state) ancestors.push(node);
}
for (let i = ancestors.length - 1; i >= 0; i--) {
node = ancestors[i];
if ((node.state) === STALE) {
updateComputation(node);
} else if ((node.state) === PENDING) {
const updates = Updates;
Updates = null;
runUpdates(() => lookUpstream(node, ancestors[0]), false);
Updates = updates;
}
}
}
function runUpdates(fn, init) {
if (Updates) return fn();
let wait = false;
if (!init) Updates = [];
if (Effects) wait = true;else Effects = [];
ExecCount++;
try {
const res = fn();
completeUpdates(wait);
return res;
} catch (err) {
if (!wait) Effects = null;
Updates = null;
handleError(err);
}
}
function completeUpdates(wait) {
if (Updates) {
runQueue(Updates);
Updates = null;
}
if (wait) return;
const e = Effects;
Effects = null;
if (e.length) runUpdates(() => runEffects(e), false);
}
function runQueue(queue) {
for (let i = 0; i < queue.length; i++) runTop(queue[i]);
}
function runUserEffects(queue) {
let i,
userLength = 0;
for (i = 0; i < queue.length; i++) {
const e = queue[i];
if (!e.user) runTop(e);else queue[userLength++] = e;
}
for (i = 0; i < userLength; i++) runTop(queue[i]);
}
function lookUpstream(node, ignore) {
node.state = 0;
for (let i = 0; i < node.sources.length; i += 1) {
const source = node.sources[i];
if (source.sources) {
const state = source.state;
if (state === STALE) {
if (source !== ignore && (!source.updatedAt || source.updatedAt < ExecCount)) runTop(source);
} else if (state === PENDING) lookUpstream(source, ignore);
}
}
}
function markDownstream(node) {
for (let i = 0; i < node.observers.length; i += 1) {
const o = node.observers[i];
if (!o.state) {
o.state = PENDING;
if (o.pure) Updates.push(o);else Effects.push(o);
o.observers && markDownstream(o);
}
}
}
function cleanNode(node) {
let i;
if (node.sources) {
while (node.sources.length) {
const source = node.sources.pop(),
index = node.sourceSlots.pop(),
obs = source.observers;
if (obs && obs.length) {
const n = obs.pop(),
s = source.observerSlots.pop();
if (index < obs.length) {
n.sourceSlots[s] = index;
obs[index] = n;
source.observerSlots[index] = s;
}
}
}
}
if (node.owned) {
for (i = node.owned.length - 1; i >= 0; i--) cleanNode(node.owned[i]);
node.owned = null;
}
if (node.cleanups) {
for (i = node.cleanups.length - 1; i >= 0; i--) node.cleanups[i]();
node.cleanups = null;
}
node.state = 0;
node.context = null;
}
function handleError(err) {
throw err;
}
function resolveChildren(children) {
if (typeof children === "function" && !children.length) return resolveChildren(children());
if (Array.isArray(children)) {
const results = [];
for (let i = 0; i < children.length; i++) {
const result = resolveChildren(children[i]);
Array.isArray(result) ? results.push.apply(results, result) : results.push(result);
}
return results;
}
return children;
}
const FALLBACK = Symbol("fallback");
function dispose(d) {
for (let i = 0; i < d.length; i++) d[i]();
}
function mapArray(list, mapFn, options = {}) {
let items = [],
mapped = [],
disposers = [],
len = 0,
indexes = mapFn.length > 1 ? [] : null;
onCleanup(() => dispose(disposers));
return () => {
let newItems = list() || [],
i,
j;
newItems[$TRACK];
return untrack(() => {
let newLen = newItems.length,
newIndices,
newIndicesNext,
temp,
tempdisposers,
tempIndexes,
start,
end,
newEnd,
item;
if (newLen === 0) {
if (len !== 0) {
dispose(disposers);
disposers = [];
items = [];
mapped = [];
len = 0;
indexes && (indexes = []);
}
if (options.fallback) {
items = [FALLBACK];
mapped[0] = createRoot(disposer => {
disposers[0] = disposer;
return options.fallback();
});
len = 1;
}
} else if (len === 0) {
mapped = new Array(newLen);
for (j = 0; j < newLen; j++) {
items[j] = newItems[j];
mapped[j] = createRoot(mapper);
}
len = newLen;
} else {
temp = new Array(newLen);
tempdisposers = new Array(newLen);
indexes && (tempIndexes = new Array(newLen));
for (start = 0, end = Math.min(len, newLen); start < end && items[start] === newItems[start]; start++);
for (end = len - 1, newEnd = newLen - 1; end >= start && newEnd >= start && items[end] === newItems[newEnd]; end--, newEnd--) {
temp[newEnd] = mapped[end];
tempdisposers[newEnd] = disposers[end];
indexes && (tempIndexes[newEnd] = indexes[end]);
}
newIndices = new Map();
newIndicesNext = new Array(newEnd + 1);
for (j = newEnd; j >= start; j--) {
item = newItems[j];
i = newIndices.get(item);
newIndicesNext[j] = i === undefined ? -1 : i;
newIndices.set(item, j);
}
for (i = start; i <= end; i++) {
item = items[i];
j = newIndices.get(item);
if (j !== undefined && j !== -1) {
temp[j] = mapped[i];
tempdisposers[j] = disposers[i];
indexes && (tempIndexes[j] = indexes[i]);
j = newIndicesNext[j];
newIndices.set(item, j);
} else disposers[i]();
}
for (j = start; j < newLen; j++) {
if (j in temp) {
mapped[j] = temp[j];
disposers[j] = tempdisposers[j];
if (indexes) {
indexes[j] = tempIndexes[j];
indexes[j](j);
}
} else mapped[j] = createRoot(mapper);
}
mapped = mapped.slice(0, len = newLen);
items = newItems.slice(0);
}
return mapped;
});
function mapper(disposer) {
disposers[j] = disposer;
if (indexes) {
const [s, set] = createSignal(j);
indexes[j] = set;
return mapFn(newItems[j], s);
}
return mapFn(newItems[j]);
}
};
}
function createComponent(Comp, props) {
return untrack(() => Comp(props || {}));
}
function trueFn() {
return true;
}
const propTraps = {
get(_, property, receiver) {
if (property === $PROXY) return receiver;
return _.get(property);
},
has(_, property) {
if (property === $PROXY) return true;
return _.has(property);
},
set: trueFn,
deleteProperty: trueFn,
getOwnPropertyDescriptor(_, property) {
return {
configurable: true,
enumerable: true,
get() {
return _.get(property);
},
set: trueFn,
deleteProperty: trueFn
};
},
ownKeys(_) {
return _.keys();
}
};
function splitProps(props, ...keys) {
const blocked = new Set(keys.flat());
if ($PROXY in props) {
const res = keys.map(k => {
return new Proxy({
get(property) {
return k.includes(property) ? props[property] : undefined;
},
has(property) {
return k.includes(property) && property in props;
},
keys() {
return k.filter(property => property in props);
}
}, propTraps);
});
res.push(new Proxy({
get(property) {
return blocked.has(property) ? undefined : props[property];
},
has(property) {
return blocked.has(property) ? false : property in props;
},
keys() {
return Object.keys(props).filter(k => !blocked.has(k));
}
}, propTraps));
return res;
}
const descriptors = Object.getOwnPropertyDescriptors(props);
keys.push(Object.keys(descriptors).filter(k => !blocked.has(k)));
return keys.map(k => {
const clone = {};
for (let i = 0; i < k.length; i++) {
const key = k[i];
if (!(key in props)) continue;
Object.defineProperty(clone, key, descriptors[key] ? descriptors[key] : {
get() {
return props[key];
},
set() {
return true;
},
enumerable: true
});
}
return clone;
});
}
const narrowedError = name => `Stale read from <${name}>.`;
function For(props) {
const fallback = "fallback" in props && {
fallback: () => props.fallback
};
return createMemo(mapArray(() => props.each, props.children, fallback || undefined));
}
function Show(props) {
const keyed = props.keyed;
const condition = createMemo(() => props.when, undefined, {
equals: (a, b) => keyed ? a === b : !a === !b
});
return createMemo(() => {
const c = condition();
if (c) {
const child = props.children;
const fn = typeof child === "function" && child.length > 0;
return fn ? untrack(() => child(keyed ? c : () => {
if (!untrack(condition)) throw narrowedError("Show");
return props.when;
})) : child;
}
return props.fallback;
}, undefined, undefined);
}
function Switch(props) {
let keyed = false;
const equals = (a, b) => a[0] === b[0] && (keyed ? a[1] === b[1] : !a[1] === !b[1]) && a[2] === b[2];
const conditions = children(() => props.children),
evalConditions = createMemo(() => {
let conds = conditions();
if (!Array.isArray(conds)) conds = [conds];
for (let i = 0; i < conds.length; i++) {
const c = conds[i].when;
if (c) {
keyed = !!conds[i].keyed;
return [i, c, conds[i]];
}
}
return [-1];
}, undefined, {
equals
});
return createMemo(() => {
const [index, when, cond] = evalConditions();
if (index < 0) return props.fallback;
const c = cond.children;
const fn = typeof c === "function" && c.length > 0;
return fn ? untrack(() => c(keyed ? when : () => {
if (untrack(evalConditions)[0] !== index) throw narrowedError("Match");
return cond.when;
})) : c;
}, undefined, undefined);
}
function Match(props) {
return props;
}
const booleans = ["allowfullscreen", "async", "autofocus", "autoplay", "checked", "controls", "default", "disabled", "formnovalidate", "hidden", "indeterminate", "ismap", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "seamless", "selected"];
const Properties = /*#__PURE__*/new Set(["className", "value", "readOnly", "formNoValidate", "isMap", "noModule", "playsInline", ...booleans]);
const ChildProperties = /*#__PURE__*/new Set(["innerHTML", "textContent", "innerText", "children"]);
const Aliases = /*#__PURE__*/Object.assign(Object.create(null), {
className: "class",
htmlFor: "for"
});
const PropAliases = /*#__PURE__*/Object.assign(Object.create(null), {
class: "className",
formnovalidate: {
$: "formNoValidate",
BUTTON: 1,
INPUT: 1
},
ismap: {
$: "isMap",
IMG: 1
},
nomodule: {
$: "noModule",
SCRIPT: 1
},
playsinline: {
$: "playsInline",
VIDEO: 1
},
readonly: {
$: "readOnly",
INPUT: 1,
TEXTAREA: 1
}
});
function getPropAlias(prop, tagName) {
const a = PropAliases[prop];
return typeof a === "object" ? a[tagName] ? a["$"] : undefined : a;
}
const DelegatedEvents = /*#__PURE__*/new Set(["beforeinput", "click", "dblclick", "contextmenu", "focusin", "focusout", "input", "keydown", "keyup", "mousedown", "mousemove", "mouseout", "mouseover", "mouseup", "pointerdown", "pointermove", "pointerout", "pointerover", "pointerup", "touchend", "touchmove", "touchstart"]);
const SVGElements = /*#__PURE__*/new Set(["altGlyph", "altGlyphDef", "altGlyphItem", "animate", "animateColor", "animateMotion", "animateTransform", "circle", "clipPath", "color-profile", "cursor", "defs", "desc", "ellipse", "feBlend", "feColorMatrix", "feComponentTransfer", "feComposite", "feConvolveMatrix", "feDiffuseLighting", "feDisplacementMap", "feDistantLight", "feFlood", "feFuncA", "feFuncB", "feFuncG", "feFuncR", "feGaussianBlur", "feImage", "feMerge", "feMergeNode", "feMorphology", "feOffset", "fePointLight", "feSpecularLighting", "feSpotLight", "feTile", "feTurbulence", "filter", "font", "font-face", "font-face-format", "font-face-name", "font-face-src", "font-face-uri", "foreignObject", "g", "glyph", "glyphRef", "hkern", "image", "line", "linearGradient", "marker", "mask", "metadata", "missing-glyph", "mpath", "path", "pattern", "polygon", "polyline", "radialGradient", "rect", "set", "stop", "svg", "switch", "symbol", "text", "textPath", "tref", "tspan", "use", "view", "vkern"]);
const SVGNamespace = {
xlink: "http://www.w3.org/1999/xlink",
xml: "http://www.w3.org/XML/1998/namespace"
};
function reconcileArrays(parentNode, a, b) {
let bLength = b.length,
aEnd = a.length,
bEnd = bLength,
aStart = 0,
bStart = 0,
after = a[aEnd - 1].nextSibling,
map = null;
while (aStart < aEnd || bStart < bEnd) {
if (a[aStart] === b[bStart]) {
aStart++;
bStart++;
continue;
}
while (a[aEnd - 1] === b[bEnd - 1]) {
aEnd--;
bEnd--;
}
if (aEnd === aStart) {
const node = bEnd < bLength ? bStart ? b[bStart - 1].nextSibling : b[bEnd - bStart] : after;
while (bStart < bEnd) parentNode.insertBefore(b[bStart++], node);
} else if (bEnd === bStart) {
while (aStart < aEnd) {
if (!map || !map.has(a[aStart])) a[aStart].remove();
aStart++;
}
} else if (a[aStart] === b[bEnd - 1] && b[bStart] === a[aEnd - 1]) {
const node = a[--aEnd].nextSibling;
parentNode.insertBefore(b[bStart++], a[aStart++].nextSibling);
parentNode.insertBefore(b[--bEnd], node);
a[aEnd] = b[bEnd];
} else {
if (!map) {
map = new Map();
let i = bStart;
while (i < bEnd) map.set(b[i], i++);
}
const index = map.get(a[aStart]);
if (index != null) {
if (bStart < index && index < bEnd) {
let i = aStart,
sequence = 1,
t;
while (++i < aEnd && i < bEnd) {
if ((t = map.get(a[i])) == null || t !== index + sequence) break;
sequence++;
}
if (sequence > index - bStart) {
const node = a[aStart];
while (bStart < index) parentNode.insertBefore(b[bStart++], node);
} else parentNode.replaceChild(b[bStart++], a[aStart++]);
} else aStart++;
} else a[aStart++].remove();
}
}
}
const $$EVENTS = "_$DX_DELEGATE";
function render(code, element, init, options = {}) {
let disposer;
createRoot(dispose => {
disposer = dispose;
element === document ? code() : insert(element, code(), element.firstChild ? null : undefined, init);
}, options.owner);
return () => {
disposer();
element.textContent = "";
};
}
function template(html, isCE, isSVG) {
let node;
const create = () => {
const t = document.createElement("template");
t.innerHTML = html;
return isSVG ? t.content.firstChild.firstChild : t.content.firstChild;
};
const fn = isCE ? () => (node || (node = create())).cloneNode(true) : () => untrack(() => document.importNode(node || (node = create()), true));
fn.cloneNode = fn;
return fn;
}
function delegateEvents(eventNames, document = window.document) {
const e = document[$$EVENTS] || (document[$$EVENTS] = new Set());
for (let i = 0, l = eventNames.length; i < l; i++) {
const name = eventNames[i];
if (!e.has(name)) {
e.add(name);
document.addEventListener(name, eventHandler);
}
}
}
function setAttribute(node, name, value) {
if (value == null) node.removeAttribute(name);else node.setAttribute(name, value);
}
function setAttributeNS(node, namespace, name, value) {
if (value == null) node.removeAttributeNS(namespace, name);else node.setAttributeNS(namespace, name, value);
}
function className(node, value) {
if (value == null) node.removeAttribute("class");else node.className = value;
}
function addEventListener(node, name, handler, delegate) {
if (delegate) {
if (Array.isArray(handler)) {
node[`$$${name}`] = handler[0];
node[`$$${name}Data`] = handler[1];
} else node[`$$${name}`] = handler;
} else if (Array.isArray(handler)) {
const handlerFn = handler[0];
node.addEventListener(name, handler[0] = e => handlerFn.call(node, handler[1], e));
} else node.addEventListener(name, handler);
}
function classList(node, value, prev = {}) {
const classKeys = Object.keys(value || {}),
prevKeys = Object.keys(prev);
let i, len;
for (i = 0, len = prevKeys.length; i < len; i++) {
const key = prevKeys[i];
if (!key || key === "undefined" || value[key]) continue;
toggleClassKey(node, key, false);
delete prev[key];
}
for (i = 0, len = classKeys.length; i < len; i++) {
const key = classKeys[i],
classValue = !!value[key];
if (!key || key === "undefined" || prev[key] === classValue || !classValue) continue;
toggleClassKey(node, key, true);
prev[key] = classValue;
}
return prev;
}
function style(node, value, prev) {
if (!value) return prev ? setAttribute(node, "style") : value;
const nodeStyle = node.style;
if (typeof value === "string") return nodeStyle.cssText = value;
typeof prev === "string" && (nodeStyle.cssText = prev = undefined);
prev || (prev = {});
value || (value = {});
let v, s;
for (s in prev) {
value[s] == null && nodeStyle.removeProperty(s);
delete prev[s];
}
for (s in value) {
v = value[s];
if (v !== prev[s]) {
nodeStyle.setProperty(s, v);
prev[s] = v;
}
}
return prev;
}
function spread(node, props = {}, isSVG, skipChildren) {
const prevProps = {};
if (!skipChildren) {
createRenderEffect(() => prevProps.children = insertExpression(node, props.children, prevProps.children));
}
createRenderEffect(() => props.ref && props.ref(node));
createRenderEffect(() => assign(node, props, isSVG, true, prevProps, true));
return prevProps;
}
function insert(parent, accessor, marker, initial) {
if (marker !== undefined && !initial) initial = [];
if (typeof accessor !== "function") return insertExpression(parent, accessor, initial, marker);
createRenderEffect(current => insertExpression(parent, accessor(), current, marker), initial);
}
function assign(node, props, isSVG, skipChildren, prevProps = {}, skipRef = false) {
props || (props = {});
for (const prop in prevProps) {
if (!(prop in props)) {
if (prop === "children") continue;
prevProps[prop] = assignProp(node, prop, null, prevProps[prop], isSVG, skipRef);
}
}
for (const prop in props) {
if (prop === "children") {
if (!skipChildren) insertExpression(node, props.children);
continue;
}
const value = props[prop];
prevProps[prop] = assignProp(node, prop, value, prevProps[prop], isSVG, skipRef);
}
}
function toPropertyName(name) {
return name.toLowerCase().replace(/-([a-z])/g, (_, w) => w.toUpperCase());
}
function toggleClassKey(node, key, value) {
const classNames = key.trim().split(/\s+/);
for (let i = 0, nameLen = classNames.length; i < nameLen; i++) node.classList.toggle(classNames[i], value);
}
function assignProp(node, prop, value, prev, isSVG, skipRef) {
let isCE, isProp, isChildProp, propAlias, forceProp;
if (prop === "style") return style(node, value, prev);
if (prop === "classList") return classList(node, value, prev);
if (value === prev) return prev;
if (prop === "ref") {
if (!skipRef) value(node);
} else if (prop.slice(0, 3) === "on:") {
const e = prop.slice(3);
prev && node.removeEventListener(e, prev);
value && node.addEventListener(e, value);
} else if (prop.slice(0, 10) === "oncapture:") {
const e = prop.slice(10);
prev && node.removeEventListener(e, prev, true);
value && node.addEventListener(e, value, true);
} else if (prop.slice(0, 2) === "on") {
const name = prop.slice(2).toLowerCase();
const delegate = DelegatedEvents.has(name);
if (!delegate && prev) {
const h = Array.isArray(prev) ? prev[0] : prev;
node.removeEventListener(name, h);
}
if (delegate || value) {
addEventListener(node, name, value, delegate);
delegate && delegateEvents([name]);
}
} else if (prop.slice(0, 5) === "attr:") {
setAttribute(node, prop.slice(5), value);
} else if ((forceProp = prop.slice(0, 5) === "prop:") || (isChildProp = ChildProperties.has(prop)) || !isSVG && ((propAlias = getPropAlias(prop, node.tagName)) || (isProp = Properties.has(prop))) || (isCE = node.nodeName.includes("-"))) {
if (forceProp) {
prop = prop.slice(5);
isProp = true;
}
if (prop === "class" || prop === "className") className(node, value);else if (isCE && !isProp && !isChildProp) node[toPropertyName(prop)] = value;else node[propAlias || prop] = value;
} else {
const ns = isSVG && prop.indexOf(":") > -1 && SVGNamespace[prop.split(":")[0]];
if (ns) setAttributeNS(node, ns, prop, value);else setAttribute(node, Aliases[prop] || prop, value);
}
return value;
}
function eventHandler(e) {
const key = `$$${e.type}`;
let node = e.composedPath && e.composedPath()[0] || e.target;
if (e.target !== node) {
Object.defineProperty(e, "target", {
configurable: true,
value: node
});
}
Object.defineProperty(e, "currentTarget", {
configurable: true,
get() {
return node || document;
}
});
while (node) {
const handler = node[key];
if (handler && !node.disabled) {
const data = node[`${key}Data`];
data !== undefined ? handler.call(node, data, e) : handler.call(node, e);
if (e.cancelBubble) return;
}
node = node._$host || node.parentNode || node.host;
}
}
function insertExpression(parent, value, current, marker, unwrapArray) {
while (typeof current === "function") current = current();
if (value === current) return current;
const t = typeof value,
multi = marker !== undefined;
parent = multi && current[0] && current[0].parentNode || parent;
if (t === "string" || t === "number") {
if (t === "number") value = value.toString();
if (multi) {
let node = current[0];
if (node && node.nodeType === 3) {
node.data = value;
} else node = document.createTextNode(value);
current = cleanChildren(parent, current, marker, node);
} else {
if (current !== "" && typeof current === "string") {
current = parent.firstChild.data = value;
} else current = parent.textContent = value;
}
} else if (value == null || t === "boolean") {
current = cleanChildren(parent, current, marker);
} else if (t === "function") {
createRenderEffect(() => {
let v = value();
while (typeof v === "function") v = v();
current = insertExpression(parent, v, current, marker);
});
return () => current;
} else if (Array.isArray(value)) {
const array = [];
const currentArray = current && Array.isArray(current);
if (normalizeIncomingArray(array, value, current, unwrapArray)) {
createRenderEffect(() => current = insertExpression(parent, array, current, marker, true));
return () => current;
}
if (array.length === 0) {
current = cleanChildren(parent, current, marker);
if (multi) return current;
} else if (currentArray) {
if (current.length === 0) {
appendNodes(parent, array, marker);
} else reconcileArrays(parent, current, array);
} else {
current && cleanChildren(parent);
appendNodes(parent, array);
}
current = array;
} else if (value instanceof Node) {
if (Array.isArray(current)) {
if (multi) return current = cleanChildren(parent, current, marker, value);
cleanChildren(parent, current, null, value);
} else if (current == null || current === "" || !parent.firstChild) {
parent.appendChild(value);
} else parent.replaceChild(value, parent.firstChild);
current = value;
} else console.warn(`Unrecognized value. Skipped inserting`, value);
return current;
}
function normalizeIncomingArray(normalized, array, current, unwrap) {
let dynamic = false;
for (let i = 0, len = array.length; i < len; i++) {
let item = array[i],
prev = current && current[i];
if (item instanceof Node) {
normalized.push(item);
} else if (item == null || item === true || item === false) ;else if (Array.isArray(item)) {
dynamic = normalizeIncomingArray(normalized, item, prev) || dynamic;
} else if (typeof item === "function") {
if (unwrap) {
while (typeof item === "function") item = item();
dynamic = normalizeIncomingArray(normalized, Array.isArray(item) ? item : [item], Array.isArray(prev) ? prev : [prev]) || dynamic;
} else {
normalized.push(item);
dynamic = true;
}
} else {
const value = String(item);
if (prev && prev.nodeType === 3) {
prev.data = value;
normalized.push(prev);
} else normalized.push(document.createTextNode(value));
}
}
return dynamic;
}
function appendNodes(parent, array, marker = null) {
for (let i = 0, len = array.length; i < len; i++) parent.insertBefore(array[i], marker);
}
function cleanChildren(parent, current, marker, replacement) {
if (marker === undefined) return parent.textContent = "";
const node = replacement || document.createTextNode("");
if (current.length) {
let inserted = false;
for (let i = current.length - 1; i >= 0; i--) {
const el = current[i];
if (node !== el) {
const isParent = el.parentNode === parent;
if (!inserted && !i) isParent ? parent.replaceChild(node, el) : parent.insertBefore(node, marker);else isParent && el.remove();
} else inserted = true;
}
} else parent.insertBefore(node, marker);
return [node];
}
const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
function createElement(tagName, isSVG = false) {
return isSVG ? document.createElementNS(SVG_NAMESPACE, tagName) : document.createElement(tagName);
}
function Dynamic(props) {
const [p, others] = splitProps(props, ["component"]);
const cached = createMemo(() => p.component);
return createMemo(() => {
const component = cached();
switch (typeof component) {
case "function":
Object.assign(component, {
[$DEVCOMP]: true
});
return untrack(() => component(others));
case "string":
const isSvg = SVGElements.has(component);
const el = createElement(component, isSvg);
spread(el, others, isSvg);
return el;
}
});
}
var throttle = (callback, wait) => {
let isThrottled = false,
timeoutId,
lastArgs;
const throttled = (...args) => {
lastArgs = args;
if (isThrottled) return;
isThrottled = true;
timeoutId = setTimeout(() => {
callback(...lastArgs);
isThrottled = false;
}, wait);
};
const clear = () => {
clearTimeout(timeoutId);
isThrottled = false;
};
if (getOwner()) onCleanup(clear);
return Object.assign(throttled, {
clear
});
};
var access = v => typeof v === "function" && !v.length ? v() : v;
var asArray = value => Array.isArray(value) ? value : value ? [value] : [];
function createGMSignal(key, initialValue) {
const [signal, setSignal] = createSignal(initialValue);
let listener;
GMP.addValueChangeListener?.(key, (name, oldValue, newValue, remote) => {
if (name === key && (remote === void 0 || remote === true)) read(newValue);
}).then(l => listener = l);
let effectPaused = false;
createEffect(on(signal, () => {
if (effectPaused) return;
if (signal() == null) {
GMP.deleteValue(key);
effectPaused = true;
setSignal(() => initialValue);
effectPaused = false;
} else {
GMP.setValue(key, signal());
}
}, {
defer: true
}));
async function read(newValue) {
effectPaused = true;
const rawValue = newValue ?? (await GMP.getValue(key));
if (rawValue == null) setSignal(() => initialValue);else setSignal(() => rawValue);
effectPaused = false;
}
const [isReady, setIsReady] = createSignal(false);
signal.isReady = isReady;
signal.ready = read().then(() => {
setIsReady(true);
});
onCleanup(() => {
if (listener) GMP.removeValueChangeListener?.(listener);
});
return [signal, setSignal];
}
const [detectionResolution, setDetectionResolution] = createGMSignal("detectionResolution", "M");
const [textDetector, setTextDetector] = createGMSignal("textDetector", "default");
const [translatorService, setTranslatorService] = createGMSignal("translator", "youdao");
const [renderTextOrientation, setRenderTextOrientation] = createGMSignal("renderTextOrientation", "auto");
const [targetLang, setTargetLang] = createGMSignal("targetLang", "");
const [scriptLang, setScriptLang] = createGMSignal("scriptLanguage", "");
const [keepInstances, setKeepInstances] = createGMSignal("keepInstances", "until-reload");
const storageReady = Promise.all([detectionResolution.ready, textDetector.ready, translatorService.ready, renderTextOrientation.ready, targetLang.ready, scriptLang.ready, keepInstances.ready]);
var data$1 = { common:{ source:{ "download-image":"正在拉取原图",
"download-image-progress":"正在拉取原图({progress})",
"download-image-error":"拉取原图出错" },
client:{ submit:"正在提交翻译",
"submit-progress":"正在提交翻译({progress})",
"submit-error":"提交翻译出错",
"download-image":"正在下载图片",
"download-image-progress":"正在下载图片({progress})",
"download-image-error":"下载图片出错",
resize:"正在缩放图片",
merging:"正在合并图层" },
status:{ "default":"未知状态",
pending:"正在等待",
"pending-pos":"正在等待,列队还有 {pos} 张图片",
upscaling:"正在放大图片",
detection:"正在检测文本",
ocr:"正在识别文本",
"mask-generation":"正在生成文本掩码",
inpainting:"正在修补图片",
translating:"正在翻译文本",
rendering:"正在渲染",
downscaling:"正在缩小图片",
finished:"正在整理结果",
error:"翻译出错",
"error-lang":"你选择的翻译服务不支持你选择的语言",
"error-translating":"翻译服务没有返回任何文本",
"error-with-id":"翻译出错 (ID: {id})" },
control:{ translate:"翻译",
batch:"翻译全部 ({count})",
reset:"还原" },
batch:{ progress:"翻译中 ({count}/{total})",
finish:"翻译完成",
error:"翻译完成(有失败)" } },
settings:{ title:"Cotrans 图片翻译器设置",
"inline-options-title":"设置当前翻译",
"detection-resolution":"文本扫描清晰度",
"text-detector":"文本扫描器",
"text-detector-options":{ "default":"默认" },
translator:"翻译服务",
"render-text-orientation":"渲染字体方向",
"render-text-orientation-options":{ auto:"跟随原文本",
horizontal:"仅限水平",
vertical:"仅限垂直" },
"target-language":"翻译语言",
"target-language-options":{ auto:"跟随网页语言" },
"script-language":"用户脚本语言",
"script-language-options":{ auto:"跟随网页语言" },
reset:"重置所有设置",
"detection-resolution-desc":"设置检测图片文本所用的清晰度,小文字适合使用更高的清晰度。",
"text-detector-desc":"设置使用的文本扫描器。",
"translator-desc":"设置翻译图片所用的翻译服务。",
"render-text-orientation-desc":"设置嵌字的文本方向。",
"target-language-desc":"设置图片翻译后的语言。",
"script-language-desc":"设置此用户脚本的语言。",
"translator-options":{ none:"None (删除文字)" },
"keep-instances-options":{ "until-reload":"直到页面刷新",
"until-navigate":"直到下次跳转" },
"keep-instances":"保留翻译进度",
"keep-instances-desc":"设置翻译进度的保留时间。 翻译进度即图片的翻译状态和翻译结果。 保留更多的翻译进度会占用更多的内存。",
"force-retry":"强制重试 (忽略缓存)" },
sponsor:{ text:"制作不易,请考虑赞助我们!" } };
data$1.common;
data$1.settings;
data$1.sponsor;
var data = { common:{ source:{ "download-image":"Downloading original image",
"download-image-progress":"Downloading original image ({progress})",
"download-image-error":"Error during original image download" },
client:{ submit:"Submitting translation",
"submit-progress":"Submitting translation ({progress})",
"submit-error":"Error during translation submission",
"download-image":"Downloading translated image",
"download-image-progress":"Downloading translated image ({progress})",
"download-image-error":"Error during translated image download",
resize:"Resizing image",
merging:"Merging layers" },
status:{ "default":"Unknown status",
pending:"Pending",
"pending-pos":"Pending, {pos} in queue",
upscaling:"Upscaling",
detection:"Detecting text",
ocr:"Scanning text",
"mask-generation":"Generating mask",
inpainting:"Inpainting",
translating:"Translating",
rendering:"Rendering",
downscaling:"Downscaling",
finished:"Finishing",
error:"Error during translation",
"error-lang":"Your target language is not supported by the chosen translator",
"error-translating":"Did not get any text back from the text translation service",
"error-with-id":"Error during translation (ID: {id})" },
control:{ translate:"Translate",
batch:"Translate all ({count})",
reset:"Reset" },
batch:{ progress:"Translating ({count}/{total} finished)",
finish:"Translation finished",
error:"Translation finished with errors" } },
settings:{ "detection-resolution":"Text detection resolution",
"render-text-orientation":"Render text orientation",
"render-text-orientation-options":{ auto:"Follow source",
horizontal:"Horizontal only",
vertical:"Vertical only" },
reset:"Reset Settings",
"target-language":"Translate target language",
"target-language-options":{ auto:"Follow website" },
"text-detector":"Text detector",
"text-detector-options":{ "default":"Default" },
title:"Cotrans Manga Translator Settings",
translator:"Translator",
"script-language":"Userscript language",
"script-language-options":{ auto:"Follow website language" },
"inline-options-title":"Current Settings",
"detection-resolution-desc":"The resolution used to scan texts on an image, higher value are better suited for smaller texts.",
"script-language-desc":"Language of this userscript.",
"render-text-orientation-desc":"Overwrite the orientation of texts rendered in the translated image.",
"target-language-desc":"The language that images are translated to.",
"text-detector-desc":"The detector used to scan texts in an image.",
"translator-desc":"The translate service used to translate texts.",
"translator-options":{ none:"None (remove texts)" },
"keep-instances-options":{ "until-reload":"Until page reload",
"until-navigate":"Until next navigation" },
"keep-instances":"Keep translation instances",
"keep-instances-desc":"How long before a translation instance is disposed. A translation instance includes the translation state of an image, that is, whether the image is translated or not, and the translation result. Keeping more translation instances will result in more memory consumption.",
"force-retry":"Force retry (ignore cache)" },
sponsor:{ text:"If you find this script helpful, please consider supporting us!" } };
data.common;
data.settings;
data.sponsor;
const messages = {
"zh-CN": data$1,
"en-US": data
};
function tryMatchLang(lang2) {
if (lang2.startsWith("zh")) return "zh-CN";
if (lang2.startsWith("en")) return "en-US";
return "en-US";
}
const [realLang, setRealLang] = createSignal(navigator.language);
const lang = createMemo(() => scriptLang() || tryMatchLang(realLang()));
function t(key_, props = {}) {
return createMemo(() => {
const key = access(key_);
const segments = key.split(".");
const msg = segments.reduce((obj, k) => obj[k], messages[lang()]) ?? segments.reduce((obj, k) => obj[k], messages["zh-CN"]);
if (!msg) return key;
return msg.replace(/\{([^}]+)\}/g, (_, k) => String(access(access(props)[k])) ?? "");
});
}
let langEL;
let langObserver;
function changeLangEl(el) {
if (langEL === el) return;
if (langObserver) langObserver.disconnect();
langObserver = new MutationObserver(mutations => {
for (const mutation of mutations) {
if (mutation.type === "attributes" && mutation.attributeName === "lang") {
const target = mutation.target;
if (target.lang) setRealLang(target.lang);
break;
}
}
});
langObserver.observe(el, {
attributes: true
});
langEL = el;
setRealLang(el.lang);
}
function BCP47ToISO639(code) {
try {
const lo = new Intl.Locale(code);
switch (lo.language) {
case "zh":
{
switch (lo.script) {
case "Hans":
return "CHS";
case "Hant":
return "CHT";
}
switch (lo.region) {
case "CN":
return "CHS";
case "HK":
case "TW":
return "CHT";
}
return "CHS";
}
case "ja":
return "JPN";
case "en":
return "ENG";
case "ko":
return "KOR";
case "vi":
return "VIE";
case "cs":
return "CSY";
case "nl":
return "NLD";
case "fr":
return "FRA";
case "de":
return "DEU";
case "hu":
return "HUN";
case "it":
return "ITA";
case "pl":
return "PLK";
case "pt":
return "PTB";
case "ro":
return "ROM";
case "ru":
return "RUS";
case "es":
return "ESP";
case "tr":
return "TRK";
case "uk":
return "UKR";
}
return "ENG";
} catch (e) {
return "ENG";
}
}
DelegatedEvents.clear();
function createScopedInstance(cb) {
return createRoot(dispose => {
const instance = cb();
return {
...instance,
dispose
};
});
}
let currentURL;
let translator$2;
let settingsInjector$2;
async function start(translators, settingsInjectors) {
await storageReady;
async function onUpdate() {
await new Promise(resolve => (queueMicrotask ?? setTimeout)(resolve));
if (currentURL !== location.href) {
currentURL = location.href;
changeLangEl(document.documentElement);
if (translator$2?.canKeep?.(currentURL)) {
translator$2.onURLChange?.(currentURL);
} else {
translator$2?.dispose();
translator$2 = void 0;
const url = new URL(location.href);
const matched = translators.find(t => t.match(url));
if (matched) translator$2 = createScopedInstance(matched.mount);
}
if (settingsInjector$2?.canKeep?.(currentURL)) {
settingsInjector$2.onURLChange?.(currentURL);
} else {
settingsInjector$2?.dispose();
settingsInjector$2 = void 0;
const url = new URL(location.href);
const matched = settingsInjectors.find(t => t.match(url));
if (matched) settingsInjector$2 = createScopedInstance(matched.mount);
}
}
}
if (window.onurlchange === null) {
window.addEventListener("urlchange", onUpdate);
} else {
const installObserver = new MutationObserver(throttle(onUpdate, 200));
installObserver.observe(document.body, {
childList: true,
subtree: true
});
}
onUpdate();
}
// src/index.ts
var triggerOptions = {
equals: false
};
var triggerCacheOptions = triggerOptions;
var TriggerCache = class {
#map;
constructor(mapConstructor = Map) {
this.#map = new mapConstructor();
}
dirty(key) {
this.#map.get(key)?.$$();
}
track(key) {
if (!getListener()) return;
let trigger = this.#map.get(key);
if (!trigger) {
const [$, $$] = createSignal(void 0, triggerCacheOptions);
this.#map.set(key, trigger = {
$,
$$,
n: 1
});
} else trigger.n++;
onCleanup(() => {
if (trigger.n-- === 1) queueMicrotask(() => trigger.n === 0 && this.#map.delete(key));
});
trigger.$();
}
};
// src/index.ts
var $KEYS = Symbol("track-keys");
var ReactiveMap = class extends Map {
#keyTriggers = new TriggerCache();
#valueTriggers = new TriggerCache();
constructor(initial) {
super();
if (initial) for (const v of initial) super.set(v[0], v[1]);
}
// reads
has(key) {
this.#keyTriggers.track(key);
return super.has(key);
}
get(key) {
this.#valueTriggers.track(key);
return super.get(key);
}
get size() {
this.#keyTriggers.track($KEYS);
return super.size;
}
keys() {
this.#keyTriggers.track($KEYS);
return super.keys();
}
values() {
this.#keyTriggers.track($KEYS);
for (const v of super.keys()) this.#valueTriggers.track(v);
return super.values();
}
entries() {
this.#keyTriggers.track($KEYS);
for (const v of super.keys()) this.#valueTriggers.track(v);
return super.entries();
}
// writes
set(key, value) {
batch(() => {
if (super.has(key)) {
if (super.get(key) === value) return;
} else {
this.#keyTriggers.dirty(key);
this.#keyTriggers.dirty($KEYS);
}
this.#valueTriggers.dirty(key);
super.set(key, value);
});
return this;
}
delete(key) {
const r = super.delete(key);
if (r) {
batch(() => {
this.#keyTriggers.dirty(key);
this.#keyTriggers.dirty($KEYS);
this.#valueTriggers.dirty(key);
});
}
return r;
}
clear() {
if (super.size) {
batch(() => {
for (const v of super.keys()) {
this.#keyTriggers.dirty(v);
this.#valueTriggers.dirty(v);
}
super.clear();
this.#keyTriggers.dirty($KEYS);
});
}
}
// callback
forEach(callbackfn) {
this.#keyTriggers.track($KEYS);
super.forEach((value, key) => callbackfn(value, key, this));
}
[Symbol.iterator]() {
return this.entries();
}
};
// src/index.ts
function createMutationObserver(initial, b, c) {
let defaultOptions, callback;
const isSupported = typeof window !== "undefined" && "MutationObserver" in window;
if (typeof b === "function") {
defaultOptions = {};
callback = b;
} else {
defaultOptions = b;
callback = c;
}
const instance = isSupported ? new MutationObserver(callback) : void 0;
const add = (el, options) => instance?.observe(el, access(options) ?? defaultOptions);
const start = () => {
asArray(access(initial)).forEach(item => {
item instanceof Node ? add(item, defaultOptions) : add(item[0], item[1]);
});
};
const stop = () => instance?.disconnect();
onMount(start);
onCleanup(stop);
return [add, {
start,
stop,
instance,
isSupported
}];
}
const _tmpl$$9 = /*#__PURE__*/template(`<div><div> edition, v</div><div></div><div></div><div><button>`),
_tmpl$2$2 = /*#__PURE__*/template(`<a target="_blank" rel="noopener noreferrer">`),
_tmpl$3$2 = /*#__PURE__*/template(`<div>`),
_tmpl$4$2 = /*#__PURE__*/template(`<div><div></div><div><select>`),
_tmpl$5$2 = /*#__PURE__*/template(`<option>`);
const detectResOptionsMap = {
S: () => "1024px",
M: () => "1536px",
L: () => "2048px",
X: () => "2560px"
};
const detectResOptions = Object.keys(detectResOptionsMap);
const renderTextDirOptionsMap = {
auto: t("settings.render-text-orientation-options.auto"),
horizontal: t("settings.render-text-orientation-options.horizontal"),
vertical: t("settings.render-text-orientation-options.vertical")
};
const renderTextDirOptions = Object.keys(renderTextDirOptionsMap);
const textDetectorOptionsMap = {
default: t("settings.text-detector-options.default"),
ctd: () => "Comic Text Detector"
};
const textDetectorOptions = Object.keys(textDetectorOptionsMap);
const translatorOptionsMap = {
youdao: () => "Youdao",
baidu: () => "Baidu",
google: () => "Google",
deepl: () => "DeepL",
papago: () => "Papago",
offline: () => "Sugoi / NLLB",
none: t("settings.translator-options.none")
// offline_big: () => 'Sugoi / NLLB (Big)',
// nnlb: () => 'NLLB',
// nnlb_big: () => 'NLLB (Big)',
// sugoi: () => 'Sugoi',
// sugoi_small: () => 'Sugoi (Small)',
// sugoi_big: () => 'Sugoi (Big)',
};
const translatorOptions = Object.keys(translatorOptionsMap);
const targetLangOptionsMap = {
"": t("settings.target-language-options.auto"),
"CHS": () => "简体中文",
"CHT": () => "繁體中文",
"JPN": () => "日本語",
"ENG": () => "English",
"KOR": () => "한국어",
"VIN": () => "Tiếng Việt",
"CSY": () => "čeština",
"NLD": () => "Nederlands",
"FRA": () => "français",
"DEU": () => "Deutsch",
"HUN": () => "magyar nyelv",
"ITA": () => "italiano",
"PLK": () => "polski",
"PTB": () => "português",
"ROM": () => "limba română",
"RUS": () => "русский язык",
"UKR": () => "українська мова",
"ESP": () => "español",
"TRK": () => "Türk dili"
};
const scriptLangOptionsMap = {
"": t("settings.script-language-options.auto"),
"zh-CN": () => "简体中文",
"en-US": () => "English"
};
const keepInstancesOptionsMap = {
"until-reload": t("settings.keep-instances-options.until-reload"),
"until-navigate": t("settings.keep-instances-options.until-navigate")
};
const Settings = props => {
const itemOrientation = () => props.itemOrientation ?? "vertical";
const textStyle = () => props.textStyle ?? {};
return (() => {
const _el$ = _tmpl$$9(),
_el$2 = _el$.firstChild,
_el$3 = _el$2.firstChild,
_el$4 = _el$2.nextSibling,
_el$5 = _el$4.nextSibling,
_el$6 = _el$5.nextSibling,
_el$7 = _el$6.firstChild;
className(_el$, tw`flex flex-col gap-2`);
insert(_el$2, EDITION, _el$3);
insert(_el$2, VERSION, null);
insert(_el$4, t("sponsor.text"));
insert(_el$5, createComponent(For, {
each: [["ko-fi", "https://ko-fi.com/voilelabs"], ["Patreon", "https://patreon.com/voilelabs"], ["爱发电", "https://afdian.net/@voilelabs"]],
children: ([name, url]) => [" ", (() => {
const _el$8 = _tmpl$2$2();
setAttribute(_el$8, "href", url);
className(_el$8, tw`no-underline text-blue-600`);
insert(_el$8, name);
return _el$8;
})()]
}));
insert(_el$, createComponent(For, {
get each() {
return [[t("settings.detection-resolution"), detectionResolution, setDetectionResolution, detectResOptionsMap, t("settings.detection-resolution-desc")], [t("settings.text-detector"), textDetector, setTextDetector, textDetectorOptionsMap, t("settings.text-detector-desc")], [t("settings.translator"), translatorService, setTranslatorService, translatorOptionsMap, t("settings.translator-desc")], [t("settings.render-text-orientation"), renderTextOrientation, setRenderTextOrientation, renderTextDirOptionsMap, t("settings.render-text-orientation-desc")], [t("settings.target-language"), targetLang, setTargetLang, targetLangOptionsMap, t("settings.target-language-desc")], [t("settings.script-language"), scriptLang, setScriptLang, scriptLangOptionsMap, t("settings.script-language-desc")], [t("settings.keep-instances"), keepInstances, setKeepInstances, keepInstancesOptionsMap, t("settings.keep-instances-desc")]];
},
children: ([title, opt, setOpt, optMap, desc]) => (() => {
const _el$9 = _tmpl$4$2(),
_el$10 = _el$9.firstChild,
_el$11 = _el$10.nextSibling,
_el$12 = _el$11.firstChild;
insert(_el$10, title);
_el$12.addEventListener("change", e => setOpt(e.target.value));
insert(_el$12, () => Object.entries(optMap).map(([value, label]) => (() => {
const _el$14 = _tmpl$5$2();
_el$14.value = value;
insert(_el$14, label);
return _el$14;
})()));
insert(_el$11, createComponent(Show, {
get when() {
return desc();
},
get children() {
const _el$13 = _tmpl$3$2();
className(_el$13, tw`text-sm`);
insert(_el$13, desc);
return _el$13;
}
}), null);
createRenderEffect(_p$ => {
const _v$ = itemOrientation() === "horizontal" ? tw`flex items-center` : "",
_v$2 = textStyle();
_v$ !== _p$._v$ && className(_el$9, _p$._v$ = _v$);
_p$._v$2 = style(_el$10, _v$2, _p$._v$2);
return _p$;
}, {
_v$: undefined,
_v$2: undefined
});
createRenderEffect(() => _el$12.value = opt());
return _el$9;
})()
}), _el$6);
_el$7.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
setDetectionResolution(null);
setTextDetector(null);
setTranslatorService(null);
setRenderTextOrientation(null);
setTargetLang(null);
setScriptLang(null);
});
insert(_el$7, t("settings.reset"));
return _el$;
})();
};
function formatSize(bytes) {
const k = 1024;
const sizes = ["B", "KB", "MB", "GB", "TB"];
if (bytes === 0) return "0B";
const i = Math.floor(Math.log(bytes) / Math.log(k));
return `${(bytes / k ** i).toFixed(2)}${sizes[i]}`;
}
function formatProgress(loaded, total) {
return `${formatSize(loaded)}/${formatSize(total)}`;
}
function assert(condition, message) {
if (!condition) throw new Error(message);
}
async function resizeToSubmit(blob, suffix) {
const blobUrl = URL.createObjectURL(blob);
const img = await new Promise((resolve, reject) => {
const img2 = new Image();
img2.onload = () => resolve(img2);
img2.onerror = err => reject(err);
img2.src = blobUrl;
});
URL.revokeObjectURL(blobUrl);
const w = img.width;
const h = img.height;
if (w <= 6e3 && h <= 6e3) return {
blob,
suffix
};
const scale = Math.min(6e3 / w, 6e3 / h);
const width = Math.floor(w * scale);
const height = Math.floor(h * scale);
const canvas = document.createElement("canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext("2d");
ctx.imageSmoothingQuality = "high";
ctx.drawImage(img, 0, 0, width, height);
const newBlob = await new Promise((resolve, reject) => {
canvas.toBlob(blob2 => {
if (blob2) resolve(blob2);else reject(new Error("Canvas toBlob failed"));
}, "image/png");
});
console.log(`resized from ${w}x${h}(${formatSize(blob.size)},${suffix}) to ${width}x${height}(${formatSize(newBlob.size)},png)`);
return {
blob: newBlob,
suffix: "png"
};
}
async function submitTranslate(blob, suffix, listeners = {}, optionsOverwrite) {
const {
onProgress
} = listeners;
const formData = new FormData();
formData.append("file", blob, `image.${suffix}`);
formData.append("target_language", targetLang() || BCP47ToISO639(realLang()));
formData.append("detector", optionsOverwrite?.textDetector ?? textDetector());
formData.append("direction", optionsOverwrite?.renderTextOrientation ?? renderTextOrientation());
formData.append("translator", optionsOverwrite?.translator ?? translatorService());
formData.append("size", optionsOverwrite?.detectionResolution ?? detectionResolution());
formData.append("retry", optionsOverwrite?.forceRetry ? "true" : "false");
const result = await GMP.xmlHttpRequest({
method: "POST",
url: "https://api.cotrans.touhou.ai/task/upload/v1",
// @ts-expect-error FormData is supported
data: formData,
upload: {
onprogress: onProgress ? e => {
if (e.lengthComputable) {
const p = formatProgress(e.loaded, e.total);
onProgress(p);
}
} : void 0
}
});
console.log(result.responseText);
return JSON.parse(result.responseText);
}
function getStatusText(msg) {
if (msg.type === "pending") return t("common.status.pending-pos", {
pos: msg.pos
});
if (msg.type === "status") return t(`common.status.${msg.status}`);
return t("common.status.default");
}
function pullTranslationStatus(id, cb) {
const ws = new WebSocket(`wss://api.cotrans.touhou.ai/task/${id}/event/v1`);
return new Promise((resolve, reject) => {
ws.onmessage = e => {
const msg = JSON.parse(e.data);
if (msg.type === "result") resolve(msg.result);else if (msg.type === "error") reject(t("common.status.error-with-id", {
id: msg.error_id
}));else cb(getStatusText(msg));
};
});
}
async function pullTranslationStatusPolling(id, cb) {
while (true) {
const res = await GMP.xmlHttpRequest({
method: "GET",
url: `https://api.cotrans.touhou.ai/task/${id}/status/v1`
});
const msg = JSON.parse(res.responseText);
if (msg.type === "result") return msg.result;else if (msg.type === "error") throw t("common.status.error-with-id", {
id: msg.error_id
});else cb(getStatusText(msg));
await new Promise(resolve => setTimeout(resolve, 1e3));
}
}
async function downloadBlob(url, listeners = {}) {
const {
onProgress
} = listeners;
const res = await GMP.xmlHttpRequest({
method: "GET",
responseType: "blob",
url,
onprogress: onProgress ? e => {
if (e.lengthComputable) {
const p = formatProgress(e.loaded, e.total);
onProgress(p);
}
} : void 0
});
return res.response;
}
const _tmpl$$8 = /*#__PURE__*/template(`<svg viewBox="0 0 32 32" width="1.2em" height="1.2em"><path fill="currentColor" d="M27.85 29H30l-6-15h-2.35l-6 15h2.15l1.6-4h6.85zm-7.65-6l2.62-6.56L25.45 23zM18 7V5h-7V2H9v3H2v2h10.74a14.71 14.71 0 0 1-3.19 6.18A13.5 13.5 0 0 1 7.26 9h-2.1a16.47 16.47 0 0 0 3 5.58A16.84 16.84 0 0 1 3 18l.75 1.86A18.47 18.47 0 0 0 9.53 16a16.92 16.92 0 0 0 5.76 3.84L16 18a14.48 14.48 0 0 1-5.12-3.37A17.64 17.64 0 0 0 14.8 7z">`);
const IconCarbonTranslate = ((props = {}) => (() => {
const _el$ = _tmpl$$8();
spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$7 = /*#__PURE__*/template(`<svg viewBox="0 0 32 32" width="1.2em" height="1.2em"><path fill="currentColor" d="M18 28A12 12 0 1 0 6 16v6.2l-3.6-3.6L1 20l6 6l6-6l-1.4-1.4L8 22.2V16a10 10 0 1 1 10 10Z">`);
const IconCarbonReset = ((props = {}) => (() => {
const _el$ = _tmpl$$7();
spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$6 = /*#__PURE__*/template(`<svg viewBox="0 0 32 32" width="1.2em" height="1.2em"><path fill="currentColor" d="M22 16L12 26l-1.4-1.4l8.6-8.6l-8.6-8.6L12 6z">`);
const IconCarbonChevronRight = ((props = {}) => (() => {
const _el$ = _tmpl$$6();
spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$5 = /*#__PURE__*/template(`<svg viewBox="0 0 32 32" width="1.2em" height="1.2em"><path fill="currentColor" d="M10 16L20 6l1.4 1.4l-8.6 8.6l8.6 8.6L20 26z">`);
const IconCarbonChevronLeft = ((props = {}) => (() => {
const _el$ = _tmpl$$5();
spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$4 = /*#__PURE__*/template(`<svg viewBox="0 0 32 32" width="1.2em" height="1.2em"><path fill="currentColor" d="M16 22L6 12l1.4-1.4l8.6 8.6l8.6-8.6L26 12z">`);
const IconCarbonChevronDown = ((props = {}) => (() => {
const _el$ = _tmpl$$4();
spread(_el$, props, true, true);
return _el$;
})());
const _tmpl$$3 = /*#__PURE__*/template(`<div>`),
_tmpl$2$1 = /*#__PURE__*/template(`<div><div>`),
_tmpl$3$1 = /*#__PURE__*/template(`<div><label><input type="checkbox">`),
_tmpl$4$1 = /*#__PURE__*/template(`<div><div><div><div></div></div></div><div>`),
_tmpl$5$1 = /*#__PURE__*/template(`<div><div></div><div><select>`),
_tmpl$6 = /*#__PURE__*/template(`<option>`),
_tmpl$7 = /*#__PURE__*/template(`<div data-transall="true">`);
function mount$3() {
const images = /* @__PURE__ */new Set();
const instances = new ReactiveMap();
const translatedMap = /* @__PURE__ */new Map();
const translateEnabledMap = /* @__PURE__ */new Map();
function findImageNodes(node) {
return Array.from(node.querySelectorAll("img")).filter(node2 => node2.hasAttribute("srcset") || node2.hasAttribute("data-trans") || node2.parentElement?.classList.contains("sc-1pkrz0g-1") || node2.parentElement?.classList.contains("gtm-expand-full-size-illust"));
}
function rescanImages() {
const imageNodes = findImageNodes(document.body);
const removedImages = new Set(images);
for (const node of imageNodes) {
removedImages.delete(node);
if (images.has(node)) continue;
try {
instances.set(node, createRoot(dispose => {
const instance = createInstance(node);
return {
...instance,
dispose
};
}));
images.add(node);
} catch (e) {}
}
for (const node of removedImages) {
if (!instances.has(node)) continue;
const instance = instances.get(node);
instance.dispose();
instances.delete(node);
images.delete(node);
}
}
function createInstance(imageNode) {
const src = imageNode.getAttribute("src");
const srcset = imageNode.getAttribute("srcset");
const parent = imageNode.parentElement;
if (!parent) throw new Error("no parent");
const originalSrc = parent.getAttribute("href") || src;
const originalSrcSuffix = originalSrc.split(".").pop();
let originalImage;
let translatedImage = translatedMap.get(originalSrc);
const [translateMounted, setTranslateMounted] = createSignal(false);
let buttonDisabled = false;
const [processing, setProcessing] = createSignal(false);
const [translated, setTranslated] = createSignal(false);
const [transStatus, setTransStatus] = createSignal(() => void 0);
parent.style.position = "relative";
const container = document.createElement("div");
parent.appendChild(container);
onCleanup(() => {
container.remove();
});
const disposeButton = render(() => {
const status = createMemo(() => transStatus()());
const [advancedMenuOpen, setAdvancedMenuOpen] = createSignal(false);
const [advDetectRes, setAdvDetectRes] = createSignal(detectionResolution());
const [advRenderTextDir, setAdvRenderTextDir] = createSignal(renderTextOrientation());
const [advTextDetector, setAdvTextDetector] = createSignal(textDetector());
const [advTranslator, setAdvTranslator] = createSignal(translatorService());
const [forceRetry, setForceRetry] = createSignal(false);
const [mouseInside, setMouseInside] = createSignal(false);
let mouseInsideTimeout;
const fullOpacity = createMemo(() => mouseInside() || advancedMenuOpen() || processing());
return (() => {
const _el$ = _tmpl$4$1(),
_el$2 = _el$.firstChild,
_el$3 = _el$2.firstChild,
_el$4 = _el$3.firstChild,
_el$5 = _el$2.nextSibling;
_el$.addEventListener("mouseout", () => {
if (!mouseInsideTimeout) {
mouseInsideTimeout = window.setTimeout(() => {
setMouseInside(false);
mouseInsideTimeout = void 0;
}, 400);
}
});
_el$.addEventListener("mouseover", () => {
if (mouseInsideTimeout) {
window.clearTimeout(mouseInsideTimeout);
mouseInsideTimeout = void 0;
}
setMouseInside(true);
});
_el$.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
});
className(_el$, tw`absolute z-1 flex top-1 left-2 transition-opacity duration-80`);
className(_el$3, tw`relative rounded-full bg-white`);
insert(_el$3, createComponent(Dynamic, {
get component() {
return translated() ? IconCarbonReset : IconCarbonTranslate;
},
"class": tw`w-6 h-6 p-2 align-middle cursor-pointer`,
onClick: e => {
e.stopPropagation();
e.preventDefault();
if (advancedMenuOpen()) return;
toggle();
},
onContextMenu: e => {
e.stopPropagation();
e.preventDefault();
if (translateMounted()) setAdvancedMenuOpen(false);else setAdvancedMenuOpen(v => !v);
}
}), _el$4);
className(_el$4, tw`absolute inset-0 border-1 border-solid rounded-full pointer-events-none`);
className(_el$5, tw`-ml-2 mt-1.5`);
insert(_el$5, createComponent(Show, {
get when() {
return !translateMounted();
},
get children() {
const _el$6 = _tmpl$$3();
className(_el$6, tw`flex flex-col text-base px-1 border-1 border-solid border-gray-300 rounded-2xl bg-white cursor-default`);
insert(_el$6, createComponent(Switch, {
get children() {
return [createComponent(Match, {
get when() {
return status();
},
get children() {
const _el$7 = _tmpl$$3();
className(_el$7, tw`px-1`);
insert(_el$7, status);
return _el$7;
}
}), createComponent(Match, {
get when() {
return advancedMenuOpen();
},
get children() {
return [(() => {
const _el$8 = _tmpl$2$1(),
_el$9 = _el$8.firstChild;
_el$8.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
setAdvancedMenuOpen(false);
});
className(_el$8, tw`flex items-center py-1`);
insert(_el$8, createComponent(IconCarbonChevronLeft, {
"class": tw`align-middle cursor-pointer`
}), _el$9);
insert(_el$9, t("settings.inline-options-title"));
return _el$8;
})(), (() => {
const _el$10 = _tmpl$3$1(),
_el$11 = _el$10.firstChild,
_el$12 = _el$11.firstChild;
className(_el$10, tw`flex flex-col w-48 gap-2 mx-2`);
insert(_el$10, createComponent(For, {
get each() {
return [[t("settings.detection-resolution"), advDetectRes, setAdvDetectRes, detectResOptions, detectResOptionsMap], [t("settings.text-detector"), advTextDetector, setAdvTextDetector, textDetectorOptions, textDetectorOptionsMap], [t("settings.translator"), advTranslator, setAdvTranslator, translatorOptions, translatorOptionsMap], [t("settings.render-text-orientation"), advRenderTextDir, setAdvRenderTextDir, renderTextDirOptions, renderTextDirOptionsMap]];
},
children: ([title, opt, setOpt, opts, optMap]) => (() => {
const _el$14 = _tmpl$5$1(),
_el$15 = _el$14.firstChild,
_el$16 = _el$15.nextSibling,
_el$17 = _el$16.firstChild;
insert(_el$15, title);
className(_el$16, tw`relative px-1`);
_el$17.addEventListener("change", e => {
setOpt(e.target.value);
});
className(_el$17, tw`w-full py-1 appearance-none text-black border-x-0 border-t-0 border-b border-solid border-gray-600 bg-transparent`);
insert(_el$17, createComponent(For, {
each: opts,
children: opt2 => (() => {
const _el$18 = _tmpl$6();
_el$18.value = opt2;
insert(_el$18, () =>
// @ts-expect-error optMap are incompatible with each other
optMap[opt2]());
return _el$18;
})()
}));
insert(_el$16, createComponent(IconCarbonChevronDown, {
"class": tw`absolute top-1 right-1 pointer-events-none`
}), null);
createRenderEffect(() => _el$17.value = opt());
return _el$14;
})()
}), _el$11);
_el$11.addEventListener("click", e => {
e.stopImmediatePropagation();
});
className(_el$11, tw`flex items-center cursor-pointer`);
_el$12.addEventListener("change", e => {
setForceRetry(e.target.checked);
});
_el$12.checked = forceRetry();
insert(_el$11, t("settings.force-retry"), null);
return _el$10;
})(), (() => {
const _el$13 = _tmpl$$3();
_el$13.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
if (buttonDisabled) return;
if (translateMounted()) return;
enable({
detectionResolution: advDetectRes(),
renderTextOrientation: advRenderTextDir(),
textDetector: advTextDetector(),
translator: advTranslator(),
forceRetry: forceRetry()
});
setAdvancedMenuOpen(false);
});
className(_el$13, tw`w-full mt-2 mb-1 py-1 border border-solid border-gray-600 rounded-full text-center cursor-pointer`);
insert(_el$13, t("common.control.translate"));
return _el$13;
})()];
}
}), createComponent(Match, {
when: true,
get children() {
return createComponent(IconCarbonChevronRight, {
"class": tw`py-1 align-middle cursor-pointer`,
onClick: e => {
e.stopPropagation();
e.preventDefault();
setAdvancedMenuOpen(true);
}
});
}
})];
}
}));
return _el$6;
}
}));
createRenderEffect(_p$ => {
const _v$ = {
[tw`opacity-100`]: fullOpacity(),
[tw`opacity-30`]: !fullOpacity()
},
_v$2 = {
[tw`border-x-gray-300 border-b-gray-300 border-t-gray-600 animate-spin`]: processing(),
[tw`border-gray-300`]: !processing()
};
_p$._v$ = classList(_el$, _v$, _p$._v$);
_p$._v$2 = classList(_el$4, _v$2, _p$._v$2);
return _p$;
}, {
_v$: undefined,
_v$2: undefined
});
return _el$;
})();
}, container);
onCleanup(disposeButton);
async function getTranslatedImage(optionsOverwrite) {
if (!optionsOverwrite && translatedImage) return translatedImage;
buttonDisabled = true;
const text = transStatus();
setProcessing(true);
const setStatus = t2 => setTransStatus(() => t2);
setStatus(t("common.source.download-image"));
if (!originalImage) {
const result = await GMP.xmlHttpRequest({
method: "GET",
responseType: "blob",
url: originalSrc,
headers: {
referer: "https://www.pixiv.net/"
},
overrideMimeType: "text/plain; charset=x-user-defined",
onprogress(e) {
if (e.lengthComputable) {
setStatus(t("common.source.download-image-progress", {
progress: formatProgress(e.loaded, e.total)
}));
}
}
}).catch(e => {
setStatus(t("common.source.download-image-error"));
throw e;
});
originalImage = result.response;
}
setStatus(t("common.client.resize"));
await new Promise(resolve => queueMicrotask(resolve));
const {
blob: resizedImage,
suffix: resizedSuffix
} = await resizeToSubmit(originalImage, originalSrcSuffix);
setStatus(t("common.client.submit"));
const task = await submitTranslate(resizedImage, resizedSuffix, {
onProgress(progress) {
setStatus(t("common.client.submit-progress", {
progress
}));
}
}, optionsOverwrite).catch(e => {
setStatus(t("common.client.submit-error"));
throw e;
});
let maskUrl = task.result?.translation_mask;
if (!maskUrl) {
setStatus(t("common.status.pending"));
const res = await pullTranslationStatus(task.id, setStatus).catch(e => {
setStatus(e);
throw e;
});
maskUrl = res.translation_mask;
}
setStatus(t("common.client.download-image"));
const mask = await downloadBlob(maskUrl, {
onProgress(progress) {
setStatus(t("common.client.download-image-progress", {
progress
}));
}
}).catch(e => {
setStatus(t("common.client.download-image-error"));
throw e;
});
const maskUri = URL.createObjectURL(mask);
setStatus(t("common.client.merging"));
const canvas = document.createElement("canvas");
const canvasCtx = canvas.getContext("2d");
const img = new Image();
img.src = URL.createObjectURL(resizedImage);
await new Promise(resolve => {
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
canvasCtx.drawImage(img, 0, 0);
resolve(null);
};
});
const img2 = new Image();
img2.src = maskUri;
img2.crossOrigin = "anonymous";
await new Promise(resolve => {
img2.onload = () => {
canvasCtx.drawImage(img2, 0, 0);
resolve(null);
};
});
const translated2 = await new Promise(resolve => {
canvas.toBlob(blob => {
resolve(blob);
}, "image/png");
});
const translatedUri = URL.createObjectURL(translated2);
translatedImage = translatedUri;
translatedMap.set(originalSrc, translatedUri);
setStatus(text);
setProcessing(false);
buttonDisabled = false;
return translatedUri;
}
async function enable(optionsOverwrite) {
try {
const translated2 = await getTranslatedImage(optionsOverwrite);
imageNode.setAttribute("data-trans", src);
imageNode.setAttribute("src", translated2);
imageNode.removeAttribute("srcset");
setTranslateMounted(true);
setTranslated(true);
} catch (e) {
buttonDisabled = false;
setTranslateMounted(false);
throw e;
}
}
function disable() {
imageNode.setAttribute("src", src);
if (srcset) imageNode.setAttribute("srcset", srcset);
imageNode.removeAttribute("data-trans");
setTranslateMounted(false);
setTranslated(false);
}
function toggle() {
if (buttonDisabled) return;
if (!translateMounted()) {
translateEnabledMap.set(originalSrc, true);
enable();
} else {
translateEnabledMap.delete(originalSrc);
disable();
}
}
if (translateEnabledMap.get(originalSrc)) enable();
onCleanup(() => {
if (translateMounted()) disable();
});
return {
imageNode,
async enable() {
translateEnabledMap.set(originalSrc, true);
return await enable();
},
disable() {
translateEnabledMap.delete(originalSrc);
return disable();
},
isEnabled: createMemo(() => processing() || translateMounted())
};
}
const TranslateAll = () => {
const [started, setStarted] = createSignal(false);
const [total, setTotal] = createSignal(0);
const [finished, setFinished] = createSignal(0);
const [erred, setErred] = createSignal(false);
return (() => {
const _el$19 = _tmpl$7();
_el$19.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
if (started()) return;
setStarted(true);
setTotal(instances.size);
const inc = () => {
setFinished(finished() + 1);
};
const err = () => {
setErred(true);
inc();
};
for (const instance of instances.values()) {
if (instance.isEnabled()) inc();else instance.enable().then(inc).catch(err);
}
});
className(_el$19, tw`inline-block mr-3 p-0 h-8 text-inherit leading-8 font-bold cursor-pointer`);
insert(_el$19, createComponent(Switch, {
get children() {
return [createComponent(Match, {
get when() {
return !started();
},
get children() {
return t("common.control.batch", {
count: instances.size
})();
}
}), createComponent(Match, {
get when() {
return finished() !== total();
},
get children() {
return t("common.batch.progress", {
count: finished(),
total: total()
})();
}
}), createComponent(Match, {
get when() {
return finished() === total();
},
get children() {
return createComponent(Show, {
get when() {
return !erred();
},
get fallback() {
return t("common.batch.error")();
},
get children() {
return t("common.batch.finish")();
}
});
}
})];
}
}));
return _el$19;
})();
};
let disposeTransAll;
function refreshTransAll() {
if (document.querySelector(".sc-emr523-2")) return;
const section = document.querySelector(".sc-181ts2x-0");
if (section) {
if (section.querySelector("[data-transall]")) return;
const container = document.createElement("div");
section.appendChild(container);
const dispose = render(() => createComponent(TranslateAll, {}), container);
disposeTransAll = () => {
dispose();
container.remove();
};
} else {
if (disposeTransAll) {
disposeTransAll();
disposeTransAll = void 0;
}
}
}
onCleanup(() => {
disposeTransAll?.();
});
let disposeMangaViewerTransAll;
function refreshManagaViewerTransAll() {
const mangaViewer = document.querySelector(".gtm-manga-viewer-change-direction")?.parentElement?.parentElement;
if (mangaViewer) {
if (disposeMangaViewerTransAll) return;
const container = document.createElement("div");
mangaViewer.prepend(container);
const dispose = render(() => createComponent(TranslateAll, {}), container);
disposeMangaViewerTransAll = () => {
dispose();
container.remove();
};
} else {
if (disposeMangaViewerTransAll) {
disposeMangaViewerTransAll();
disposeMangaViewerTransAll = void 0;
}
}
}
onCleanup(() => {
disposeMangaViewerTransAll?.();
});
createMutationObserver(document.body, {
childList: true,
subtree: true
}, throttle(() => {
rescanImages();
refreshTransAll();
refreshManagaViewerTransAll();
}, 200));
rescanImages();
refreshTransAll();
onCleanup(() => {
images.clear();
instances.forEach(instance => instance.dispose());
instances.clear();
});
return {};
}
const translator$1 = {
match(url) {
return url.hostname.endsWith("pixiv.net") && url.pathname.match(/\/artworks\//);
},
mount: mount$3
};
const _tmpl$$2 = /*#__PURE__*/template(`<div><h2></h2><div>`);
function mount$2() {
const wrapper = document.getElementById("wrapper");
if (!wrapper) return {};
const adFooter = wrapper.querySelector(".ad-footer");
if (!adFooter) return {};
const settingsContainer = document.createElement("div");
onCleanup(() => {
settingsContainer.remove();
});
const disposeSettings = render(() => (() => {
const _el$ = _tmpl$$2(),
_el$2 = _el$.firstChild,
_el$3 = _el$2.nextSibling;
className(_el$, tw`mb-2.5 pt-2.5 px-5 pb-4 bg-white border border-solid border-[#d6dee5]`);
className(_el$2, tw`text-lg font-bold`);
insert(_el$2, t("settings.title"));
className(_el$3, tw`w-[665px] my-2.5 mx-auto`);
insert(_el$3, createComponent(Settings, {
itemOrientation: "horizontal",
textStyle: {
"width": "185px",
"font-weight": "bold"
}
}));
return _el$;
})(), settingsContainer);
onCleanup(disposeSettings);
wrapper.insertBefore(settingsContainer, adFooter);
return {};
}
const settingsInjector$1 = {
match(url) {
return url.hostname.endsWith("pixiv.net") && url.pathname.match(/\/setting_user\.php/);
},
mount: mount$2
};
const $RAW = Symbol("store-raw"),
$NODE = Symbol("store-node");
function wrap$1(value) {
let p = value[$PROXY];
if (!p) {
Object.defineProperty(value, $PROXY, {
value: p = new Proxy(value, proxyTraps$1)
});
if (!Array.isArray(value)) {
const keys = Object.keys(value),
desc = Object.getOwnPropertyDescriptors(value);
for (let i = 0, l = keys.length; i < l; i++) {
const prop = keys[i];
if (desc[prop].get) {
Object.defineProperty(value, prop, {
enumerable: desc[prop].enumerable,
get: desc[prop].get.bind(p)
});
}
}
}
}
return p;
}
function isWrappable(obj) {
let proto;
return obj != null && typeof obj === "object" && (obj[$PROXY] || !(proto = Object.getPrototypeOf(obj)) || proto === Object.prototype || Array.isArray(obj));
}
function unwrap(item, set = new Set()) {
let result, unwrapped, v, prop;
if (result = item != null && item[$RAW]) return result;
if (!isWrappable(item) || set.has(item)) return item;
if (Array.isArray(item)) {
if (Object.isFrozen(item)) item = item.slice(0);else set.add(item);
for (let i = 0, l = item.length; i < l; i++) {
v = item[i];
if ((unwrapped = unwrap(v, set)) !== v) item[i] = unwrapped;
}
} else {
if (Object.isFrozen(item)) item = Object.assign({}, item);else set.add(item);
const keys = Object.keys(item),
desc = Object.getOwnPropertyDescriptors(item);
for (let i = 0, l = keys.length; i < l; i++) {
prop = keys[i];
if (desc[prop].get) continue;
v = item[prop];
if ((unwrapped = unwrap(v, set)) !== v) item[prop] = unwrapped;
}
}
return item;
}
function getDataNodes(target) {
let nodes = target[$NODE];
if (!nodes) Object.defineProperty(target, $NODE, {
value: nodes = Object.create(null)
});
return nodes;
}
function getDataNode(nodes, property, value) {
return nodes[property] || (nodes[property] = createDataNode(value));
}
function proxyDescriptor$1(target, property) {
const desc = Reflect.getOwnPropertyDescriptor(target, property);
if (!desc || desc.get || !desc.configurable || property === $PROXY || property === $NODE) return desc;
delete desc.value;
delete desc.writable;
desc.get = () => target[$PROXY][property];
return desc;
}
function trackSelf(target) {
if (getListener()) {
const nodes = getDataNodes(target);
(nodes._ || (nodes._ = createDataNode()))();
}
}
function ownKeys(target) {
trackSelf(target);
return Reflect.ownKeys(target);
}
function createDataNode(value) {
const [s, set] = createSignal(value, {
equals: false,
internal: true
});
s.$ = set;
return s;
}
const proxyTraps$1 = {
get(target, property, receiver) {
if (property === $RAW) return target;
if (property === $PROXY) return receiver;
if (property === $TRACK) {
trackSelf(target);
return receiver;
}
const nodes = getDataNodes(target);
const tracked = nodes[property];
let value = tracked ? tracked() : target[property];
if (property === $NODE || property === "__proto__") return value;
if (!tracked) {
const desc = Object.getOwnPropertyDescriptor(target, property);
if (getListener() && (typeof value !== "function" || target.hasOwnProperty(property)) && !(desc && desc.get)) value = getDataNode(nodes, property, value)();
}
return isWrappable(value) ? wrap$1(value) : value;
},
has(target, property) {
if (property === $RAW || property === $PROXY || property === $TRACK || property === $NODE || property === "__proto__") return true;
this.get(target, property, target);
return property in target;
},
set() {
return true;
},
deleteProperty() {
return true;
},
ownKeys: ownKeys,
getOwnPropertyDescriptor: proxyDescriptor$1
};
function setProperty(state, property, value, deleting = false) {
if (!deleting && state[property] === value) return;
const prev = state[property],
len = state.length;
if (value === undefined) delete state[property];else state[property] = value;
let nodes = getDataNodes(state),
node;
if (node = getDataNode(nodes, property, prev)) node.$(() => value);
if (Array.isArray(state) && state.length !== len) (node = getDataNode(nodes, "length", len)) && node.$(state.length);
(node = nodes._) && node.$();
}
function mergeStoreNode(state, value) {
const keys = Object.keys(value);
for (let i = 0; i < keys.length; i += 1) {
const key = keys[i];
setProperty(state, key, value[key]);
}
}
function updateArray(current, next) {
if (typeof next === "function") next = next(current);
next = unwrap(next);
if (Array.isArray(next)) {
if (current === next) return;
let i = 0,
len = next.length;
for (; i < len; i++) {
const value = next[i];
if (current[i] !== value) setProperty(current, i, value);
}
setProperty(current, "length", len);
} else mergeStoreNode(current, next);
}
function updatePath(current, path, traversed = []) {
let part,
prev = current;
if (path.length > 1) {
part = path.shift();
const partType = typeof part,
isArray = Array.isArray(current);
if (Array.isArray(part)) {
for (let i = 0; i < part.length; i++) {
updatePath(current, [part[i]].concat(path), traversed);
}
return;
} else if (isArray && partType === "function") {
for (let i = 0; i < current.length; i++) {
if (part(current[i], i)) updatePath(current, [i].concat(path), traversed);
}
return;
} else if (isArray && partType === "object") {
const {
from = 0,
to = current.length - 1,
by = 1
} = part;
for (let i = from; i <= to; i += by) {
updatePath(current, [i].concat(path), traversed);
}
return;
} else if (path.length > 1) {
updatePath(current[part], path, [part].concat(traversed));
return;
}
prev = current[part];
traversed = [part].concat(traversed);
}
let value = path[0];
if (typeof value === "function") {
value = value(prev, traversed);
if (value === prev) return;
}
if (part === undefined && value == undefined) return;
value = unwrap(value);
if (part === undefined || isWrappable(prev) && isWrappable(value) && !Array.isArray(value)) {
mergeStoreNode(prev, value);
} else setProperty(current, part, value);
}
function createStore(...[store, options]) {
const unwrappedStore = unwrap(store || {});
const isArray = Array.isArray(unwrappedStore);
const wrappedStore = wrap$1(unwrappedStore);
function setStore(...args) {
batch(() => {
isArray && args.length === 1 ? updateArray(unwrappedStore, args[0]) : updatePath(unwrappedStore, args);
});
}
return [wrappedStore, setStore];
}
const _tmpl$$1 = /*#__PURE__*/template(`<div>`),
_tmpl$2 = /*#__PURE__*/template(`<div><div>`),
_tmpl$3 = /*#__PURE__*/template(`<div><label><input type="checkbox">`),
_tmpl$4 = /*#__PURE__*/template(`<div><div></div><div><select>`),
_tmpl$5 = /*#__PURE__*/template(`<option>`);
function mount$1() {
const mountAuthorId = location.pathname.split("/", 2)[1];
const [statusId, setStatusId] = createSignal(location.pathname.match(/\/status\/(\d+)/)?.[1]);
const [translatedMap, setTranslatedMap] = createStore({});
const [translateStatusMap, setTranslateStatusMap] = createStore({});
const [translateEnabledMap, setTranslateEnabledMap] = createStore({});
const originalImageMap = {};
const [layers, setLayers] = createSignal(null);
let dialog;
const createDialog = () => {
const [active, setActive] = createSignal(0);
const buttonParent = dialog.querySelector('[aria-labelledby="modal-header"][role="dialog"]').firstElementChild.firstElementChild;
const getImages = () => {
try {
const cont = buttonParent.firstElementChild;
assert(cont.nodeName === "DIV");
const ul = cont.firstElementChild.firstElementChild.nextElementSibling.firstElementChild.firstElementChild;
assert(ul.nodeName === "UL");
const images2 = [];
let li = ul.firstElementChild;
do {
const img = li.firstElementChild.firstElementChild.firstElementChild.firstElementChild.lastElementChild;
assert(img.nodeName === "IMG");
images2.push(img);
} while (li = li.nextElementSibling);
return images2;
} catch (e) {
return [].slice.call(buttonParent.firstElementChild.querySelectorAll("img"));
}
};
const [images, setImages] = createSignal(getImages(), {
equals: (a, b) => a.length === b.length && a.every((img, i) => img === b[i])
});
const currentImg = createMemo(() => {
const img = images()[active()];
if (!img) return void 0;
return img.getAttribute("data-transurl") || img.src;
});
createEffect(() => {
for (const img of images()) {
const div = img.previousSibling;
if (img.hasAttribute("data-transurl")) {
const transurl = img.getAttribute("data-transurl");
if (!translateEnabledMap[transurl]) {
if (div) div.style.backgroundImage = `url("${transurl}")`;
img.src = transurl;
img.removeAttribute("data-transurl");
}
} else if (translateEnabledMap[img.src] && translatedMap[img.src]) {
const ori = img.src;
img.setAttribute("data-transurl", ori);
img.src = translatedMap[ori];
if (div) div.style.backgroundImage = `url("${translatedMap[ori]}")`;
}
}
});
const getTranslatedImage = async (url, optionsOverwrite) => {
if (!optionsOverwrite && translatedMap[url]) return translatedMap[url];
const setStatus = t2 => setTranslateStatusMap(url, () => t2);
setStatus(t("common.source.download-image"));
if (!originalImageMap[url]) {
const result = await GMP.xmlHttpRequest({
method: "GET",
responseType: "blob",
url,
headers: {
referer: "https://twitter.com/"
},
overrideMimeType: "text/plain; charset=x-user-defined",
onprogress(e) {
if (e.lengthComputable) {
setStatus(t("common.source.download-image-progress", {
progress: formatProgress(e.loaded, e.total)
}));
}
}
}).catch(e => {
setStatus(t("common.source.download-image-error"));
throw e;
});
originalImageMap[url] = result.response;
}
const originalImage = originalImageMap[url];
const originalSrcSuffix = new URL(url).searchParams.get("format") || url.split(".")[1] || "jpg";
setStatus(t("common.client.resize"));
await new Promise(resolve => queueMicrotask(resolve));
const {
blob: resizedImage,
suffix: resizedSuffix
} = await resizeToSubmit(originalImage, originalSrcSuffix);
setStatus(t("common.client.submit"));
const task = await submitTranslate(resizedImage, resizedSuffix, {
onProgress(progress) {
setStatus(t("common.client.submit-progress", {
progress
}));
}
}, optionsOverwrite).catch(e => {
setStatus(t("common.client.submit-error"));
throw e;
});
let maskUrl = task.result?.translation_mask;
if (!maskUrl) {
setStatus(t("common.status.pending"));
const res = await pullTranslationStatusPolling(task.id, setStatus).catch(e => {
setStatus(e);
throw e;
});
maskUrl = res.translation_mask;
}
setStatus(t("common.client.download-image"));
const mask = await downloadBlob(maskUrl, {
onProgress(progress) {
t("common.client.download-image-progress", {
progress
});
}
}).catch(e => {
setStatus(t("common.client.download-image-error"));
throw e;
});
const maskUri = URL.createObjectURL(mask);
setStatus(t("common.client.merging"));
const canvas = document.createElement("canvas");
const canvasCtx = canvas.getContext("2d");
const img = new Image();
img.src = URL.createObjectURL(resizedImage);
await new Promise(resolve => {
img.onload = () => {
canvas.width = img.width;
canvas.height = img.height;
canvasCtx.drawImage(img, 0, 0);
resolve(null);
};
});
const img2 = new Image();
img2.src = maskUri;
img2.crossOrigin = "anonymous";
await new Promise(resolve => {
img2.onload = () => {
canvasCtx.drawImage(img2, 0, 0);
resolve(null);
};
});
const translated = await new Promise(resolve => {
canvas.toBlob(blob => {
resolve(blob);
}, "image/png");
});
const translatedUri = URL.createObjectURL(translated);
setTranslatedMap(url, translatedUri);
setStatus(() => "");
return translatedUri;
};
const enable = async (url, optionsOverwrite) => {
await getTranslatedImage(url, optionsOverwrite);
setTranslateEnabledMap(url, true);
};
const disable = url => {
setTranslateEnabledMap(url, false);
};
const isEnabled = createMemo(() => {
const img = currentImg();
return img ? !!translateEnabledMap[img] : false;
});
const transStatus = createMemo(() => {
const img = currentImg();
return img ? translateStatusMap[img]?.() : "";
});
const isProcessing = createMemo(() => !!transStatus());
const [advancedMenuOpen, setAdvancedMenuOpen] = createSignal(false);
const referenceEl = buttonParent.children[2];
const container = referenceEl.cloneNode(true);
container.style.top = "48px";
createEffect(() => {
container.style.display = currentImg() ? "flex" : "none";
container.style.alignItems = advancedMenuOpen() ? "start" : "center";
});
container.style.flexDirection = "row";
container.style.flexWrap = "nowrap";
const child = container.firstChild;
const referenceChild = referenceEl.firstChild;
const [backgroundColor, setBackgroundColor] = createSignal(referenceChild.style.backgroundColor);
buttonParent.appendChild(container);
const submitTranslateTest = () => {
const img = currentImg();
return img && !translateStatusMap[img]?.();
};
container.onclick = e => {
e.stopPropagation();
if (advancedMenuOpen()) return;
if (!submitTranslateTest()) return;
if (isEnabled()) disable(currentImg());else enable(currentImg());
};
container.oncontextmenu = e => {
e.preventDefault();
e.stopPropagation();
if (isEnabled()) setAdvancedMenuOpen(false);else setAdvancedMenuOpen(v => !v);
};
const spinnerContainer = container.firstChild;
const disposeProcessingSpinner = render(() => createComponent(Show, {
get when() {
return isProcessing();
},
get children() {
const _el$ = _tmpl$$1();
className(_el$, tw`absolute inset-0 border-1 border-solid border-x-transparent border-b-transparent border-t-gray-400 rounded-full animate-spin`);
return _el$;
}
}), spinnerContainer);
onCleanup(disposeProcessingSpinner);
const svg = container.querySelector("svg");
const svgParent = svg.parentElement;
const buttonIconContainer = document.createElement("div");
svgParent.insertBefore(buttonIconContainer, svg);
svg.remove();
const disposeButtonIcon = render(() => createComponent(Dynamic, {
get component() {
return isEnabled() ? IconCarbonReset : IconCarbonTranslate;
},
"class": tw`w-5 h-5 mt-1`
}), buttonIconContainer);
onCleanup(disposeButtonIcon);
const buttonStatusContainer = document.createElement("div");
container.insertBefore(buttonStatusContainer, container.firstChild);
const disposeButtonStatus = render(() => {
const status = createMemo(() => transStatus());
const [advDetectRes, setAdvDetectRes] = createSignal(detectionResolution());
const [advRenderTextDir, setAdvRenderTextDir] = createSignal(renderTextOrientation());
const [advTextDetector, setAdvTextDetector] = createSignal(textDetector());
const [advTranslator, setAdvTranslator] = createSignal(translatorService());
const [forceRetry, setForceRetry] = createSignal(false);
createEffect(prev => {
const img = currentImg();
if (prev !== img) {
setAdvDetectRes(detectionResolution());
setAdvRenderTextDir(renderTextOrientation());
}
return img;
});
return (() => {
const _el$2 = _tmpl$$1();
className(_el$2, tw`flex flex-col -mr-3 pl-1 pr-2 text-white rounded-2xl cursor-default`);
insert(_el$2, createComponent(Switch, {
get children() {
return [createComponent(Match, {
get when() {
return status();
},
get children() {
const _el$3 = _tmpl$$1();
className(_el$3, tw`px-2 py-1`);
insert(_el$3, status);
return _el$3;
}
}), createComponent(Match, {
get when() {
return createMemo(() => !!currentImg())() && !translateEnabledMap[currentImg()];
},
get children() {
return createComponent(Show, {
get when() {
return advancedMenuOpen();
},
get fallback() {
return createComponent(IconCarbonChevronLeft, {
"class": tw`py-1 align-middle cursor-pointer`,
onClick: e => {
e.stopPropagation();
setAdvancedMenuOpen(true);
}
});
},
get children() {
return [(() => {
const _el$4 = _tmpl$2(),
_el$5 = _el$4.firstChild;
_el$4.addEventListener("click", e => {
e.stopPropagation();
setAdvancedMenuOpen(false);
});
className(_el$4, tw`flex justify-between items-center pl-2 py-1`);
className(_el$5, tw`text-lg`);
insert(_el$5, t("settings.inline-options-title"));
insert(_el$4, createComponent(IconCarbonChevronRight, {
"class": tw`align-middle cursor-pointer`
}), null);
return _el$4;
})(), (() => {
const _el$6 = _tmpl$3(),
_el$7 = _el$6.firstChild,
_el$8 = _el$7.firstChild;
className(_el$6, tw`flex flex-col w-48 gap-2 ml-2`);
insert(_el$6, createComponent(For, {
get each() {
return [[t("settings.detection-resolution"), advDetectRes, setAdvDetectRes, detectResOptions, detectResOptionsMap], [t("settings.text-detector"), advTextDetector, setAdvTextDetector, textDetectorOptions, textDetectorOptionsMap], [t("settings.translator"), advTranslator, setAdvTranslator, translatorOptions, translatorOptionsMap], [t("settings.render-text-orientation"), advRenderTextDir, setAdvRenderTextDir, renderTextDirOptions, renderTextDirOptionsMap]];
},
children: ([title, opt, setOpt, opts, optMap]) => (() => {
const _el$10 = _tmpl$4(),
_el$11 = _el$10.firstChild,
_el$12 = _el$11.nextSibling,
_el$13 = _el$12.firstChild;
insert(_el$11, title);
className(_el$12, tw`relative px-1`);
_el$13.addEventListener("change", e => {
setOpt(e.target.value);
});
className(_el$13, tw`w-full py-1 appearance-none text-white border-x-0 border-t-0 border-b border-solid border-gray-300 bg-transparent`);
insert(_el$13, createComponent(For, {
each: opts,
children: opt2 => (() => {
const _el$14 = _tmpl$5();
_el$14.value = opt2;
insert(_el$14, () =>
// @ts-expect-error optMap are incompatible with each other
optMap[opt2]());
return _el$14;
})()
}));
insert(_el$12, createComponent(IconCarbonChevronDown, {
"class": tw`absolute top-1 right-1 pointer-events-none`
}), null);
createRenderEffect(() => _el$13.value = opt());
return _el$10;
})()
}), _el$7);
className(_el$7, tw`flex items-center cursor-pointer`);
_el$8.addEventListener("change", e => {
setForceRetry(e.target.checked);
});
_el$8.checked = forceRetry();
insert(_el$7, t("settings.force-retry"), null);
return _el$6;
})(), (() => {
const _el$9 = _tmpl$$1();
_el$9.addEventListener("click", e => {
e.stopPropagation();
e.preventDefault();
if (!submitTranslateTest()) return;
if (translateEnabledMap[currentImg()]) return;
enable(currentImg(), {
detectionResolution: advDetectRes(),
renderTextOrientation: advRenderTextDir(),
textDetector: advTextDetector(),
translator: advTranslator(),
forceRetry: forceRetry()
});
setAdvancedMenuOpen(false);
});
className(_el$9, tw`w-full mt-2 mb-1 py-1 border border-solid border-white rounded-full text-center cursor-pointer`);
insert(_el$9, t("common.control.translate"));
return _el$9;
})()];
}
});
}
})];
}
}));
createRenderEffect(() => backgroundColor() != null ? _el$2.style.setProperty("background-color", backgroundColor()) : _el$2.style.removeProperty("background-color"));
return _el$2;
})();
}, buttonStatusContainer);
onCleanup(disposeButtonStatus);
onCleanup(() => {
container.remove();
for (const img of images()) {
if (img.hasAttribute("data-transurl")) {
const transurl = img.getAttribute("data-transurl");
img.src = transurl;
img.removeAttribute("data-transurl");
}
}
setImages([]);
});
return {
setActive,
update() {
if (referenceChild.style.backgroundColor) setBackgroundColor(child.style.backgroundColor = referenceChild.style.backgroundColor);
setImages(getImages());
}
};
};
let dialogInstance;
const rescanLayers = () => {
const [newDialog] = Array.from(layers().children).filter(el => el.querySelector('[aria-labelledby="modal-header"][role="dialog"]')?.firstChild?.firstChild?.childNodes[2]);
if (newDialog !== dialog || !newDialog) {
dialogInstance?.dispose();
dialogInstance = void 0;
dialog = newDialog;
if (!dialog) return;
dialogInstance = createRoot(dispose => {
const dialog2 = createDialog();
return {
...dialog2,
dispose
};
});
}
const newIndex = Number(location.pathname.match(/\/status\/\d+\/photo\/(\d+)/)?.[1]) - 1;
dialogInstance.setActive(newIndex);
dialogInstance.update();
};
onCleanup(() => {
dialogInstance?.dispose();
});
let stopLayersObserver;
const onLayersUpdate = () => {
stopLayersObserver?.();
const [, {
stop
}] = createMutationObserver(() => layers(), {
childList: true,
subtree: true
}, throttle(() => rescanLayers(), 200));
stopLayersObserver = stop;
rescanLayers();
};
createEffect(prev => {
const id = statusId();
if (!id) stopLayersObserver?.();
if (id && id !== prev) {
const layers2 = document.getElementById("layers");
setLayers(layers2);
if (layers2) {
onLayersUpdate();
} else {
const [, {
stop
}] = createMutationObserver(document.body, {
childList: true,
subtree: true
}, throttle(() => {
const layers3 = document.getElementById("layers");
setLayers(layers3);
if (layers3) {
onLayersUpdate();
stop();
}
}, 200));
}
}
return id;
});
return {
canKeep(url) {
switch (keepInstances()) {
case "until-reload":
return url.startsWith("https://twitter.com/");
case "until-navigate":
return url.startsWith(`https://twitter.com/${mountAuthorId}`);
default:
return false;
}
},
onURLChange(url) {
setStatusId(url.match(/\/status\/(\d+)/)?.[1]);
}
};
}
const translator = {
// https://twitter.com/<user>/status/<id>
match(url) {
return url.hostname.endsWith("twitter.com") && url.pathname.match(/\/status\//);
},
mount: mount$1
};
const _tmpl$ = /*#__PURE__*/template(`<div><div><h2>`);
function mount() {
let settingsTab;
let disposeText;
const checkTab = () => {
const tablist = document.querySelector('[role="tablist"]') || document.querySelector('[data-testid="loggedOutPrivacySection"]');
if (!tablist) {
if (disposeText) {
disposeText();
disposeText = void 0;
}
return;
}
if (tablist.querySelector(`div[data-imgtrans-settings-${EDITION}]`)) return;
const inactiveRefrenceEl = Array.from(tablist.children).find(el => el.children.length < 2 && el.querySelector("a"));
if (!inactiveRefrenceEl) return;
settingsTab = inactiveRefrenceEl.cloneNode(true);
settingsTab.setAttribute(`data-imgtrans-settings-${EDITION}`, "true");
const textEl = settingsTab.querySelector("span");
if (textEl) {
while (textEl.firstChild) textEl.removeChild(textEl.firstChild);
disposeText = render(() => t("settings.title")(), textEl);
onCleanup(disposeText);
}
const linkEl = settingsTab.querySelector("a");
if (linkEl) linkEl.href = `/settings/__imgtrans_${EDITION}`;
tablist.appendChild(settingsTab);
};
let disposeSettings;
const checkSettings = () => {
const section = document.querySelector('[data-testid="error-detail"]')?.parentElement?.parentElement;
if (!section?.querySelector(`[data-imgtrans-settings-${EDITION}-section]`)) {
if (disposeSettings) {
disposeSettings();
disposeSettings = void 0;
}
if (!section) return;
}
const title = `${t("settings.title")()} / Twitter`;
if (document.title !== title) document.title = title;
if (disposeSettings) return;
const errorPage = section.firstChild;
errorPage.style.display = "none";
const settingsContainer = document.createElement("div");
settingsContainer.setAttribute(`data-imgtrans-settings-${EDITION}-section`, "true");
section.appendChild(settingsContainer);
const disposeSettingsApp = render(() => {
onCleanup(() => {
errorPage.style.display = "";
});
return (// r-37j5jr: twitter font
(() => {
const _el$ = _tmpl$(),
_el$2 = _el$.firstChild,
_el$3 = _el$2.firstChild;
className(_el$, tw`px-4 r-37j5jr`);
className(_el$2, tw`flex items-center h-14`);
className(_el$3, tw`text-xl leading-6`);
insert(_el$3, t("settings.title"));
insert(_el$, createComponent(Settings, {}), null);
return _el$;
})()
);
}, settingsContainer);
disposeSettings = () => {
disposeSettingsApp();
settingsContainer.remove();
};
onCleanup(disposeSettings);
};
createMutationObserver(document.body, {
childList: true,
subtree: true
}, throttle(() => {
if (!location.pathname.startsWith("/settings")) return;
if (location.pathname === "/settings/profile") return;
checkTab();
if (location.pathname.match(`/settings/__imgtrans_${EDITION}`)) {
if (settingsTab && settingsTab.children.length < 2) {
settingsTab.style.backgroundColor = "#F7F9F9";
const activeIndicator = document.createElement("div");
activeIndicator.className = tw`absolute z-10 inset-0 border-y-0 border-l-0 border-r-2 border-solid border-[#1D9Bf0] pointer-events-none`;
settingsTab.appendChild(activeIndicator);
}
checkSettings();
} else {
if (settingsTab && settingsTab.children.length > 1) {
settingsTab.style.backgroundColor = "";
settingsTab.removeChild(settingsTab.lastChild);
}
if (disposeSettings) {
disposeSettings();
disposeSettings = void 0;
}
}
}, 200));
return {
canKeep(url) {
return url.includes("twitter.com") && url.includes("/settings");
}
};
}
const settingsInjector = {
match(url) {
return url.hostname.endsWith("twitter.com") && (url.pathname === "/settings" || url.pathname.match(/^\/settings\//)) && url.pathname !== "/settings/profile";
},
mount
};
start([translator$1, translator], [settingsInjector$1, settingsInjector]);
})();
/*
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
*/
/*
MIT License
Copyright (c) 2021 Solid Primitives Working Group
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
MIT License
Copyright (c) 2016-2023 Ryan Carniato
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
MIT License
Copyright (c) 2021 [these people](https://github.com/tw-in-js/twind/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
Copyright (c) 2017-2018 Fredrik Nicol
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
MIT License Copyright (c) 2023 Alexis Munsayac <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*
Copyright 2010, 2011, Chris Winberry <[email protected]>. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
*/
/*
The MIT License (MIT)
Copyright (c) 2020-2022 Kristóf Poduszló
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/*
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
License
(The MIT License)
Copyright (c) 2014 The cheeriojs contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/